Академический Документы
Профессиональный Документы
Культура Документы
Oracle Database
Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is an object-
relational database management system produced and marketed by Oracle Corporation. It is
most widely database used in the world. It runs virtually every kind of computer. It functions
virtually identically on all the machines, so when we learn it on one, we can use it on any
other. This fact makes knowledgeable oracle user and developers very much in demand, and
makes oracle knowledge and skills very portable.
Oracle is an Object-relational database. A relational database is an extremely simple way of
thinking and managing the data used in business. It is nothing more than a collection of tables
of data. We all encounter table every day: weather reports, stocks charts, sports scores. These
all tables, with column headings and rows of information simply presented. Even so the
relational approach can be sophisticated and powerful enough for even the most complex of
business. An object relational database supports all of the features of a relational database
while also supporting object-oriented concepts and features.
Oracle has grown from its humble beginnings as one of a number of databases available in
the 1970s to the market leader of today. In its early days, Oracle Corporation was known
more as an aggressive sales and promotion organization than a technology supplier. Over the
years, the Oracle database has grown in depth and quality, and its technical capabilities now
are generally recognized as the most advanced. With each release, Oracle has added more
power and features to its already solid base while improving the manageability.
1|Page
Oracle 10g
As of the Oracle Database 10g release, Oracle Corporation seems to have started to make an
effort to standardize all current versions of its major products using the "10g" label. Major
products include:
SQL
2|Page
The history of SQL begins in an IBM laboratory in San Jose, California, where SQL
was developed in the late 1970s.
SQL stands for Structured Query Language, and the language itself is often referred to
as "sequel."
It is a standard and programming language.
SQL lets you access and manipulate databases.
It was originally developed for IBM'sDB2 product.
American National Standard Institute is primary organization for fostering of
technology standard. Long established computer standard includes the American code
for information interchange (ANSI).
SQL is a nonprocedural language, in contrast to the procedural or third generation
languages (3GLs) such as COBOL and C that had been created up to that time.
Nonprocedural means what rather than how. For example, SQL describes what data to
retrieve, delete, or insert, rather than how to perform the operation.
Some common RDBMS that used SQL are ORACLE, CYBASE, and Microsoft SQL
SERVER.
Oracles RDBMS
Oracle provides a flexible RDBMS called Oracle Database 10g. Using its features, you can
store and manage data with all the advantages of a relational structure plus PL/SQL, an
engine that provides you with the ability to store and execute program units. Oracle
Database 10g also supports Java and XML. The Oracle server offers the options of retrieving
data based on optimization techniques. It includes security features that control how a
database is accessed and used. Other features include consistency and protection of data
through locking mechanisms.
The Oracle10g release provides an open, comprehensive, and integrated approach to
information management. An Oracle server consists of an Oracle database and an Oracle
server instance. Every time a database is started, a system global area (SGA) is allocated and
Oracle background processes are started. The SGA is an area of memory that is used for
database information shared by the database users. The combination of the background
processes and memory buffers is called an Oracle instance.
SQL Statements
Oracle SQL complies with industry-accepted standards. Oracle Corporation ensures future
compliance with evolving standards by actively involving key personnel in SQL standards
committees. Industry-accepted committees are the American National Standards Institute
(ANSI) and the International Standards Organization (ISO). Both ANSI and ISO have
accepted SQL as the standard language for relational databases.
3|Page
Statement Description
SELECT
Retrieves data from the database, enters new rows, changes existing
INSERT
rows, and removes unwanted rows from tables in the database,
UPDATE
respectively.
DELETE
Collectively known as data manipulation language (DM L).
MERGE
CREATE
ALTER
DROP Sets up, changes, and removes data structures from tables.
RENAME Collectively known as data definition language (DDL).
TRUNCATE
COMMENT
Gives or removes access rights to both the Oracle database and the
GRANT
structures within it. Collectively known as data control language
REVOKE
(DCL).
COMMIT Manages the changes made by DML statements. Changes to the data
ROLLBACK can be grouped together into logical transactions. Collectively
SAVEPOINT known as Transaction control (TC).
SELECT Statement
A SELECT statement retrieves information from the database. With a SELECT statement,
you can use the following capabilities:
Projection: Choose the columns in a table that are returned by a query. Choose as
few or as many of the columns as needed.
Selection: Choose the rows in a table that are returned by a query. Various criteria
can be used to restrict the rows that are retrieved.
Joining: Bring together data that is stored in different tables by specifying the link
between them.
In its simplest form, a SELECT statement must include the following:
A SELECT clause, which specifies the columns to be displayed.
A FROM clause, which identifies the table containing the columns that are listed in
the SELECT clause.
Syntax:
SELECT *| {[DISTINCT] column | expression [alias]...} FROM table;
In the syntax:
SELECT is a list of one or more columns
* selects all columns
DISTINCT suppresses duplicates
column | expression selects the named column or the expression
alias gives selected columns different headings
FROM table specifies the table containing the columns
4|Page
Selecting All Columns of All Rows
You can display all columns of data in a table by following the SELECT keyword with
an
asterisk (*).You can also display all columns in the table by listing all the columns after
the SELECT keyword.
SELECT * FROM table_name;
SELECT col1, col2 ... coln FROM table_name;
Arithmetic Expressions
You may need to modify the way in which data is displayed, or you may want to perform
calculations or look at what-if scenarios. These are all possible using arithmetic expressions.
An arithmetic expression can contain column names, constant numeric values, and the
arithmetic operators.
Arithmetic Operators
The arithmetic operators that are available in SQL are:
* Multiply
/ Divide
- Subtract
+ Add
You can use arithmetic operators in any clause of a SQL statement (except the FROM
clause).
Eg:- SELECT last_name, salary, salary + 300 FROM employees;
Null Values
If a row lacks a data value for a particular column, that value is said to be null or to contain a
null. A null is a value that is unavailable, unassigned, unknown, or inapplicable. A null is not
the same as a zero or a space. Zero is a number, and a space is a character.
Columns of any data type can contain nulls. However, some constraints (NOT NULL and
PRIMARY KEY) prevent nulls from being used in the column.
If any column value in an arithmetic expression is null, the result is null. For example, if you
attempt to perform division by zero, you get an error. However, if you divide a number by
null, the result is a null or unknown.
Column Alias
Renames a column heading
Is useful with calculations
Immediately follows the column name (There can also be the optional AS
keyword between the column name and alias.)
5|Page
Requires double quotation marks if it contains spaces or special characters or if it
is case sensitive.
Eg:- SELECT last_name AS name, commission_pct comm FROM employees;
Eg:- SELECT last_name "Name" , salary*12 "Annual Salary" FROM employees;
Concatenation Operator
You can link columns to other columns, arithmetic expressions, or constant values to create
a character expression by using the concatenation operator (||). Columns on either side of
the operator are combined to make a single output column.
Eg: SELECT last_name||job_id AS "Employees" FROM employees;
The AS keyword before the alias name makes the SELECT clause easier to read.
If you concatenate a null value with a character string, the result is a character string.
LAST_NAME || NULL results in LAST_NAME.
Literal Character Strings
A literal is a character, a number, or a date that is included in the SELECT list and that is
not
a column name or a column alias. It is printed for each row returned. Literal strings of
free format text can be included in the query result and are treated the same as a column
in the
SELECT list.
Date and character literals must be enclosed by single quotation marks (' '); number
literals
need not be so enclosed.
Eg: In the following example, the last name and salary for each employee are concatenated
with a literal to give the returned rows more meaning:
SELECT last_name ||': 1 Month salary = '||salary Monthly FROM employees;
Alternative Quote (q) Operator
Many SQL statements use character literals in expressions or conditions. If the literal
itself
contains a single quotation mark, you can use the quote (q) operator and choose your own
quotation mark delimiter.
You can choose any convenient delimiter, single-byte or multibyte, or any of the
following
character pairs: [ ], { }, ( ), or < >.
Eg: SELECT department_name || q'[, it's assigned Manager Id: ]' || manager_id
AS "Department and Manager" FROM departments;
The string contains a single quotation mark, which is normally interpreted as a delimiter of a
character string. By using the q operator, however, the brackets [] are used as the quotation
mark delimiter. The string between the brackets delimiters is interpreted as a literal character
string.
6|Page
Limiting the Rows That Are Selected
You can restrict the rows that are returned from the query by using the WHERE clause. A
WHERE clause contains a condition that must be met, and it directly follows the FROM
clause. If the condition is true, the row meeting the condition is returned.
Syntax: SELECT * | {[DISTINCT] column | expression [alias],...} FROM table
[WHERE condition(s)];
In the syntax:
WHERE restricts the query to rows that meet a condition
condition is composed of column names, expressions, constants, and a comparison operator
The WHERE clause can compare values in columns, literal values, arithmetic expressions, or
functions. It consists of three elements:
- Column name
- Comparison condition
- Column name, constant, or list of values
Comparison Conditions
Operator Meaning
= Equal to
Comparison conditions are used in conditions that compare one expression to another value
or expression. They are used in the WHERE clause in the following format:
7|Page
Syntax
... WHERE expr operator value
Example:
... WHERE hire_date = '01-JAN-95'
... WHERE salary >= 6000
... WHERE last_name = 'Smith'
An alias cannot be used in the WHERE clause.
Using the BETWEEN Condition
You can display rows based on a range of values using the BETWEEN range condition.
The range that you specify contains a lower limit and an upper limit.
Eg: SELECT last_name, salary FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
Values that are specified with the BETWEEN condition are inclusive. You must specify
the lower limit first. You can also use the BETWEEN condition on character values:
Eg: SELECT last_name FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith';
8|Page
Using the NULL Conditions
The NULL conditions include the IS NULL condition and the IS NOT NULL condition.
The IS NULL condition tests for nulls. A null value means the value is unavailable,
unassigned, unknown, or inapplicable. Therefore, you cannot test with = because a null
cannot be equal or unequal to any value.
Eg: SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
This example retrieves the last names and managers of all employees who do not have a
manager.
Eg: To display last name, job ID, and commission for all employees who are not entitled
to receive a commission, use the following SQL statement:
SELECT last_name, job_id, commission_pct FROM employees
WHERE commission_pct IS NULL;
Logical Conditions
A logical condition combines the result of two component conditions to produce a single
result based on those conditions, or it inverts the result of a single condition. A row is
returned only if the overall result of the condition is true. Three logical operators are
available in SQL: AND, OR, NOT
9|Page
Using the NOT Operator
Eg: SELECT last_name, job_id FROM employees WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
The example displays the last name and job ID of all employees whose job ID is not
IT_PROG, ST_CLERK, or SA_REP.
NOT Truth Table
The following table shows the result of applying the NOT operator to a condition:
NOT TRUE FALSE NULL
Single row functions can be character functions, numeric functions, date functions, and
conversion functions. Note that these functions are used to manipulate data items. These
functions require one or more input arguments and operate on each row, thereby returning
one output value for each row. Argument can be a column, literal or an expression. Single
row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single
row functions can be -
General functions - Usually contains NULL handling functions. The functions under
the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE.
Case Conversion functions - Accepts character input and returns a character value.
Functions under the category are UPPER, LOWER and INITCAP.
o UPPER function converts a string to upper case.
o LOWER function converts a string to lower case.
o INITCAP function converts only the initial alphabets of a string to upper case.
Character functions - Accepts character input and returns number or character value.
Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD,
RPAD, TRIM and REPLACE.
o CONCAT function concatenates two string values.
o LENGTH function returns the length of the input string.
o SUBSTR function returns a portion of a string from a given start point to an
end point.
o INSTR function returns numeric position of a character or a string in a given
string.
10 | P a g e
o
LPAD and RPAD functions pad the given string upto a specific length with a
given character.
o TRIM function trims the string input from the start or end.
o REPLACE function replaces characters from the input string with a given
character.
Date functions - Date arithmetic operations return date or numeric values. Functions
under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY,
LAST_DAY, ROUND and TRUNC.
o MONTHS_BETWEEN function returns the count of months between the two
dates.
o ADD_MONTHS function add 'n' number of months to an input date.
o NEXT_DAY function returns the next day of the date specified.
o LAST_DAY function returns last day of the month of the input date.
o ROUND and TRUNC functions are used to round and truncates the date
value.
Number functions - Accepts numeric input and returns numeric values. Functions
under the category are ROUND, TRUNC, and MOD.
o ROUND and TRUNC functions are used to round and truncate the number
value.
o MOD is used to return the remainder of the division operation between two
numbers.
Illustrations
The SELECT query below demonstrates the use of NVL function.
SELECT first_name, last_name, salary, NVL (commission_pct,0)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of case conversion functions.
SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of CONCAT function to concatenate
two string values.
SELECT CONCAT (first_name, last_name)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of SUBSTR and INSTR functions.
SUBSTR function returns the portion of input string from 1st position to 5th position.
INSTR function returns the numeric position of character 'a' in the first name.
SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print
the employee and job information.
SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of ROUND and TRUNC functions.
SELECT ROUND (1372.472,1) FROM dual;
SELECT TRUNC (72183,-2) FROM dual;
11 | P a g e
The SELECT query below shows a date arithmetic function where difference of
employee hire date and sysdate is done.
SELECT employee_id, (sysdate - hire_date) Employment_days
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of MONTHS_BETWEEN,
ADD_MONTHS, NEXT_DAY and LAST_DAY functions.
SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date)
Employment_months FROM employees WHERE rownum < 5;
SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate)
FROM dual;
Illustrations
The below SELECT query counts the number of employees in the organization.
12 | P a g e
SELECT COUNT(*) Count FROM employees;
The below SELECT query returns the average of the salaries of employees in the
organization.
SELECT AVG(Salary) average_sal FROM employees;
The below SELECT query returns the sum of the salaries of employees in the
organization.
SELECT SUM(Salary) total_sal FROM employees;
The below SELECT query returns the oldest and latest hired dates of employees in the
organization.
SELECT MIN (hire_date) oldest, MAX (hire_date) latest FROM employees;
GROUP BY
Aggregate functions are normally used in conjunction with a GROUP BY clause. The
GROUP BY clause enables you to use aggregate functions to answer more complex
managerial questions such as:
What is the average salary of employees in each department?
How many employees work in each department?
How many employees are working on a particular project?
Group by function establishes data groups based on columns and aggregates the information
within a group only. The grouping criterion is defined by the columns specified in GROUP
BY clause. Following this hierarchy, data is first organized in the groups and then WHERE
clause restricts the rows in each group.
Guidelines of using GROUP BY clause
(1) All the dependent columns or columns used in GROUP BY function must form the basis
of grouping, hence must be included in GROUP BY clause also.
(2) GROUP BY clause does not support the use of column alias, but the actual names.
(3) GROUP BY clause can only be used with aggregate functions like SUM, AVG, COUNT,
MAX, and MIN. If it is used with single row functions,
(4) Aggregate functions cannot be used in a GROUP BY clause.Below query lists the count
of employees working in each department.
SELECT DEPARTMENT_ID, COUNT (*)
FROM employees
GROUP BY DEPARTMENT_ID;
Similarly, below query to find sum of salaries for respective job ids in each department. Note
the group is established based on Department and Job id. So they appear in GROUP BY
clause.
SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
The below query also produces the same result. Please note that grouping is based on the
department id and job id columns but not used for display purpose.
SELECT SUM (SALARY)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
13 | P a g e
Use of DISTINCT, ALL keywords with Aggregate functions
By specifying DISTINCT keyword with the input parameter, group by function considers
only the unique value of the column for aggregation. By specifying ALL keyword with the
input parameter, group by function considers all the values of the column for aggregation,
including nulls and duplicates. ALL is the default specification.
The HAVING clause is used for aggregate functions in the same way that a WHERE clause
is used for column names and expressions. Essentially, the HAVING and WHERE clauses do
the same thing, that is filter rows from inclusion in a result table based on a condition. While
it may appear that a HAVING clause filters out groups, it does not. Rather, a HAVING
clause filters rows.
When all rows for a group are eliminated so is the group. To summarize, the important
differences between the WHERE and HAVING clauses are:
A WHERE clause is used to filter rows BEFORE the GROUPING action (i.e., before
the calculation of the aggregate functions).
A HAVING clause filters rows AFTER the GROUPING action (i.e., after calculation
of the aggregate functions).
SELECT JOB_ID, SUM (SALARY) FROM employees
GROUP BY JOB_ID HAVING SUM (SALARY) > 10000;
The HAVING clause is a conditional option that is directly related to the GROUP BY
clause option because a HAVING clause eliminates rows from a result table based on
the result of a GROUP BY clause.
14 | P a g e
Cartesian join (also known as a Cartesian product or cross join) - Replicates each row
from the first table with every row from the second table. Creates a join between
tables by displaying every possible record combination.
Natural Join
The NATURAL keyword can simplify the syntax of an equijoin. A NATURAL JOIN is
possible whenever two (or more) tables have columns with the same name, and the columns
are join compatible, i.e., the columns have a shared domain of values. The join operation
joins rows from the tables that have equal column values for the same named columns.
Eg: Consider the one-to-many relationship between the DEPARTMENTS and EMPLOYEES
tables. Each table has a column named DEPARTMENT_ID. This column is the primary key
of the DEPARTMENTS table and a foreign key of the EMPLOYEES table.
SELECT E.first_ name NAME, D.department_name DNAME
FROM employees E NATURAL JOIN departments D;
Eg: The below SELECT query joins the two tables by explicitly specifying the join condition
with the ON keyword.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
ON (E.department_id = D.department_id);
USING Clause Using Natural joins, Oracle implicitly identify columns to form the basis of
join. Many situations require explicit declaration of join conditions. In such cases, we use
USING clause to specify the joining criteria. Since, USING clause joins the tables based on
equality of columns, it is also known as Equijoin. They are also known as Inner joins or
simple joins.
Syntax:
SELECT <column list>
FROM TABLE1 JOIN TABLE2
USING (column name)
Consider the below SELECT query, EMPLOYEES table and DEPARTMENTS table are
joined using the common column DEPARTMENT_ID.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
USING (department_id);
Self Join
A SELF-JOIN operation produces a result table when the relationship of interest exists
among rows that are stored within a single table. In other words, when a table is joined to
itself, the join is known as Self Join.
15 | P a g e
Consider EMPLOYEES table, which contains employee and their reporting managers. To
find manager's name for an employee would require a join on the EMP table itself. This is a
typical candidate for Self Join.
SELECT e1.FirstName Manager,e2.FirstName Employee
FROM employees e1 JOIN employees e2
ON (e1.employee_id = e2.manager_id)
ORDER BY e2.manager_id DESC;
Non Equijoins
A non-equality join is used when the related columns can't be joined with an equal sign-
meaning there are no equivalent rows in the tables to be joined. A non-equality join enables
you to store a range's minimum value in one column of a record and the maximum value in
another column. So instead of finding a column-to-column match, you can use a non-equality
join to determine whether the item being shipped falls between minimum and maximum
ranges in the columns. If the join does find a matching range for the item, the corresponding
shipping fee can be returned in the results. As with the traditional method of equality joins, a
non-equality join can be performed in a WHERE clause. In addition, the JOIN keyword can
be used with the ON clause to specify relevant columns for the join.
SELECT E.first_name, J.job_hisal, J.job_losal, E.salary
FROM employees E JOIN job_sal J
ON (E.salary BETWEEN J.job_losal AND J.job_losal);
Outer Joins
An Outer Join is used to identify situations where rows in one table do not match rows in a
second table, even though the two tables are related.
There are three types of outer joins: the LEFT, RIGHT, and FULL OUTER JOIN. They all
begin with an INNER JOIN, and then they add back some of the rows that have been
dropped. A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left)
table in the join condition, and output columns from the second (right) table are set to NULL.
A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table
in the join condition, and output columns from the first (left) table are set to NULL. The
FULL OUTER JOIN adds back all the rows that are dropped from both the tables.
Right Outer Join
A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table
in the join condition, and output columns from the first (left) table are set to NULL. Note the
below query lists the employees and their corresponding departments. Also no employee has
been assigned to department 30.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE E.DEPARTMENT_ID (+) = D.DEPARTMENT_ID;
16 | P a g e
A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in
the join condition, and output columns from the second (right) table are set to NULL. The
query demonstrated above can be used to demonstrate left outer join, by exchanging the
position of (+) sign.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE D.DEPARTMENT_ID = E.DEPARTMENT_ID (+);
The FULL OUTER JOIN adds back all the rows that are dropped from both the tables. Below
query shows lists the employees and their departments. Note that employee 'MAN' has not
been assigned any department till now (its NULL) and department 30 is not assigned to any
employee.
SELECT nvl (e.first_name,'-') first_name, nvl (to_char (d.department_id),'-') department_id
FROM employee e FULL OUTER JOIN department d
ON e. depARTMENT_ID = d. depARTMENT_ID;
17 | P a g e
INSERT, UPDATE, and DELETE statements. Sub queries must be enclosed within
parentheses.
A sub query can be used any place where an expression is allowed providing it returns a
single value. This means that a sub query that returns a single value can also be listed as an
object in a FROM clause listing. This is termed an inline view because when a sub query is
used as part of a FROM clause, it is treated like a virtual table or view. Sub query can be
placed either in FROM clause, WHERE clause or HAVING clause of the main query.
Oracle allows a maximum nesting of 255 sub query levels in a WHERE clause. There is no
limit for nesting sub queries expressed in a FROM clause. In practice, the limit of 255 levels
is not really a limit at all because it is rare to encounter sub queries nested beyond three or
four levels.
A sub query SELECT statement is very similar to the SELECT statement used to begin a
regular or outer query. The complete syntax of a sub query is:
( SELECT [DISTINCT] subquery_select_parameter
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )
Types of Sub queries
Single Row Sub Query: Sub query which returns single row output. They mark the
usage of single row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use of
multiple row comparison operators like IN, ANY, ALL. There can be sub queries
returning multiple columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query.This type of subquery also includes subqueries that use the EXISTS operator to test
the existence of data rows satisfying specified criteria.
18 | P a g e
A HAVING clause is used when the group results of a query need to be restricted based on
some condition. If a sub query's result must be compared with a group function, you must
nest the inner query in the outer query's HAVING clause.
SELECT department_id, MIN (salary)
FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary) FROM employees)
Note in the above query, IN matches department ids returned from the sub query, compares it
with that in the main query and returns employee's name who satisfy the condition.
Correlated Sub Query
As opposed to a regular sub query, where the outer query depends on values provided by the
inner query, a correlated sub query is one where the inner query depends on values provided
by the outer query. This means that in a correlated sub query, the inner query is executed
repeatedly, once for each row that might be selected by the outer query.
Correlated sub queries can produce result tables that answer complex management questions.
19 | P a g e
Consider the below SELECT query. Unlike the sub queries previously considered, the sub
query in this SELECT statement cannot be resolved independently of the main query. Notice
that the outer query specifies that rows are selected from the employee table with an alias
name of e1. The inner query compares the employee department number column
(Department Number) of the employee table with alias e2 to the same column for the alias
table name e1.
SELECT EMPLOYEE_ID, salary, department_id FROM employees E
WHERE salary > (SELECT AVG(salary) FROM EMP T
WHERE E.department_id = T.department_id)
When a multiple-column sub query is used in the outer query's FROM clause, it creates a
temporary table that can be referenced by other clauses of the outer query. This temporary
table is more formally called an inline view. The sub query's results are treated like any other
table in the FROM clause. If the temporary table contains grouped data, the grouped subsets
are treated as separate rows of data in a table. Consider the FROM clause in the below query.
The inline view formed by the sub query is the data source for the main query.
SELECT *
FROM (SELECT salary, department_id FROM employees
WHERE salary BETWEEN 1000 and 2000);
SET OPERATORS
The set operators combine the results of two or more component queries into one result. Queries
containing set operators are called compound queries.
Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows that are selected by the first SELECT statement
and not selected in the second SELECT statement
All set operators have equal precedence. If a SQL statement contains multiple set operators,
the Oracle server evaluates them from left (top) to right (bottom) if no parentheses explicitly
specify another order.
20 | P a g e
UNION Operator
The UNION operator returns all rows that are selected by either query. Use the UNION
operator to return all rows from multiple tables and eliminate any duplicate rows. By
default, the output is sorted in ascending order of the first column of the SELECT
clause. Consider the following example showing use of UNION:
SELECT employee_id, job_id, department_id
FROM employees
UNION
SELECT employee_id, job_id, department_id
FROM job_history;
INTERSECT Operator
Use the INTERSECT operator to return all rows that are common to multiple queries.
The number of columns and the data types of the columns being selected by the
SELECT statements in the queries must be identical in all the SELECT statements used
in the query. The names of the columns need not be identical.
Example:
SELECT employee_id, job_id, department_id
FROM employees
INTERSECT
SELECT employee_id, job_id, department_id
FROM job_history;
MINUS Operator
Use the MINUS operator to return rows returned by the first query that are not present
in the second query (the first SELECT statement MINUS the second SELECT
statement). All of the columns in the WHERE clause must be in the SELECT clause
for the MINUS operator to work.
Example:
SELECT employee_id, job_id
FROM employees
MINUS
SELECT employee_id, job_id
FROM job_history;
Set Operator Guidelines
The expressions in the select lists of the queries must match in number and data type.
Queries that use UNION, UNION ALL, INTERSECT, and MINUS operators in their
WHERE clause must have the same number and type of columns in their SELECT list.
The ORDER BY clause:
Can appear only at the very end of the statement
Will accept the column name, an alias, or the positional notation
The column name or alias, if used in an ORDER BY clause, must be from the first
SELECT list.
21 | P a g e
Set operators can be used in subqueries.
MANIPULATING DATA
Data manipulation language (DML) is a core part of SQL. When you want to add, update, or
delete data in the database, you execute a DML statement. A collection of DML statements
that form a logical unit of work is called a transaction.
Example:
INSERT INTO departments (department_id,department_name, manager_id,
location_id)
VALUES (70, 'Public Relations', 100, 1700);
This statement with the VALUES clause adds only one row at a time to a table. List values in
the default order of the columns in the table. Optionally, list the columns in the INSERT clause.
Enclose character and date values in single quotation marks. Number values should not be
enclosed in single quotation marks, because implicit conversion may take place for numeric
values that are assigned to NUMBER data type columns if single quotation marks are included.
22 | P a g e
Inserting Special Values by Using SQL Functions
The SYSDATE function records the current date and time. Inserting Specific Date and Time
Values. The DD-MON-YY format is usually used to insert a date value. With this format, recall
that the century defaults to the current century. Because the date also contains time information,
the default time is midnight (00:00:00).
Creating a Script
You can save commands with substitution variables to a file and execute the commands in the
file. Run the script file and you are prompted for input for each of the & substitution variables.
After entering a value for the substitution variable, click the Continue button. The values that
you input are then substituted into the statement. This enables you to run the same script file
over and over but supply a different set of values each time you run it.
Example:
INSERT INTO departments(department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);
The number of columns and their data types in the column list of the INSERT clause must
match the number of values and their data types in the subquery. To create a copy of the rows
of a table, use SELECT * in the subquery:
Syntax:
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
In the syntax:
table is the name of the table
column is the name of the column in the table to populate
value is the corresponding value or subquery for the column
23 | P a g e
condition identifies the rows to be updated and is composed of column names,
expressions, constants, subqueries, and comparison operators
Example:
UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);
All rows in the table are deleted if you omit the WHERE clause.
24 | P a g e
FROM departments
WHERE department_name LIKE '%Public%');
TRUNCATE Statement
A more efficient method of emptying a table is with the TRUNCATE statement. We can use
the TRUNCATE statement to quickly remove all rows from a table or cluster.
Syntax:
TRUNCATE TABLE table_name;
Removing rows with the TRUNCATE statement is faster than removing them with the
DELETE statement for the following reasons:
The TRUNCATE statement is a data definition language (DDL) statement and
generates no rollback information.
If the table is the parent of a referential integrity constraint, you cannot truncate the
table. You need to disable the constraint before issuing the TRUNCATE statement.
DATA TRANSACTION
The Oracle server ensures data consistency based on transactions. Transactions give you more
flexibility and control when changing data, and they ensure data consistency in the event of
user process failure or system failure. Transactions consist of DML statements that make up
one consistent change to the data.
25 | P a g e
Statement Description
COMMIT Ends the current transaction by making all pending data
changes permanent
SAVEPOINT name Marks a save point within the current transaction
Read Consistency
Database users access the database in two ways:
1. Read operations (SELECT statement)
2. Write operations (INSERT, UPDATE, DELETE statements)
You need read consistency so that the following occur:
The database reader and writer are ensured a consistent view of the data.
Readers do not view data that is in the process of being changed.
Writers are ensured that the changes to the database are done in a consistent way.
Changes made by one writer do not disrupt or conflict with changes that another writer
is making.
The purpose of read consistency is to ensure that each user sees data as it existed at the last
commit, before a DML operation started.
26 | P a g e
USING DDL STATEMENTS TO CREATE AND MANAGE TABLES
Database Objects
An Oracle database can contain multiple data structures. Each structure should be outlined in
the database design so that it can be created during the build stage of database development.
Table: Stores data
View: Subset of data from one or more tables
Sequence: Generates numeric values
Index: Improves the performance of some queries
Synonym: Gives alternative names to objects
Naming Rules
You name database tables and columns according to the standard rules for naming any
Oracle database object:
Table names and column names must begin with a letter and be 130 characters long.
Names must contain only the characters AZ, az, 09, _ (underscore), $, and # (legal
characters, but their use is discouraged).
Names must not duplicate the name of another object owned by the same Oracle server
user.
Names must not be an Oracle server reserved word.
Data Types
When you identify a column for a table, you need to provide a data type for the column.
There are several data types available:
27 | P a g e
CHAR [(size)] Fixed-length character data of length size
bytes (Default and minimum size is 1;
maximum size is 2,000.)
NUMBER [(p,s)] Number having precision p and scale s
DATE Date and time values to the nearest second
between January 1,
4712 B.C., and December 31, 9999 A.D.
LONG Variable-length character data (up to 2 GB)
CLOB Character data (up to 4 GB)
BLOB Binary data (up to 4 GB)
Constraints
The Oracle server uses constraints to prevent invalid data entry into tables. Constraints can be
defined at the time of table creation or after the table has been created.
You can use constraints to do the following:
Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from
that table. The constraint must be satisfied for the operation to succeed.
Prevent the deletion of a table if there are dependencies from other tables
Provide rules for Oracle tools, such as Oracle Developer
Constraint Description
NOT NULL Specifies that the column cannot contain a null value
UNIQUE Specifies a column or combination of columns whose
values
must be unique for all rows in the table
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes and enforces a foreign key relationship
between the
column and a column of the referenced table
CHECK Specifies a condition that must be true
Defining Constraints
We can create the constraints at either the column level or table level. Constraints defined at
the column level are included when the column is defined. Table-level constraints are defined
at the end of the table definition and must refer to the column or columns on which the
constraint pertains in a set of parentheses. NOT NULL constraints must be defined at the
column level.
Syntax:
CREATE TABLE [schema.] table (column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
28 | P a g e
Example: CREATE TABLE employees( employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);
In the syntax:
schema is the same as the owners name
table is the name of the table
DEFAULT expr specifies a default value to use if a value is omitted in the
INSERT statement
Column is the name of the column
datatype is the columns data type and length
column_constraint is an integrity constraint as part of the column definition
table_constraint is an integrity constraint as part of the table definition
UNIQUE Constraint
A UNIQUE key integrity constraint requires that every value in a column or set of columns
(key) be uniquethat is, no two rows of a table can have duplicate values in a specified column
or set of columns. The column (or set of columns) included in the definition of the UNIQUE
key constraint is called the unique key. If the UNIQUE constraint comprises more than one
column, that group of columns is called a composite unique key.
29 | P a g e
key in the same table or a different table.The foreign key is defined in the child table, and the
table containing the referenced column is the parent table. The foreign key is defined using a
combination of the following keywords:
FOREIGN KEY is used to define the column in the child table at the table-constraint
level.
REFERENCES identifies the table and column in the parent table.
ON DELETE CASCADE indicates that when the row in the parent table is deleted, the
dependent rows in the child table are also deleted.
ON DELETE SET NULL converts foreign key values to null when the parent value is
removed.
The default behavior is called the restrict rule, which disallows the update or deletion of
referenced data. Without the ON DELETE CASCADE or the ON DELETE SET NULL
options, the row in the parent table cannot be deleted if it is referenced in the child table.
CHECK Constraint
The CHECK constraint defines a condition that each row must satisfy. The condition can use
the same constructs as query conditions, with the following exceptions:
References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns
Calls to SYSDATE, UID, USER, and USERENV functions
Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition.
There is no limit to the number of CHECK constraints that you can define on a column.
30 | P a g e
Add a new column
Modify an existing column
Define a default value for the new column
Drop a column
Dropping a Table
The DROP TABLE statement removes the definition of an Oracle table. When you drop a
table, the database loses all the data in the table and all the indexes associated with it. All data
and structure in the table are deleted.
Any pending transactions are committed.
All indexes are dropped.
All constraints are dropped.
You cannot roll back the DROP TABLE statement.
Syntax :
DROP TABLE table
In the syntax, table is the name of the table.
View
You can present logical subsets or combinations of data by creating views of tables. A view is
a logical table based on a table or another view. A view contains no data of its own but is like
a window through which data from tables can be viewed or changed. The tables on which a
view is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.
Syntax:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)]
AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
In the syntax:
OR REPLACE re-creates the view if it already exists
FORCE creates the view regardless of whether or not the base tables exist
NOFORCE creates the view only if the base tables exist (This is the default.)
View is the name of the view
alias specifies names for the expressions selected by the views query.
subquery is a complete SELECT statement
WITH CHECK OPTION specifies that only those rows that are accessible to the view can
be inserted or updated
31 | P a g e
constraint is the name assigned to the CHECK OPTION constraint
WITH READ ONLY ensures that no DML operations can be performed on this view
Example:
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ' '|| last_name, salary, department_id
FROM employees
WHERE department_id = 80;
Modifying a View
With the OR REPLACE option, a view can be created even if one exists with this name already,
thus replacing the old version of the view for its owner. This means that the view can be altered
without dropping, re-creating, and regranting object privileges.
Removing a View
You can remove a view without losing data because a view is based on underlying tables in the
database.
Syntax:
DROP VIEW view;
Advantages of Views
Views restrict access to the data because the view can display selected columns from
the table.
32 | P a g e
Views can be used to make simple queries to retrieve the results of complicated queries.
For example, views can be used to query information from multiple tables without the
user knowing how to write a join statement.
Views provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
Views provide groups of users access to data according to their particular criteria.
Sequences
A sequence is a database object that creates integer values. You can create sequences and then
use them to generate numbers. A sequence is a user-created database object that can be shared
by multiple users to generate integers. We can define a sequence to generate unique values or
to recycle and use the same numbers again. A typical usage for sequences is to create a primary
key value, which must be unique for each row. The sequence is generated and incremented (or
decremented) by an internal Oracle routine. This can be a time-saving object because it can
reduce the amount of application code needed to write a sequence-generating routine. Sequence
numbers are stored and generated independently of tables. Therefore, the same sequence can
be used for multiple tables.
Syntax:
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
In the syntax:
sequence is the name of the sequence generator
INCREMENT BY n specifies the interval between sequence numbers, where n is an
integer
START WITH n specifies the first sequence number to be generated
MAXVALUE n specifies the maximum value the sequence can generate
NOMAXVALUE specifies a maximum value of 10^27 for an ascending sequence
and 1 for a descending sequence
MINVALUE n specifies the minimum sequence value
NOMINVALUE specifies a minimum value of 1 for an ascending sequence and
(10^26) for a descending sequence
Modifying a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from the sequence
are allocated and you will receive an error indicating that the sequence exceeds the
MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER
SEQUENCE statement.
Syntax
ALTER SEQUENCE sequence
[INCREMENT BY n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
33 | P a g e
Indexes
An Oracle server index is a schema object that can speed up the retrieval of rows by using a
pointer. Indexes can be created explicitly or automatically. If we do not have an index on the
column, then a full table scan occurs.An index provides direct and fast access to rows in a table.
Its purpose is to reduce the necessity of disk I/O by using an indexed path to locate data quickly.
The index is used and maintained automatically by the Oracle server. After an index is created,
no direct activity is required by the user. Indexes are logically and physically independent of
the table that they index. This means that they can be created or dropped at any time and have
no effect on the base tables or other indexes.
Creating an Index
Syntax:
CREATE INDEX index ON table (column[, column]...);
Removing an Index
Remove an index from the data dictionary by using the DROP INDEX command:
DROP INDEX index;
To drop an index, you must be the owner of the index or have the DROP ANY INDEX
privilege.
Synonyms
Synonyms are database objects that enable you to call a table by another name. We can create
synonyms to give an alternate name to a table.
Syntax:
CREATE [PUBLIC] SYNONYM synonym
FOR object;
In the syntax:
PUBLIC creates a synonym that is accessible to all users
synonym is the name of the synonym to be created
object identifies the object for which the synonym is created
Removing a Synonym
To remove a synonym, use the DROP SYNONYM statement. Only the database administrator
can drop a public synonym.
DROP SYNONYM synonym;
34 | P a g e