Unit-1 Oracle Introduction & Fundametal Commands
Unit-1 Oracle Introduction & Fundametal Commands
• First, you can start a database instance without having it accessing any database
files. This is how you create a database, starting an instance first and creating the
database from within the instance.
• Second, an instance can access only one database at a time. When you start an
instance, the next step is to mount that instance to a database. And an instance can
mount only one database at a single point in time.
• Third, multiple database instances can access the same database. In a clustering
environment, many instances on several servers can access a central database to
enable high availability and scalability.
• Finally, a database can exist without an instance. However, it would be unusable
because it is just a set of files.
Physical storage structures
The physical storage structures are simply files that store data.
When you execute a CREATE DATABASE statement to create a new database, Oracle creates
the following files:
• Data files: data files contain real data, e.g., sales order and customer data. The data
of logical database structures such as tables and indexes are physically stored in the
data files.
• Control files: every database has a control file that contains metadata. The metadata
describes the physical structure of the database including the database name and the
locations of data files.
• Online redo log files: every database has an online redo log that consists of two or
more online redo log files. An online redo log is made up of redo entries that record
all changes made to the data.
Besides these files, an Oracle database includes other important files such as parameter files,
network files, backup files, and archived redo log files for backup and recovery.
The following picture illustrates segments, extents and data blocks within a tablespace:
And the next figure shows the relationship between logical and physical storage structures:
The SGA is a shared memory structure allocated when the instance started up and released
when it is shut down. The SGA is a group of shared memory structures that contain data and
control information for one database instance.
Different from the SGA, which is available to all processes, PGA is a private memory area
allocated to each session when the session started and released when the session ends.
• LGWR is the log writer process which is the key to the recoverability architecture.
Every change occurs in the database is written out to a file called redo log for recovery
purposes. And these changes are written and logged by LGWR process. The LGWR
process first writes the changes to memory and then disk as redo logs which then can
be used for recovery.
• ARCn is the archiver process that copies the content of redo logs to archive redo log
files. The archiver process can have multiple processes such as ARC0, ARC1, and ARC3,
which allow the archiver to write to various destinations such as D: drive, E drive or
other storage.
• MMON is the manageability monitor process that gathers performance metrics.
• MMAN is the memory manager that automatically manages memory in an Oracle
database.
• LREG is the listener registration process that registers information on the database
instance and dispatcher processes with the Oracle Net Listener.
SQL * Plus
• SQL * Plus is a tool that allows you to interact directly with the Oracle database.
• SQL * Plus is an Oracle command line utility that allows users to interactively execute
SQL and PL/SQL commands.
• SQL * Plus enables you to manipulate blocks of SQL and PL / SQL formatting the query
results, to copy data between tables and to execute SQL and PL / SQL.
DESCRIBE Command
Lists the column definitions for the specified table, view, or synonym or the specifications for
the specified function procedure.
Syntax:
DESCRIBE table_name
DESCRIBE view_name
DESCRIBE package_name
Example:
DESCRIBE employee
Lists all columns along with data types and other details.
LIST Command
Lists one or more lines of the buffer.
Term Description
n Lists line n.
nm Lists lines n through m.
n* Lists line n through the current line.
n LAST Lists line n through the last line.
* Lists the current line.
*n Lists the current line through line n.
* LAST Lists the current line through the last line.
LAST Lists the last line.
Syntax:
LIST n | n m | n* …
Example:
SQL> LIST 3
APPEND Command
Adds specified text to the end of the current line in the SQL buffer. To separate text from
the preceding characters with a space, enter two spaces between APPEND and text.
To APPEND text that ends with a semicolon, end the command with two semicolons (SQL*Plus
interprets a single semicolon as an optional command terminator).
Syntax:
APPEND text
where text represents the text to append.
Example
CHANGE Command
Changes text on the current line in the buffer.
Syntax:
CHANGE /old/new/
INPUT Command
Adds one or more new lines after the current line in the buffer.
To add a single line, enter the text of the line after the command INPUT, separating the text
from the command with a space. To begin the line with one or more spaces, enter two or
more spaces between INPUT and the first non-blank character of text.
To add several lines, enter INPUT with no text. INPUT prompts you for each line. To leave
INPUT, enter a null (empty) line or a period.
Syntax:
INPUT [text]
DEL Command
Deletes one more lines of the buffer.
Term Description
n Deletes line n.
nm Deletes lines n through m.
n* Deletes line n through the current line.
n LAST Deletes line n through the last line.
* Deletes the current line.
*n Deletes the current line through line n.
* LAST Deletes the current line through the last line.
LAST Deletes the last line.
Syntax:
DEL n | n m | n* …
Syntax:
CLEAR BUFFER
Accepting Values at Runtime
To read the user input and store it in a variable, for later use, you can use SQL*Plus
command ACCEPT.
Syntax:
ACCEPT <your variable> <variable type if needed [number|char|date]>
prompt 'message'
Example:
CHAR(size) It is used to store character data within the predefined length. It can be
stored up to 2000 bytes.
NCHAR(size) It is used to store national character data within the predefined length. It can
be stored up to 2000 bytes.
VARCHAR2(size) It is used to store variable string data within the predefined length. It can be
stored up to 4000 byte.
VARCHAR(SIZE) It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)
NVARCHAR2(size) It is used to store Unicode string data within the predefined length. We have
to must specify the size of NVARCHAR2 data type. It can be stored up to 4000
bytes.
Oracle Numeric Data Types
NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 to 38,
and the scale s can range from -84 to 127.
FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range from 1 to
126.
BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes, including length
byte.
BINARY_DOUBLE It is used for double binary precision (64-bit). It requires 9 bytes, including
length byte.
DATE It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.
TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
BLOB It is used to specify unstructured binary data. Its range goes up to 232-1 bytes or 4
GB.
BFILE It is used to store binary data in an external file. Its range goes up to 232-1 bytes or
4 GB.
CLOB It is used for single-byte character data. Its range goes up to 232-1 bytes or 4 GB.
NCLOB It is used to specify single byte or fixed length multibyte national character set
(NCHAR) data. Its range is up to 232-1 bytes or 4 GB.
RAW(size) It is used to specify variable length raw binary data. Its range is up to 2000 bytes per
row. Its maximum size must be specified.
LONG It is used to specify variable length raw binary data. Its range up to 231-1 bytes or 2
RAW GB, per row.
Fundamental SQL Commands
Data Definition Language (DDL) Commands
Data Definition Language (DDL) Commands in Oracle are used to define the database
objects such as Tables, Views, Stored Procedures, Stored Functions, Triggers, etc. That
means DDL statements in Oracle are used to ALTER or Modify a database or table structure
and schema. The most important point that you need to remember is DDL Commands in
Oracle are working on the structure of a database object, not on the data of a table.
The following three DDL Commands are the latest feature in Oracle
1. Recyclebin
2. Flashback
3. Purge
CREATE Command
The CREATE DDL command in the Oracle database is used to create a new database object
such as Table, View, Stored Procedure, Stored Function, Trigger, etc.
The syntax to create a table is shown below.
Rules for creating a table in Oracle:
1. The Table name must begin with a letter A-Z or a-z
2. The Table name can contain numbers and underscores
3. The name of the table can be in UPPER or lower case
4. The maximum length of the table name can be 30 characters
5. We cannot use the same name of another existing object in our schema
6. The table name must not be a SQL reserved word.
7. Don’t provide space in the table name. If you want to provide space in a table name
then you can use the underscore symbol.
8. A table should contain a minimum of 1 column and a maximum of 1000 columns
ALTER Command
This command is used to change or modify the structure of a database object i.e. Table,
Views, Stored Procedures, Stored Functions, Triggers, etc.
In Oracle, using the ALTER DDL command we can perform the following operations on an
existing table.
1. Increase/decrease the length of a column.
2. Change the data type of a column.
3. Change NOT NULL to NULL or NULL to NOT NULL.
4. Used to add a new column to an existing table.
5. Used to drop an existing column.
6. Add a new constraint.
7. Used to drop an existing constraint on a table.
8. To change the column name of a table.
To change/modify the structure of a table, we can use the following sub-commands of Alter
Data Definition Language (DDL) Command in Oracle.
1. ALTER – MODIFY
2. ALTER – ADD
3. ALTER – RENAME
4. ALTER – DROP
Syntax:
ALTER TABLE <TABLE NAME> ADD <NEW COLUMN NAME> <DATATYPE>[SIZE];
ALTER – RENAME Command
This command is used to change the column name in a table.
Syntax:
ALTER TABLE <TABLE NAME> RENAME <COLUMN> <OLD COLUMN NAME> TO
<NEW COLUMN NAME>;
Syntax:
ALTER TABLE <TABLE NAME> DROP <COLUMN> <COLUMN NAME>;
Note: Before oracle10g enterprise edition when we drop a table from the database, the table
is permanently dropped. But, from oracle 10g enterprise edition once we drop a table from
the database then it will drop temporarily. And the user has a chance to restore the dropped
table again into the database by using the following commands are,
1. Recyclebin
2. Flashback
3. Purge
RECYCLEBIN Command
It is a system-defined table that is used for storing the information about the dropped
tables. It is similar to Windows Recyclebin.
To view the structure of recycle bin, you can use the following syntax.
DESC RECYCLEBIN;
PURGE Command
This DDL command is used to drop a table permanently i.e. it will drop a specific table from
recycle bin permanently.
PURGE TABLE <TABLE NAME>;
The following two are the Latest DML Commands in the Oracle database.
1. INSERT ALL
2. MERGE
Method2:
INSERT INTO EMPLOYEE (Id, Salary, Name) VALUES (NULL, NULL, NULL);
If you want to insert another row into the Employee table, then simply type / and press the
enter key in the SQL Plus editor.
The / is used to re-execute the last executed SQL query in SQL Plus editor. Once you type the
/ button and press the enter key then again it will ask you to enter the Id, Name, and salary
column values one by one as shown in the below image.
If you want to insert another row into the Employee table with the Id and Name column
values, then simply type / and press the enter button in the SQL Plus editor.
Like in previous example.
Syntax1(&&): For all Columns
The following is the syntax to use “&&” to insert fixed values to columns for all the columns
of a table. In this case, we cannot change values.
Now, if you type / and press the enter key, then it will insert the same record once more into
the Employee table as shown in the below image. That means it is going to insert fixed values.
The value cannot be changed dynamically.
Example:
Do Yourself.
Delete
1. It is a DML command
2. It can delete a specific row from a table.
3. It supports the “WHERE” clause condition.
4. It is a temporary data deletion.
5. We can restore deleted data by using the “ROLLBACK” command.
6. Execution speed is slow as deleting operation is performed row by row / one by one
manner.
Truncate
1. It is a DDL command
2. It is not possible to delete a specific row from a table.
3. It does not support the “WHERE” clause condition.
4. It is a permanent data deletion.
5. We cannot restore deleted data by using the “ROLLBACK” command.
6. Execution speed is fast as deleting a group of rows at a time.
I) Column Level:
At this level, we are creating alias names on columns. The syntax is given below.
<column name> <column alias name>
Example: Department Dept
Syntax to combined column + table level alias names by using “select” query:
Select <column name1> <column name1 alias name>, <column name2> <column
name2 alias name> From <Table Name> <Table Alias Name>;
Example:
Concatenation Operator (||) in Oracle:
This operator is used to join two string values (or) two expressions in a select query.
Example 2
Suppose you want to create a new table with the same structure and same data as the
existing table. For example, we want to create a new table with the name Employee1 with
the same structure and same data as the Employee table, then we need to execute the
following SQL query.
When you execute the above query, you will get the following output.
Example 3
If you want to create a new table with the same structure as an existing table but without
data. For example, we want to create a new table with the name Employee2 with the same
structure as the existing Employee table but with output data. To do so, we need to
execute the following SQL query.
CREATE TABLE Employee2 AS SELECT * FROM Employee WHERE 1 = 0;
When you execute the above SQL query, you will get the following output. Here, it will
create the Employee2 table without data.
Step1:
SELECT * FROM Employee;
Step2: Create a new table from the existing Employee table with data
CREATE TABLE Employee3 AS SELECT * FROM Employee;
Step3: Insert two more records into the new Employee3 table
INSERT INTO Employee3 (Id, Name, Department, Salary, Gender, Age, City)
VALUES (1011, ‘Kumar’, ‘IT’, 55000, ‘Male’, 27, ‘London’);
INSERT INTO Employee3 (Id, Name, Department, Salary, Gender, Age, City)
VALUES (1012, ‘Santosh’, ‘HR’, 70000, ‘Female’, 29, ‘Mumbai’);
Operators in Oracle
Operators are used to expressing the conditions in Select statements. The operator
manipulates individual data items and returns a result. The data items are called operands or
arguments.
The different types of Operators available in Oracle are as follows:
• Arithmetic operators
• Assignment operator
• Relational operators
• Logical operators
• Special Operators
• Set Operators
SELECT ID, Name, Salary, Salary + 2000 “Incremented salary” FROM Employee;
Assignment Operator in Oracle
The equal sign (=) is the assignment operator where the value on the right is assigned to the
value on the left.
This operator is used for the equality test. Used to test the equality of two operands. For
example, display the details of Employees whose Gender is Male.
The different types of relational operators that are available in Oracle are as follows:
1. Equal (=) Operator
2. Not Equal (!= or <>) Operator
3. Greater Than (>) Operator
4. Less Than (<) Operator
5. Greater Than or Equal To (>=) Operator
6. Less Than or Equal To (<=) Operator
In Oracle, there are three Logical Operators available. They are as follows:
1. AND: TRUE if both Boolean expressions are TRUE.
2. OR: TRUE if one of the Boolean expressions is TRUE.
3. NOT: Reverses the value of any other Boolean operator.
The Logical Operators in Oracle are used to compare two conditions to check whether a row
(or rows) can be selected for the output.
SELECT * FROM employee WHERE department = ‘IT’ AND NOT Age = 28;
SELECT * FROM Employee WHERE Salary >= 27000 AND Salary <= 30000 OR NOT CITY
= ‘Mumbai’;
IN Operator in Oracle
The IN Operator in Oracle is used to search for specified values that match any value in the
set of multiple values it accepts. The “IN” operator evaluates multiple values on a single data
column. It displays the data row if any one of the given values is matched with the data
column value. If none of the values matches, the SQL statement won’t return that data row.
Once you execute the above SELECT SQL Query, then you will get the result set which
includes only the IT and HR departments employees.
For example, the following SQL query returns all the employees who belong to the IT or HR
department using the Oracle OR Operator.
The following SQL Query also returns all the employees who belong to the IT or HR
department using the Oracle IN Operator.
If you want to fetch all the employees from the Employee table where the employee age is
between 25 and 27, then we need to write the SELECT SQL Query using the Oracle Between
Operator as shown below.
Once you execute the above SELECT Query, then you will get the following result set which
includes only the employees whose age is between 25 and 27.
Example: Fetch all the Employees whose names start with the letter P.
SELECT * FROM Employee WHERE Name LIKE ‘P%’;
Example: Fetch all the employees whose city ends with ai.
SELECT * FROM Employee WHERE City LIKE ‘%ai’;
Example: Fetch all employee whose name contains the word am
SELECT * FROM Employee WHERE Name LIKE ‘%am%’;
Example: Fetch all the employees whose name does not start with P.
SELECT * FROM Employee WHERE Name NOT LIKE ‘P%’;
Example: Fetch all the employees whose city does not end with ai.
SELECT * FROM Employee WHERE CITY NOT LIKE ‘%ai%’;
Example: Fetch all employee whose name does not contain the word am
SELECT * FROM Employee WHERE Name NOT LIKE ‘%am%’;
Example: Fetch all the employees whose department is having two letters
Here we are using two underscores (__) as the part in the LIKE Operator.
SELECT * FROM Employee WHERE Department LIKE ‘__’;
Example: Display all the employees whose names are having the second letter as ‘i’ in the
Employee table
SELECT * FROM Employee WHERE Name LIKE ‘_i%’;
SET Operators in Oracle
SQL set operators allow combining results from two or more SELECT statements.
There are four types of SET Operators available in Oracle. They are as follows:
1. UNION: It Returns all distinct rows selected by either query
2. UNION ALL: It Returns all rows selected by either query, including all duplicates
3. INTERSECT: It Returns all distinct rows selected by both queries
4. MINUS: It Returns all distinct rows selected by the first query but not the second
Clauses in Oracle
If you want to provide the SQL Query with some additional functionalities such as filtering the
records, sorting the records, fetching the records, and grouping the records then you need to
use the Clauses along with the SQL Query. So, in simple words, we can say that clauses are
used to provide some additional functionalities.
ORDER BY Clause
The ORDER BY Clause in Oracle is used for sorting the data either in ascending or descending
order based on a specified column or list of columns.
Example: Count the total number of employees in each department from the Employee
table.
Example: Count the total salary given to each department in the employee table
Example: Find the Highest and Lowest salary in Each Department in the Employee table
Example: Find the number of employees working in each Gender per Department
Example: Find the total salaries and the total number of employees by City, and by gender
Having Clause
The Having Clause in Oracle is also used for filtering the data just like the where clause.
The Having Clause in Oracle is typically used with a GROUP BY clause. That means the Having
Clause is used in combination with a GROUP BY clause to restrict the number of groups to be
returned by satisfying the condition which is specified using the having clause.
The HAVING clause is the same as the WHERE clause. The only difference is WHERE clause
FILTERS the intermediate data results, while the HAVING clause operates on group rows.
Likewise, WHERE clause, we can use conditions and operators with the HAVING clauses to
build complex SQL statements.
Filtering groups using the HAVING clause in Oracle
Constraints in Oracle
The Oracle Constraints define specific rules to the column(s) data in a database table. While
inserting, updating, or deleting the data rows, if the rules of the constraint are not followed,
the system will display an error message and the action will be terminated. The Constraints
in Oracle are defined while creating a new table. We can also alter the table and add new
Constraints. The Constraints are mainly used to maintain data integrity.
Constraints are used to restrict unwanted(invalid) data into the table. All databases are
supporting the following constraint types for maintaining data integrity.
1. NOT NULL Constraint
2. UNIQUE KEY Constraint
3. CHECK KEY Constraint
4. PRIMARY KEY Constraint
5. FOREIGN KEY Constraint (REFERENCES Key).
6. DEFAULT Constraint
CHECK Constraint
The Check Constraint in Oracle is used to enforce domain integrity. Domain integrity means
the values that are going to store in a table column must be followed by some defined rules
such as range, type, and format.
It is only possible to impose the Composite Primary Key constraint at the table level, it is
not possible at the column level.
Note: A foreign key in one TABLE points to either a primary key or a unique key in another
table in Oracle. The foreign key constraints are basically used to enforce referential
integrity.
Joins in Oracle
Joins in Oracle are used to retrieve data from multiple tables at a time. Joins in Oracle are
again classified into two types are as follows.
Example: Write a Query to retrieve student, course details from tables if CourseId is 20.
SELECT * FROM Student S, Course C WHERE S.CourseId = C.CourseId AND
C.CourseId = 20;
Write a Query to retrieve student, course details from Course and Student tables by using
INNER JOIN.
SELECT * FROM Student INNER JOIN Course ON Student.CourseId =
Course.CourseId;
Joining Three Tables in Oracle:
Fetch the details of such employees who are currently having any projects as well as they
must have an address.
The following SQL Query, Inner Joining Employee, Projects, and Address tables to fetch the
Employee details, projects, and their addresses.
Example 1:
Who is getting the first high salary from the Employee table?
SELECT * FROM EMPLOYEE WHERE SAL = (SELECT MAX(SAL) FROM
EMPLOYEE);
Example 2:
Whose employee job is the same as the job of ‘SMITH’?
SELECT * FROM EMPLOYEE WHERE JOB=(SELECT JOB FROM EMPLOYEE WHERE
ENAME='SMITH');
Example 3:
Whose salary is more than the max salary of the job is “SALESMAN”?
SELECT * FROM EMPLOYEE WHERE SAL>(SELECT MAX(SAL) FROM EMPLOYEE
WHERE JOB='SALESMAN');
Example 4
Whose employee job is same as the job of “BLAKE” and who are earning Salary more than
“BLAKE” salary?
SELECT * FROM EMPLOYEE WHERE JOB=(SELECT JOB FROM EMPLOYEE WHERE
ENAME='BLAKE') AND SAL>(SELECT SAL FROM EMPLOYEE WHERE
ENAME='BLAKE');
Example 5
Display employee details who are getting the Second highest Salary in the Employee table?
SELECT * FROM EMPLOYEE WHERE SAL=(SELECT MAX(SAL) FROM EMPLOYEE
WHERE SAL< (SELECT MAX(SAL) FROM EMPLOYEE));
Example1:
Employee details whose employee job is same as the job of the employee “SMITH”, and
“CLARK”?
SELECT * FROM EMPLOYEE WHERE JOB IN(SELECT JOB FROM EMPLOYEE WHERE
ENAME=’SMITH’ OR ENAME=’CLARK’);
Display all employees, whose salary is more than any “SALESMAN” salary?
SELECT * FROM EMPLOYEE WHERE SAL>ANY(SELECT SAL FROM EMPLOYEE
WHERE JOB=’SALESMAN’);
Display all employees, whose salary is more than all “SALESMAN” salaries?
SELECT * FROM EMPLOYEE WHERE SAL>ALL(SELECT SAL FROM EMPLOYEE
WHERE JOB=’SALESMAN’);
Multiple Column Subquery
Multiple columns values of the inner query compared with multiple columns values of the
outer query is called Multiple Column Subquery in Oracle.
The following is the syntax.
SELECT * FROM <TN> WHERE(<COL1>,<COL2>,…………) IN(SELECT
<COL1>,<COL2>,……. FROM <TN>);
Example:
Display employee whose JOB, AGE is same as the JOB, AGE of the employee “CLARK”?
SELECT * FROM EMPLOYEE WHERE(JOB, AGE) IN(SELECT JOB, AGE FROM
EMPLOYEE WHERE ENAME=’CLARK’);