SQL Fundamentals Certification€¦ · · 2016-02-012016-02-01 · @ Ashik’s Edition Page 2 SQL...
Transcript of SQL Fundamentals Certification€¦ · · 2016-02-012016-02-01 · @ Ashik’s Edition Page 2 SQL...
SQL Fundamentals Certification (Exam: 1Z0-051)
Edited By
(Md. Ashikur Ul Alam)
March,2016
@ Ashik’s Edition Page 1
Index
Retrieving data using the SQL-------------- 3
Select Statement
Restricting and Sorting Data---------------- 9
Using Single-Row Functions--------------- 15
Using Conversion Functions--------------- 19
Using Conditional Expressions------------ 31
Conditional Functions----------------------- 33
Using Group functions---------------------- 35
Get Data from Multiple Tables------------- 39
Sub-queries to Solve Queries--------------- 44
sing the Set Operators----------------------- 48
sing Manipulating Data--------------------- 53
sing DDL Statements----------------------- 59
Creating Other Schema Objects----------- 60
@ Ashik’s Edition Page 2
SQL Fundamentals Certification 1Z0-051
(Oracle Certified Oracle Database 11g Administrator)
Oracle's Oracle Database 11g: SQL Fundamentals exam is part of the Oracle Certified Oracle
Database 11g Administrator track, combining training, experience, and testing to endorse
candidates with a strong foundation and expertise in the industry’s most advanced database
management system.
This certification is to put you on the short list for winning Oracle SQL-Based projects. An
Oracle Technical Certification is a valuable, industry-recognized credential that signifies a
proven level of knowledge and skill.
Oracle Database: SQL Fundamentals I - only available as part of Oracle Database: Introduction
to SQL (Bundle) in some regions and Exam 051 has been validated against Oracle Database 10g
and 11g Release 2 version 11.2.0.1.0. This exam can be taken online as a non-proctored exam, or
in a test center as a proctored exam.
Exam Number 1Z0-051
Exam Name Oracle Database 11g: SQL Fundamentals
Certification Track Oracle Certified Oracle Database 11g Administrator
Exam Product Version SQL and PL/SQL
Exam Fees US$ 12P a g e | 25
Number of Questions 70
Duration 120 Minutes
Passing Score 60%
Questions format Multiple Choice
Audience
This certification is primarily good for developer, application developers, PL/SQL developer,
forms developer, system analysts, business analysts and data warehouse administrator. It is also
recommended to the entry-level and junior programmers wishing to start and/or continue down
the path of using SQL technologies and same time software developers and technical leads
wishing to solidify their SQL-related skill sets.
@ Ashik’s Edition Page 3
1.Retrieving data using the SQL Select
Statement
SQL is a comprehensive database language. SQL, pronounced Sequel or simply S-Q-L, is a
computer programming language used for querying relational databases following a
nonprocedural approach. When you extract information from a database using SQL, this is
termed querying the database.
A relational database is implemented through the use of a Relational Database Management
System (RDBMS). An RDBMS performs all the basic functions of the DBMS software
mentioned above along with a multitude of other functions that make the relational model easier
to understand and to implement. RDBMS users manipulate data through the use of a special data
manipulation language. Database structures are defined through the use of a data definition
language. The commands that system users execute in order to store and retrieve data can be
entered at a terminal with an RDBMS interface by typing the commands, or entered through use
of some type of graphical interface. The DBMS then processes the commands.
Capabilities of the SELECT Statement
Data retrieval from data base is done through appropriate and efficient use of SQL. Three
concepts from relational theory encompass the capability of the SELECT statement: projection,
selection, and joining.
Projection: A project operation selects only certain columns (fields) from a table. The
result table has a subset of the available columns and can include anything from a single
column to all available columns.
Selection: A select operation selects a subset of rows (records) in a table (relation) that
satisfy a selection condition. The ability to select rows from out of complete result set is
called Selection. It involves conditional filtering and data staging. The subset can range
from no rows, if none of the rows satisfy the selection condition, to all rows in a table.
Joining: A join operation combines data from two or more tables based on one or more
common column values. A join operation enables an information system user to process
the relationships that exist between tables. The join operation is very powerful because it
allows system users to investigate relationships among data elements that might not be
anticipated at the time that a database is designed.
@ Ashik’s Edition Page 4
Consider the above table structures. Fetching first_name name, department_id and salary for a
single employee from EMPLOYEES table is Projection. Fetching employee details whose salary
is less than 5000, from EMPLOYEES table is Selection. Fetching employee's first name,
department name by joining EMPLOYEES and DEPARTMENTS is joining.
Basic SELECT statement
The basic syntax for a SELECT statement is presented below.
SELECT [DISTINCT | ALL] {* | select_list}
FROM {table_name [alias] | view_name}
[{table_name [alias] | view_name}]...
[WHERE condition]
[GROUP BY condition_list]
[HAVING condition]
[ORDER BY {column_name | column_# [ ASC | DESC ] } ...
The SELECT clause is mandatory and carries out the relational project operation.
The FROM clause is also mandatory. It identifies one or more tables and/or views from which to
retrieve the column data displayed in a result table.
The WHERE clause is optional and carries out the relational select operation. It specifies which
rows are to be selected.
The GROUP BY clause is optional. It organizes data into groups by one or more column names
listed in the SELECT clause.
The optional HAVING clause sets conditions regarding which groups to include in a result table.
The groups are specified by the GROUP BY clause.
@ Ashik’s Edition Page 5
The ORDER BY clause is optional. It sorts query results by one or more columns in ascending or
descending order.
Arithmetic expressions and NULL values in the SELECT statement
An arithmetic expression can be creaeted using the column names, operators and constant values
to embed an expression in a SELECT statement. The operator applicable to a column depends on
column's data type. For example, arithmetic operators will not fit for character literal values. For
example,
SELECT employee_id, sal * 12 ANNUAL_SAL
FROM employees;
The above query contains the arithmetic expression (sal * 12) to calculate annual salary of each
employee.
Arithmetic operators
Operators act upon the columns (known as operands) to result into a different result. In case of
multiple operators in an expression, the order of evaulation is decided by the operator
precedence. Here are the elementary rules of precedence -
Multiplication and division occur before multiplication and division.
Operators on the same priority are evaluated from left to right.
Use paretheses to override the default behavior of the operators.
Below table shows the precedence of the operators, in such cases. Precedence Level Operator
Symbol Operation
Description Operator Precedence
Addition + Lowest
Subtraction - Lowest
Multiplication * Medium
Division / Medium
Brackets ( ) Highest
Examine the below queries (a), (b), and (c)
SQL> SELECT 2*35 FROM DUAL;
SQL> SELECT salary + 1500 FROM employees;
SQL> SELECT first_name, salary, salary + (commission_pct* salary) FROM
employees;
Query (a) multiplies two numbers, while (b) shows addition of $1500 to salaries of all
employees. Query (c) shows the addition of commission component to employee's salary. As per
the precedence, first commission would be calculated on the salary, and then added to the salary.
@ Ashik’s Edition Page 6
Column Alias
An alias is used to rename a column or an expression during display. The alias to a column or an
expression appears as the heading in the output of a query. It is useful in providing a meaningful
heading to long expressions in the SELECT query. By default, the alias appears in uppercase in
the query output without spaces. To override this behavior, alias must be enclosed within double
quotes to preserve the case and spaces in the alias name.
SELECT price * 2 as DOUBLE_PRICE, price * 10 "Double Price"
FROM products;
DOUBLE_PRICE Double Price
------------ ------------
39.9 39.9
60 60
51.98 51.98
Concatenation operators
Concatenation operator can be used to join two string values or expressions in a SELECT query.
The double vertical bar symbol is used as string concatenation operator. It is applicable only for
character and string column values resulting into a new character expression. Example
SQL> SELECT 'ORACLE'||' CERTIFICATION' FROM dual;
The above query shows concatenation of two character literals values.
Literals
Any hard coded value, which is not stored in database, in the SELECT clause, is known s Literal.
It can be number, character, or date value. Character and date values must be enclosed within
quotes. Consider the below SQL queries. examples of using literals of different data types in
SQL queries.
The query below uses two character literals to join them together.
SQL> SELECT 'ORACLE'||' CERTIFICATION' FROM DUAL
The query below uses character literals to pretty print the employee's salary.
SQL> SELECT first_name ||'earns'|| salary||' as of '|||sysdate
FROM employees
@ Ashik’s Edition Page 7
Quote Operator
The quote operator is used to specify the quotation mark delimiter of your own. You can chose a
convenient delimiter, depending on the data.
SELECT department_name|| ' Department' ||q'['s Manager Id: ]'|| manager_id
FROM departments;
NULL
If a column doesn't has a definite value, it is considered as NULL. NULL value denotes
unknown or unavailable. It is not zero for numeric values, not blank space for character values.
Columns with NULL value can be selected in a SELECT query and can be the part of an
arithmetic expression. Any arithmetic expression using NULL values results into NULL. For this
reason, columns with NULL value must be handled differently by specifying their alternate
values using Oracle supplied functions like NVL or NULLIF.
SQL> SELECT NULL + 1000 NUM
FROM DUAL;
NUM
--------
DISTINCT Keyword
If the data is expected to have duplicate results, use DISTINCT keyword to eliminate duplicates
and diplay only the unique results in the query output. Only the selected columns are validated
for duplication and the rows will be logically eliminated from the query output. To be noted, the
DISTINCT keyword must appear just after the SELECT clause.
The simple query below demonstrates the use of DISTINCT to display unique department ids
from EMPLOYEES table.
SQL> SELECT DISTINCT DEPARTMENT_ID
FROM employees;
DEPARTMENT_ID
---------------
10
20
30
40
@ Ashik’s Edition Page 8
DESCRIBE Command
The structural metadata of a table may be obtained by querying the database for the list of
columns that comprise it using the DESCRIBE command. It will list the used column names,
their null property and data type.
Syntax:
DESC[RIBE] [SCHEMA].object name
For example,
DESC EMPLOYEE
Will display the EMPLOYEE table structure i.e. columns, their data types, precision and null
able property.
@ Ashik’s Edition Page 9
2. Restricting and Sorting Data
The essential capabilities of SELECT statement are Selection, Projection and Joining. Displaying
specific columns from a table is known as a project operation. We will now focus on displaying
specific rows of output. This is known as a select operation. Specific rows can be selected by
adding a WHERE clause to a SELECT query. As a matter of fact, the WHERE clause appears
just after the FROM clause in SELECT query hierarchy. The sequence has to be maintained in
all scenarios. If violated, Oracle raises an exception.
Syntax:
SELECT *|{[DISTINCT] column| expression [alias],..}
FROM table
[WHERE condition(s)]
In the syntax,
WHERE clause is the keyword
[Condition] contains column names, expressions, constants, literals and a comparison
operator.
Suppose that your manager is working on the quarterly budget for your organization. As part of
this activity, it is necessary to produce a listing of each employee's essential details, but only for
employees that are paid at least $25,000 annually. The SQL query below accomplishes this task.
Note the use of the WHERE clause shown in bold text.
SELECT Employee_ID, Last_Name, First_Name, Salary
FROM employees
WHERE Salary >= 25000;
EMPLOYEE_ID LAST_NAME FIRST_NAME SALARY
---------- --------------- --------------- -----------
88303 Jones Quincey $30,550.00
88404 Barlow William $27,500.00
88505 Smith Susan $32,500.00
3 rows selected
Points to be noted -
A SELECT clause can contain only one WHERE clause. However, multiple filter
conditions can be appended to WHERE clause using AND or OR operator.
The columns, literals or expressions in a predicate clause must be of similar or
interconvertible data types.
Column alias cannot be used in the WHERE clause.
Character literals must be enclosed within single quotation marks and are case sensitive.
@ Ashik’s Edition Page 10
Date literals must be enclosed within single quotation marks and are format sensitive.
Default format is DD-MON-RR.
Comparison Operators
Comparison operators are used in predicates to compare one term or operand with another term.
SQL offers comprehensive set of equality, inequality and miscellaneous operators. They can be
used depending on the data and filter condition logic in the SELECT query. When you use
comparison operators in a WHERE clause, the arguments (objects or values you are comparing)
on both sides of the operator must be either a column name, or a specific value. If a specific
value is used, then the value must be either a numeric value or a literal string. If the value is a
character string or date, you must enter the value within single quotation marks (' ').
Oracle has nine comparison operators to be used in equality or inequality conditions.
Operator Meaning
= equal to
< less than
> greater than
>= greater than or equal to
<= less than or equal to
!= not equal to
<> not equal to
!> not greater than
!< not less than
Other Oracle operators are BETWEEN..AND, IN, LIKE, and IS NULL.
The BETWEEN Operator
The BETWEEN operator can be used to compare a column value within a definite range. The
specified range must have a lower and upper limit where both are inclusive during comparison.
Its use is similar to composite inequality operator (<= and >=). It can be used with numeric,
character and date type values.
For example, the WHERE condition SALARY BETWEEN 1500 AND 2500 in a SELECT
query will list those employees whose salary is between 1500 and 2500.
The IN Operator
The IN operator is used to test a column value in a given set of value. If the column can be
equated to any of the values from the given set, the condition is validated. The condition defined
using the IN operator is also known as the membership condition.
For example, the WHERE condition SALARY IN (1500, 3000, 2500) in a SELECT query will
restrict the rows where salary is either of 1500, 3000 or 2500.
@ Ashik’s Edition Page 11
The LIKE Operator
The LIKE operator is used for pattern matching and wildcard searches in a SELECT query. If a
portion of the column value is unknown, wildcard can be used to substitute the unknown part. It
uses wildcard operators to build up the search string, thus search is known as Wildcard search.
These two operators are Percentile ('%') and Underscore ('_'). Underscore ('_') substitutes a single
character while percentile ('%') replaces more than one characters. They can be used in
combination as well.
For example, the below SELECT query lists the first names of those employees whose last name
starts with 'SA'.
SELECT first_name
FROM employees
WHERE last_name LIKE 'SA%';
IS (NOT) NULL Conditions
To be noted, NULL values cannot be tested using equality operator. It is because NULL values
are unknown and unassigned while equality operator tests for a definite value. The IS NULL
operator serves as equality operator to check NULL values of a column.
For example, the WHERE condition COMMISSION_PCT IS NULL in a SELECT query will
list employees who don't have commission percentage.
Logical Operators
Multiple filter conditions can be added to the WHERE clause predicate. More than one condition
can be combined together using logical operators AND, OR and NOT.
AND: joins two or more conditions, and returns results only when all of the conditions
are true.
OR: joins two or more conditions, and it returns results when any of the conditions are
true.
NOT: negates the expression that follows it.
The AND operator links two or more conditions in a WHERE clause and returns TRUE only if
all the conditions are true. Suppose that a manager needs a list of female employees. Further, the
list should only include employees with last names that begin with the letter "E" or that come
later in the alphabet. Additionally, the result table should be sorted by employee last name. There
are two simple conditions to be met. The WHERE clause may be written as: WHERE Gender =
'F' AND last_name > 'E'.
SELECT last_name "Last Name", first_name "First Name", Gender "Gender"
FROM employees
WHERE Gender = 'F' AND last_name > 'E'
ORDER BY last_name;
@ Ashik’s Edition Page 12
The OR operator links more than one condition in a WHERE clause and returns TRUE if either
of the condition returns true. Suppose that your organizational manager's requirements change a
bit. Another employee listing is needed, but in this listing the employees should: (1) be female
or, (2) have a last name that begins with the letter "T" or a letter that comes later in the alphabet.
The result table should be sorted by employee last name. In this situation either of the two
conditions can be met in order to satisfy the query. Female employees should be listed along
with employees having a name that satisfies the second condition.
The NOT operator is used to negate an expression or conation.
The ORDER BY Clause
When you display only a few rows of data, it may be unnecessary to sort the output; however,
when you display numerous rows, managers may be aided in decision making by having the
information sorted. Output from a SELECT statement can be sorted by using the optional
ORDER BY clause. When you use the ORDER BY clause, the column name on which you are
ordering must also be a column name that is specified in the SELECT clause.
The below SQL query uses an ORDER BY clause to sort the result table by the last_name
column in ascending order. Ascending order is the default sort order.
SELECT last_name, first_name
FROM employees
WHERE last_name >= 'J'
ORDER BY last_name;
last_name first_name
--------------- ---------------
Jones Quincey
Klepper Robert
Quattromani Toni
Schultheis Robert
Sorting can be based on numeric and date values also. Sorting can also be done based on
multiple columns.
By default, the ORDER BY clause will sort output rows in the result table in ascending order.
We can use the keyword DESC (short for descending) to enable descending sort. The alternative
default is ASC which sorts in ascending order, but the ASC keyword is rarely used since it is the
default. When the ASC or DESC optional keyword is used, it must follow the column name on
which you are sorting in the WHERE clause.
Positional Sorting - Numeric position of the column in the selected column list can be given in
ORDER BY clause, instead of column name. It is mainly used in UNION queries (discussed
later). The Query orders the result set by salary since it appears 2nd in the column list.
SELECT first_name, salary
FROM employees
ORDER BY 2;
@ Ashik’s Edition Page 13
Substitution Variables
When a SQL query has to be executed more than once for the different set of inputs, substitution
variables can be used. Substitution variables can be used to prompt for user inputs before the
query execution. They are widely used in query based report generation which takes data range
from the users as input for the conditional filtering and data display. Substitution variables are
prefixed by a single-ampersand (&) symbol to temporarily store values. For example,
SELECT EMPLOYEE_ID, LAST_NAME, SALARY
FROM employees
WHERE LAST_NAME = &last_name
OR EMPLOYEE_ID = &EMPNO;
When the above SELECT query is executed, oracle identifies the '&' as substitution variable. It
prompts user to enter value for 'last_name' and 'EMPNO' as below.
Enter value for last_name:
Enter value for empno:
Once the user provides inputs to both the variables, values are substituted, query is verified and
executed.
Points to be noted -
If the variable is meant to substitute a character or date value, the literal needs to be
enclosed in single quotes. A useful technique is to enclose the ampersand substitution
variable in single quotes when dealing with character and date values.
Both SQL Developer and SQL* Plus support the substitution variables and the
DEFINE/UNDEFINE commands. Though SQL Developer or SQL* Plus does not
support validation checks (except for data type) on user input.
You can use the substitution variables not only in the WHERE clause of a SQL
statement, but also as substitution for column names, expressions, or text.
Using the Double-Ampersand Substitution Variable
When the same substitution variable is used at more than one place, then to avoid re-entering the
same data again, we use double ampersand substitution. In such cases, value of the substitution
variable, once entered, would be substituted at all instants of usage.
SELECT first_name, HIRE_DATE, SEPARATION_DATE
FROM employees
WHERE HIRE_DATE LIKE '%&DT%' AND SEPARATION_DATE '%&&DT%'
Note that the same value of &DT is substituted twice in the above query. So, its value once given
by the user will be substituted at two places.
@ Ashik’s Edition Page 14
The DEFINE and VERIFY Commands
Setting the definition of variables in a session is set by DEFINE feature of SQL* Plus. The
variables can be defined in the session, so as to avoid halt during query execution. Oracle reads
the same variable whenever encountered in an SQL query. It is in ON state by default. With the
help of DEFINE clause, one can declare a variable in command line before query execution as
DEFINE variable=value;.
Verify command verifies the above substitution showing as OLD and NEW statement. It is OFF
by default and can be set to ON using SET command.
SQL> SET DEFINE ON
SQL> SET VERIFY ON
SQL> DEFINE NAME = MARTIN'
SQL> SELECT first_name, SALARY
FROM employees
WHERE first_name = '&NAME';
OLD 1: select first_name, sal from employee where first_name =
'&first_name'
new 1: select first_name, sal from employee where first_name = 'MARTIN'
first_name SALARY
------- -------
MARTIN 5000
@ Ashik’s Edition Page 15
3. Using Single-Row Functions
Using Single row functions to customize output
Oracle SQL supplies a rich library of in-built functions which can be employed for various tasks.
The essential capabilities of a functions can be the case conversion of strings, in-string or
substring operations, mathematical computations on numeric data, and date operations on date
type values. SQL Functions optionally take arguments from the user and mandatorily return a
value.
On a broader category, there are two types of functions: -
Single Row functions - Single row functions are the one who work on single row and return one
output per row. For example, length and case conversion functions are single row functions.
Multiple Row functions - Multiple row functions work upon group of rows and return one
result for the complete set of rows. They are also known as Group Functions.
Single row functions
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.
o LPAD and RPAD functions pad the given string up to a specific length with a
given character.
o TRIM function trims the string input from the start or end.
@ Ashik’s Edition Page 16
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
General functions
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;
FIRST_NAME LAST_NAME SALARY
NVL(COMMISSION_PCT,0)
-------------------- ------------------------- ---------- -------------------
--
Steven King 24000
0
Neena Kochhar 17000
0
Lex De Haan 17000
0
Alexander Hunold 9000
0
Case Conversion functions
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;
UPPER(FIRST_NAME) INITCAP(LAST_NAME) LOWER(JOB_
-------------------- ------------------------- ----------
@ Ashik’s Edition Page 17
STEVEN King ad_pres
NEENA Kochhar ad_vp
LEX De Haan ad_vp
ALEXANDER Hunold it_prog
Character functions
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;
CONCAT(FIRST_NAME,LAST_NAME)
--------------------------------
EllenAbel
SundarAnde
MozheAtkinson
DavidAustin
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;
SUBST INSTR(FIRST_NAME,'A')
----- ---------------------
Ellen 0
Sunda 5
Mozhe 0
David 2
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;
RPAD(FIRST_NAME,10,'_')||
-------------------------
Steven____________AD_PRES
Neena_______________AD_VP
Lex_________________AD_VP
Alexander_________IT_PROG
Number functions
The SELECT query below demonstrates the use of ROUND and TRUNC functions.
@ Ashik’s Edition Page 18
SELECT ROUND (1372.472,1)
FROM dual;
ROUND(1372.472,1)
-----------------
1372.5
SELECT TRUNC (72183,-2)
FROM dual;
TRUNC(72183,-2)
---------------
72100
Date arithmetic operations
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;
EMPLOYEE_ID EMPLOYMENT_DAYS
----------- ---------------
100 3698.61877
101 2871.61877
102 4583.61877
103 2767.61877
Date functions
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;
EMPLOYEE_ID EMPLOYMENT_MONTHS
----------- -----------------
100 121.504216
101 94.3751837
102 150.633248
103 90.9558289
SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate)
FROM dual;
ADD_MONTH NEXT_DAY( LAST_DAY(
--------- --------- ---------
01-JAN-14 05-AUG-13 31-AUG-13
@ Ashik’s Edition Page 19
4. Using Conversion Functions
Besides the SQL utility functions, Oracle inbuilt function library contains type conversion
functions. There may be scenarios where the query expects input in a specific data type, but it
receives it in a different data type. In such cases, Oracle implicitly tries to convert the unexpected
value to a compatible data type which can be substituted in place and application continuity is
not compromised. Type conversion can be either implicitly done by Oracle or explicitly done by
the programmer.
Implicit data type conversion works based on a matrix which showcases the Oracle's support for
internal type casting. Besides these rules, Oracle offers type conversion functions which can be
used in the queries for explicit conversion and formatting. As a matter of fact, it is recommended
to perform explicit conversion instead of relying on software intelligence. Though implicit
conversion works well, but to eliminate the skew chances where bad inputs could be difficult to
typecast internally.
Implicit Data Type Conversion
A VARCHAR2 or CHAR value can be implicitly converted to NUMBER or DATE type value
by Oracle. Similarly, a NUMBER or DATA type value can be automatically converted to
character data by Oracle server. Note that the implicit inter conversion happens only when the
character represents the a valid number or date type value respectively.
For example, examine the below SELECT queries. Both the queries will give the same result
because Oracle internally treats 15000 and '15000' as same.
Query-1 SELECT employee_id,first_name,salary
FROM employees
WHERE salary > 15000;
Query-2 SELECT employee_id,first_name,salary
FROM employees
WHERE salary > '15000';
Explicit Data Type Conversion
SQL Conversion functions are single row functions which are capable of typecasting column
value, literal or an expression. TO_CHAR, TO_NUMBER and TO_DATE are the three
functions which perform cross modification of data types.
@ Ashik’s Edition Page 20
TO_CHAR function
TO_CHAR function is used to typecast a numeric or date input to character type with a format
model (optional).
Syntax TO_CHAR(number1, [format], [nls_parameter])
For number to character conversion, nls parameters can be used to specify decimal characters,
group separator, local currency model, or international currency model. It is an optional
specification - if not available, session level nls settings will be used. For date to character
conversion, the nls parameter can be used to specify the day and month names, as applicable.
Dates can be formatted in multiple formats after converting to character types using TO_CHAR
function. The TO_CHAR function is used to have Oracle 11g display dates in a particular
format. Format models are case sensitive and must be enclosed within single quotes.
Consider the below SELECT query. The query format the HIRE_DATE and SALARY columns
of EMPLOYEES table using TO_CHAR function.
SELECT first_name,
TO_CHAR (hire_date, 'MONTH DD, YYYY') HIRE_DATE,
TO_CHAR (salary, '$99999.99') Salary
FROM employees
WHERE rownum < 5;
FIRST_NAME HIRE_DATE SALARY
-------------------- ------------------ ----------
Steven JUNE 17, 2003 $24000.00
Neena SEPTEMBER 21, 2005 $17000.00
Lex JANUARY 13, 2001 $17000.00
Alexander JANUARY 03, 2006 $9000.00
The first TO_CHAR is used to convert the hire date to the date format MONTH DD, YYYY i.e.
month spelled out and padded with spaces, followed by the two-digit day of the month, and then
the four-digit year. If you prefer displaying the month name in mixed case (that is, "December"),
simply use this case in the format argument: ('Month DD, YYYY').
The second TO_CHAR function in Figure 10-39 is used to format the SALARY to display the
currency sign and two decimal positions.
Oracle offers comprehensive set of format models. The below table shows the list of format
models which can be used to typecast date and number values as character using TO_CHAR.
@ Ashik’s Edition Page 21
Format Model
Description
,(comma)
It returns a comma in the specified position. You can specify multiple commas in a
number format model. Restrictions: A comma element cannot begin a number
format model. A comma cannot appear to the right of a decimal character or
period in a number format model.
.(period) Returns a decimal point, which is a period (.) in the specified position. Restriction:
You can specify only one period in a number format model
$ Returns value with a leading dollar sign
0 Returns leading zeros. Returns trailing zeros.
9
Returns value with the specified number of digits with a leading space if positive or
with a leading minus if negative. Leading zeros are blank, except for a zero value,
which returns a zero for the integer part of the fixed-point number.
B Returns blanks for the integer part of a fixed-point number when the integer part is
zero (regardless of "0"s in the format model).
C Returns in the specified position the ISO currency symbol (the current value of the
NLS_ISO_CURRENCY parameter).
D
Returns in the specified position the decimal character, which is the current value
of the NLS_NUMERIC_CHARACTER parameter. The default is a period (.).
Restriction: You can specify only one decimal character in a number format model.
EEE Returns a value using in scientific notation.
FM Returns a value with no leading or trailing blanks.
G
Returns in the specified position the group separator (the current value of the
NLS_NUMERIC_CHARACTER parameter). You can specify multiple group separators
in a number format model. Restriction: A group separator cannot appear to the
right of a decimal character or period in a number format model
L Returns in the specified position the local currency symbol (the current value of the
NLS_CURRENCY parameter).
MI Returns negative value with a trailing minus sign (-). Returns positive value with a
trailing blank. Restriction: The MI format element can appear only in the last
@ Ashik’s Edition Page 22
position of a number format model.
PR Returns negative value in . It can appear only in the end of a number format model.
RN, rm Returns a value as Roman numerals in uppercase. Returns a value as Roman
numerals in lowercase. Value can be an integer between 1 and 3999.
S
Returns negative value with a leading or trailing minus sign (-). Returns positive
value with a leading or trailing plus sign (+). Restriction: The S format element can
appear only in the first or last position of a number format model.
TM "Text minimum". Returns (in decimal output) the smallest number of characters
possible. This element is case-insensitive.
U Returns in the specified position the "Euro" (or other) dual currency symbol (the
current value of the NLS_DUAL_CURRENCY parameter).
V Returns a value multiplied by 10n (and if necessary, round it up), where n is the
number of 9's after the "V".
X Returns the hexadecimal value of the specified number of digits.
TO_NUMBER function
The TO_NUMBER function converts a character value to a numeric datatype. If the string being
converted contains nonnumeric characters, the function returns an error.
Syntax TO_NUMBER (string1, [format], [nls_parameter])
The below table shows the list of format models which can be used to typecast character values
as number using TO_NUMBER.
Format Model Description
CC Century
SCC Century BC prefixed with -
YYYY Year with 4 numbers
SYYY Year BC prefixed with -
@ Ashik’s Edition Page 23
IYYY ISO Year with 4 numbers
YY Year with 2 numbers
RR Year with 2 numbers with Y2k compatibility
YEAR Year in characters
SYEAR Year in characters, BC prefixed with -
BC BC/AD Indicator
Q Quarter in numbers (1,2,3,4)
MM Month of year 01, 02...12
MONTH Month in characters (i.e. January)
MON JAN, FEB
WW Week number (i.e. 1)
W Week number of the month (i.e. 5)
IW Week number of the year in ISO standard.
DDD Day of year in numbers (i.e. 365)
DD Day of the month in numbers (i.e. 28)
D Day of week in numbers(i.e. 7)
DAY Day of the week in characters (i.e. Monday)
FMDAY Day of the week in characters (i.e. Monday)
DY Day of the week in short character description (i.e. SUN)
J Julian Day (number of days since January 1 4713 BC, where January 1 4713 BC is 1
in Oracle)
HH,H12 Hour number of the day (1-12)
HH24 Hour number of the day with 24Hours notation (0-23)
@ Ashik’s Edition Page 24
AM, PM AM or PM
MI, SS Number of minutes and seconds (i.e. 59) ,
SSSSS Number of seconds this day.
DS Short date format. Depends on NLS-settings. Use only with timestamp.
DL Long date format. Depends on NLS-settings. Use only with timestamp.
E Abbreviated era name. Valid only for calendars: Japanese Imperial, ROC Official,
Thai Buddha.
EE The full era name
FF The fractional seconds. Use with timestamp.
FF1..FF9 The fractional seconds. Use with timestamp. The digit controls the number of
decimal digits used for fractional seconds.
FM Fill Mode: suppresses blanks in output from conversion
FX Format Exact: requires exact pattern matching between data and format model.
IYY OR IY OR I The last 3,2,1 digits of the ISO standard year. Output only
RM The Roman numeral representation of the month (I .. XII)
RR The last 2 digits of the year.
RRRR The last 2 digits of the year when used for output. Accepts fout-digit years when
used for input.
SP Spelled format. Can appear of the end of a number element. The result is always in
english. For example month 10 in format MMSP returns "ten"
SPTH Spelled and ordinal format; 1 results in first.
TH Converts a number to it's ordinal format. For example 1 becoms 1st.
TS Short time format. Depends on NLS-settings. Use only with timestamp.
TZD Abbreviated time zone name. ie PST.
@ Ashik’s Edition Page 25
TZH,TZM Time zone hour/minute displacement.
TZR Time zone region
X Local radix character. In America this is a period (.)
The SELECT queries below accept numbers as character inputs and prints them following the
format specifier.
SELECT TO_NUMBER('121.23', '9G999D99')
FROM DUAL
TO_NUMBER('121.23','9G999D99')
------------------------------
121.23
SELECT TO_NUMBER('1210.73', '9999.99')
FROM DUAL;
TO_NUMBER('1210.73','9999.99')
------------------------------
1210.73
TO_DATE function
The function takes character values as input and returns formatted date equivalent of the same.
The TO_DATE function allows users to enter a date in any format, and then it converts the entry
into the default format used by Oracle 11g.
Syntax: TO_DATE( string1, [ format_mask ], [ nls_language ] )
A format_mask argument consists of a series of elements representing exactly what the data
should look like and must be entered in single quotation marks.
Format Model Description
YEAR Year, spelled out
YYYY 4-digit year
YYY,YY,Y Last 3, 2, or 1 digit(s) of year.
IYY,IY,I Last 3, 2, or 1 digit(s) of ISO year.
IYYY 4-digit year based on the ISO standard
@ Ashik’s Edition Page 26
RRRR Accepts a 2-digit year and returns a 4-digit year.
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
WW Week of year (1-53) where week 1 starts on the first day of the year and continues
to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends
on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI,SS Minute (0-59).
SSSSS Seconds past midnight (0-86399).
FF Fractional seconds. Use a value from 1 to 9 after FF to indicate the number of digits
in the fractional seconds. For example, 'FF4'.
AM,PM Meridian indicator
@ Ashik’s Edition Page 27
AD,BC AD, BC indicator
TZD Daylight savings information. For example, 'PST'
TZH,TZM,TZR Time zone hour/minute/region.
The following example converts a character string into a date:
SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American')
FROM DUAL;
TO_DATE('
---------
15-JAN-89
General Functions
General functions are used to handle NULL values in database. The objective of the general
NULL handling functions is to replace the NULL values with an alternate value. We shall briefly
see through these functions below.
NVL
The NVL function substitutes an alternate value for a NULL value.
Syntax: NVL( Arg1, replace_with )
In the syntax, both the parameters are mandatory. Note that NVL function works with all types
of data types. And also that the data type of original string and the replacement must be in
compatible state i.e. either same or implicitly convertible by Oracle.
If arg1 is a character value, then oracle converts replacement string to the data type compatible
with arg1 before comparing them and returns VARCHAR2 in the character set of expr1. If arg1
is numeric, then Oracle determines the argument with highest numeric precedence, implicitly
converts the other argument to that data type, and returns that data type.
The SELECT statement below will display 'n/a' if an employee has been not assigned to any job
yet i.e. JOB_ID is NULL. Otherwise, it would display the actual JOB_ID value.
SELECT first_name, NVL(JOB_ID, 'n/a')
FROM employees;
@ Ashik’s Edition Page 28
NVL2
As an enhancement over NVL, Oracle introduced a function to substitute value not only for
NULL columns values but also for NOT NULL columns. NVL2 function can be used to
substitute an alternate value for NULL as well as non NULL value.
Syntax: NVL2( string1, value_if_NOT_null, value_if_null )
The SELECT statement below would display 'Bench' if the JOB_CODE for an employee is
NULL. For a definite not null value of JOB CODE, it would show constant value 'Job Assigned'.
SQL> SELECT NVL2(JOB_CODE, 'Job Assigned', 'Bench')
FROM employees;
NULLIF
The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it
returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can't
be NULL.
Syntax: NULLIF (expr1, expr2)
Note that first argument can be an expression that evaluates to NULL, but it can't be the literal
NULL. Both the parameters are mandatory for the function to execute.
The below query returns NULL since both the input values, 12 are equal.
SELECT NULLIF (12, 12)
FROM DUAL;
Similarly, below query return 'SUN' since both the strings are not equal.
SELECT NULLIF ('SUN', 'MOON')
FROM DUAL;
COALESCE
COALESCE function, a more generic form of NVL, returns the first non-null expression in the
argument list. It takes minimum two mandatory parameters but maximum arguments have no
limit.
Syntax: COALESCE (expr1, expr2, ... expr_n )
Consider the below SELECT query. It selects the first not null value fed into address fields for an
employee.
@ Ashik’s Edition Page 29
SELECT COALESCE (address1, address2, address3) Address
FROM employees;
Interestingly, the working of COALESCE function is similar to IF..ELSIF..ENDIF construct.
The query above can be re-written as -
IF address1 is not null THEN
result := address1;
ELSIF address2 is not null THEN
result := address2;
ELSIF address3 is not null THEN
result := address3;
ELSE
result := null;
END IF;
Conditional Functions
Oracle provides conditional functions DECODE and CASE to impose conditions even in SQL
statement.
The DECODE function
The function is the SQL equivalence of IF….THEN….ELSE conditional procedural statement.
DECODE works with values/columns/expressions of all data types.
Syntax: DECODE (expression, search, result [, search, result]... [, default])
DECODE function compares expression against each search value in order. If equality exists
between expression and search argument, then it returns the corresponding result. In case of no
match, default value is returned, if defined, else NULL. In case of any type compatibility
mismatch, oracle internally does possible implicit conversion to return the results.
As a matter of fact, Oracle considers two nulls to be equivalent while working with DECODE
function.
SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL')
FROM DUAL;
DECOD
-----
EQUAL
If expression is null, then Oracle returns the result of the first search that is also null. The
maximum number of components in the DECODE function is 255.
SELECT first_name, salary, DECODE (hire_date, sysdate,'NEW
JOINEE','EMPLOYEE')FROM employees;
@ Ashik’s Edition Page 30
CASE expression
CASE expressions works on the same concept as DECODE but differs in syntax and usage.
Syntax: CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
Oracle search starts from left and moves rightwards until it finds a true condition, and then
returns result expression associated with it. If no condition is found to be true, and an ELSE
clause exists, then Oracle returns result defined with else. Otherwise, Oracle returns null.
The maximum number of arguments in a CASE expression is 255. All expressions count toward
this limit, including the initial expression of a simple CASE expression and the optional ELSE
expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit,
you can nest CASE expressions so that the return_expr itself is a CASE expression.
SELECT first_name, CASE WHEN salary < 200 THEN 'GRADE 1'
WHEN salary > 200 AND salary < 5000 THEN 'GRADE 2'
ELSE 'GRADE 3'
END CASE
FROM employees;
ENAM CASE
---- -------
JOHN GRADE 2
EDWIN GRADE 3
KING GRADE 1
@ Ashik’s Edition Page 31
5. Using Conditional Expressions
General Functions
General functions are used to handle NULL values in database. The objective of the general
NULL handling functions is to replace the NULL values with an alternate value. We shall briefly
see through these functions below.
NVL
The NVL function substitutes an alternate value for a NULL value.
Syntax: NVL( Arg1, replace_with )
In the syntax, both the parameters are mandatory. Note that NVL function works with all types
of data types. And also that the data type of original string and the replacement must be in
compatible state i.e. either same or implicitly convertible by Oracle.
If arg1 is a character value, then oracle converts replacement string to the data type compatible
with arg1 before comparing them and returns VARCHAR2 in the character set of expr1. If arg1
is numeric, then Oracle determines the argument with highest numeric precedence, implicitly
converts the other argument to that data type, and returns that data type.
The SELECT statement below will display 'n/a' if an employee has been not assigned to any job
yet i.e. JOB_ID is NULL. Otherwise, it would display the actual JOB_ID value.
SELECT first_name, NVL(JOB_ID, 'n/a')
FROM employees;
NVL2
As an enhancement over NVL, Oracle introduced a function to substitute value not only for
NULL columns values but also for NOT NULL columns. NVL2 function can be used to
substitute an alternate value for NULL as well as non NULL value.
Syntax: NVL2( string1, value_if_NOT_null, value_if_null )
The SELECT statement below would display 'Bench' if the JOB_CODE for an employee is
NULL. For a definite not null value of JOB CODE, it would show constant value 'Job Assigned'.
SQL> SELECT NVL2(JOB_CODE, 'Job Assigned', 'Bench')
FROM employees;
@ Ashik’s Edition Page 32
NULLIF
The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it
returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can't
be NULL.
Syntax: NULLIF (expr1, expr2)
Note that first argument can be an expression that evaluates to NULL, but it can't be the literal
NULL. Both the parameters are mandatory for the function to execute.
The below query returns NULL since both the input values, 12 are equal.
SELECT NULLIF (12, 12)
FROM DUAL;
Similarly, below query return 'SUN' since both the strings are not equal.
SELECT NULLIF ('SUN', 'MOON')
FROM DUAL;
COALESCE
COALESCE function, a more generic form of NVL, returns the first non-null expression in the
argument list. It takes minimum two mandatory parameters but maximum arguments have no
limit.
Syntax: COALESCE (expr1, expr2, ... expr_n )
Consider the below SELECT query. It selects the first not null value fed into address fields for an
employee.
SELECT COALESCE (address1, address2, address3) Address
FROM employees;
Interestingly, the working of COALESCE function is similar to IF….ELSIF….ENDIF construct.
The query above can be re-written as -
IF address1 is not null THEN
result := address1;
ELSIF address2 is not null THEN
result := address2;
ELSIF address3 is not null THEN
result := address3;
ELSE
result := null;
END IF;
@ Ashik’s Edition Page 33
6. Conditional Functions
Oracle provides conditional functions DECODE and CASE to impose conditions even in SQL
statement.
The DECODE function
The function is the SQL equivalence of IF….THEN….ELSE conditional procedural statement.
DECODE works with values/columns/expressions of all data types.
Syntax: DECODE (expression, search, result [, search, result]... [, default])
DECODE function compares expression against each search value in order. If equality exists
between expression and search argument, then it returns the corresponding result. In case of no
match, default value is returned, if defined, else NULL. In case of any type compatibility
mismatch, oracle internally does possible implicit conversion to return the results.
As a matter of fact, Oracle considers two nulls to be equivalent while working with DECODE
function.
SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL')
FROM DUAL;
DECOD
-----
EQUAL
If expression is null, then Oracle returns the result of the first search that is also null. The
maximum number of components in the DECODE function is 255.
SELECT first_name, salary, DECODE (hire_date, sysdate,'NEW
JOINEE','EMPLOYEE')
FROM employees;
CASE expression
CASE expressions works on the same concept as DECODE but differs in syntax and usage.
Syntax: CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
@ Ashik’s Edition Page 34
Oracle search starts from left and moves rightwards until it finds a true condition, and then
returns result expression associated with it. If no condition is found to be true, and an ELSE
clause exists, then Oracle returns result defined with else. Otherwise, Oracle returns null.
The maximum number of arguments in a CASE expression is 255. All expressions count toward
this limit, including the initial expression of a simple CASE expression and the optional ELSE
expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit,
you can nest CASE expressions so that the return_expr itself is a CASE expression.
SELECT first_name, CASE WHEN salary < 200 THEN 'GRADE 1'
WHEN salary > 200 AND salary < 5000 THEN 'GRADE 2'
ELSE 'GRADE 3'
END CASE
FROM employees;
ENAM CASE
---- -------
JOHN GRADE 2
EDWIN GRADE 3
KING GRADE 1
@ Ashik’s Edition Page 35
7. Using Group functions
Reporting Aggregate data using the Group functions
SQL has numerous predefined aggregate functions that can be used to write queries to produce
exactly this kind of information. The GROUP BY clause specifies how to group rows from a
data table when aggregating information, while the HAVING clause filters out rows that do not
belong in specified groups.
Aggregate functions perform a variety of actions such as counting all the rows in a table,
averaging a column's data, and summing numeric data. Aggregates can also search a table to find
the highest "MAX" or lowest "MIN" values in a column. As with other types of queries, you can
restrict, or filter out the rows these functions act on with the WHERE clause. For example, if a
manager needs to know how many employees work in an organization, the aggregate function
named COUNT(*) can be used to produce this information. The COUNT(*) function shown in
the below SELECT statement counts all rows in a table.
SELECT COUNT(*)
FROM employees;
COUNT(*)
----------
24
The result table for the COUNT(*) function is a single column from a single row known as a
scalar result or value. Notice that the result table has a column heading that corresponds to the
name of the aggregate function specified in the SELECT clause.
Some of the commonly used aggregate functions are as below -
SUM( [ALL | DISTINCT] expression )
AVG( [ALL | DISTINCT] expression )
COUNT( [ALL | DISTINCT] expression )
COUNT(*)
MAX(expression)
MIN(expression)
The ALL and DISTINCT keywords are optional, and perform as they do with the SELECT
clauses that you have learned to write. The ALL keyword is the default where the option is
allowed. The expression listed in the syntax can be a constant, a function, or any combination of
column names, constants, and functions connected by arithmetic operators. However, aggregate
functions are most often used with a column name. Except COUNT function, all the aggregate
functions consider NULL values.
@ Ashik’s Edition Page 36
There are two rules that you must understand and follow when using aggregates:
Aggregate functions can be used in both the SELECT and HAVING clauses (the
HAVING clause is covered later in this chapter).
Aggregate functions cannot be used in a WHERE clause. Its violation will produce the
Oracle ORA-00934 group function is not allowed here error message.
Illustrations
The below SELECT query counts the number of employees in the organization.
SELECT COUNT(*) Count
FROM employees;
COUNT
-----
24
The below SELECT query returns the average of the salaries of employees in the organization.
SELECT AVG(Salary) average_sal
FROM employees;
AVERAGE_SAL
-----------
15694
The below SELECT query returns the sum of the salaries of employees in the organization.
SELECT SUM(Salary) total_sal
FROM employees;
TOTAL_SAL
---------
87472
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;
OLDEST LATEST
--------- -----------
16-JAN-83 01-JUL-2012
@ Ashik’s Edition Page 37
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.
SELECT DEPARTMENT_ID, SUM(SALARY)
FROM employees;
DEPARTMENT_ID,
*
ERROR at line 2:
ORA-00937: not a single-group group function
(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, Oracle throws and exception as "ORA-
00979: not a GROUP BY expression".
(4) Aggregate functions cannot be used in a GROUP BY clause. Oracle will return the "ORA-
00934: group function not allowed" here error message.
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.
@ Ashik’s Edition Page 38
SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
The below query also produce 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;
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
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 use 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 the 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.
SELECT department_id, AVG(Salary)
FROM employees
HAVING AVG(Salary) > 33000;
ERROR at line 1: ORA-00937: not a single-group group function
@ Ashik’s Edition Page 39
8. Get Data from Multiple Tables
Displaying Data from Multiple Tables
The related tables of a large database are linked through the use of foreign and primary keys or
what are often referred to as common columns. The ability to join tables will enable you to add
more meaning to the result table that is produced. For 'n' number tables to be joined in a query,
minimum (n-1) join conditions are necessary. Based on the join conditions, Oracle combines the
matching pair of rows and displays the one which satisfies the join condition.
Joins are classified as below
Natural join (also known as an equijoin or a simple join) - Creates a join by using a
commonly named and defined column.
Non-equality join - Joins tables when there are no equivalent rows in the tables to be
joined-for example, to match values in one column of a table with a range of values in
another table.
Self-join - Joins a table to itself.
Outer join - Includes records of a table in output when there's no matching record in the
other table.
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.
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;
FIRST_NAME DNAME
---------- ------
MILLER DEPT 1
JOHN DEPT 1
MARTIN DEPT 2
EDWIN DEPT 2
@ Ashik’s Edition Page 40
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);
There are some limitations regarding the NATURAL JOIN. You cannot specify a LOB column
with a NATURAL JOIN. Also, columns involved in the join cannot be qualified by a table name
or alias.
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.
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;
@ Ashik’s Edition Page 41
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);
We can make use all comparison parameter discussed earlier like equality and inequality
operators, BETWEEN, IS NULL, IS NOT NULL, and RELATIONAL.
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;
FIRST_NAME SALARY DEPARTMENT_ID
@ Ashik’s Edition Page 42
---------- ---------- ----------
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
Left Outer Join
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 (+);
FIRST_NAME SALARY DEPARTMENT_ID
---------- ---------- ----------
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
Full Outer Join
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;
FIRST_NAME DEPARTMENT_ID
---------- --------------------
MAN -
JOHN 10
EDWIN 20
MILLER 10
MARTIN 20
- 30
6 rows selected.
@ Ashik’s Edition Page 43
Cartesian product or Cross join
For two entities A and B, A * B is known as Cartesian product. A Cartesian product consists of
all possible combinations of the rows from each of the tables. Therefore, when a table with 10
rows is joined with a table with 20 rows, the Cartesian product is 200 rows (10 * 20 = 200).For
example, joining the employee table with eight rows and the department table with three rows
will produce a Cartesian product table of 24 rows (8 * 3 = 24).
Cross join refers to the Cartesian product of two tables. It produces cross product of two tables.
The above query can be written using CROSS JOIN clause.
A Cartesian product result table is normally not very useful. In fact, such a result table can be
terribly misleading. If you execute the below query for the EMPLOYEES and DEPARTMENTS
tables, the result table implies that every employee has a relationship with every department, and
we know that this is simply not the case!
SELECT E.first_name, D.DNAME
FROM employees E,departments D;
Cross join can be written as,
SELECT E.first_name, D.DNAME
FROM employees E CROSS JOIN departments D;
@ Ashik’s Edition Page 44
9. Sub-queries to Solve Queries
A subquery is best defined as a query within a query. Subqueries enable you to write queries that
select data rows for criteria that are actually developed while the query is executing at run time.
More formally, it is the use of a SELECT statement inside one of the clauses of another SELECT
statement. n fact, a subquery can be contained inside another subquery, which is inside another
subquery, and so forth. A subquery can also be nested inside INSERT, UPDATE, and DELETE
statements. Subqueries must be enclosed within parentheses.
A subquery can be used any place where an expression is allowed providing it returns a single
value. This means that a subquery 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 subquery is used as part of a
FROM clause, it is treated like a virtual table or view. Subquery can be placed either in FROM
clause, WHERE clause or HAVING clause of the main query.
Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit
for nesting subqueries 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 subqueries nested beyond three or four levels.
A subquery SELECT statement is very similar to the SELECT statement used to begin a regular
or outer query.The complete syntax of a subquery 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 Subqueries
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.
@ Ashik’s Edition Page 45
Single Row Sub Query
A single-row subquery is used when the outer query's results are based on a single, unknown
value. Although this query type is formally called "single-row," the name implies that the query
returns multiple columns-but only one row of results. However, a single-row subquery can return
only one row of results consisting of only one column to the outer query.
In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.
SELECT first_name, salary, department_id
FROM employees
WHERE salary = (SELECT MIN (salary)
FROM employees);
A HAVING clause is used when the group results of a query need to be restricted based on some
condition. If a subquery'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)
Multiple Row Sub Query
Multiple-row subqueries are nested queries that can return more than one row of results to the
parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING
clauses. Since it returns multiple rows,it must be handled by set comparison operators (IN, ALL,
ANY).While IN operator holds the same meaning as discussed in earlier chapter, ANY operator
compares a specified value to each value returned by the sub query while ALL compares a value
to every value returned by a sub query.
Below query shows the error when single row sub query returns multiple rows.
SELECT first_name, department_id
FROM employees
WHERE department_id = (SELECT department_id
FROM employees
WHERE LOCATION_ID = 100)
department_id = (select
*
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row
@ Ashik’s Edition Page 46
Usage of Multiple Row operators
[> ALL] More than the highest value returned by the subquery
[< ALL] Less than the lowest value returned by the subquery
[< ANY] Less than the highest value returned by the subquery
[> ANY] More than the lowest value returned by the subquery
[= ANY] Equal to any value returned by the subquery (same as IN)
Above SQL can be rewritten using IN operator like below.
SELECT first_name, department_id
FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE LOCATION_ID = 100)
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.
A join would be better solution for above query, but for purpose of illustration, sub query has
been used in it.
Correlated Sub Query
As opposed to a regular subquery, where the outer query depends on values provided by the
inner query,a correlated subquery is one where the inner query depends on values provided by
the outer query. This means that in a correlated subquery,the inner query is executed repeatedly,
once for each row that might be selected by the outer query.
Correlated subqueries can produce result tables that answer complex management questions.
Consider the below SELECT query. Unlike the subqueries previously considered, the subquery
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 (DepartmentNumber) 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)
@ Ashik’s Edition Page 47
Multiple Column Sub Query
A multiple-column subquery returns more than one column to the outer query and can be listed
in the outer query's FROM, WHERE, or HAVING clause. For example, the below query shows
the employee's historical details for the ones whose current salary is in range of 1000 and 2000
and working in department 10 or 20.
SELECT first_name, job_id, salary
FROM emp_history
WHERE (salary, department_id) in (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000
AND department_id BETWEEN 10 and 20)
ORDER BY first_name;
When a multiple-column subquery 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 subquery'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 subquery is the data source for the main query.
SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000);
@ Ashik’s Edition Page 48
10. Using the Set Operators
Set operators are used to join the results of two (or more) SELECT statements. The SET
operators available in Oracle 11g are UNION,UNION ALL, INTERSECT, and MINUS.
The UNION set operator returns the combined results of the two SELECT statements.
Essentially, it removes duplicates from the results i.e. only one row will be listed for each
duplicated result. To counter this behavior, use the UNION ALL set operator which retains the
duplicates in the final result. INTERSECT lists only records that are common to both the
SELECT queries; the MINUS set operator removes the second query's results from the output if
they are also found in the first query's results. INTERSECT and MINUS set operations produce
unduplicated results.
All the SET operators share the same degree of precedence among them. Instead, during query
execution, Oracle starts evaluation from left to right or from top to bottom. If explicitly
parentheses are used, then the order may differ as parentheses would be given priority over
dangling operators.
Points to remember -
Same number of columns must be selected by all participating SELECT statements.
Column names used in the display are taken from the first query.
Data types of the column list must be compatible/implicitly convertible by oracle. Oracle
will not perform implicit type conversion if corresponding columns in the component
queries belong to different data type groups. For example, if a column in the first
component query is of data type DATE, and the corresponding column in the second
component query is of data type CHAR, Oracle will not perform implicit conversion, but
raise ORA-01790 error.
Positional ordering must be used to sort the result set. Individual result set ordering is not
allowed with Set operators. ORDER BY can appear once at the end of the query. For
example,
UNION and INTERSECT operators are commutative, i.e. the order of queries is not
important; it doesn't change the final result.
Performance wise, UNION ALL shows better performance as compared to UNION
because resources are not wasted in filtering duplicates and sorting the result set.
Set operators can be the part of sub queries.
Set operators can't be used in SELECT statements containing TABLE collection
expressions.
The LONG, BLOB, CLOB, BFILE, VARRAY, or nested table are not permitted for use
in Set operators. For update clause is not allowed with the set operators.
@ Ashik’s Edition Page 49
UNION
When multiple SELECT queries are joined using UNION operator, Oracle displays the
combined result from all the compounded SELECT queries, after removing all duplicates and in
sorted order (ascending by default), without ignoring the NULL values.
Consider the below five queries joined using UNION operator. The final combined result set
contains value from all the SQLs. Note the duplication removal and sorting of data.
SELECT 1 NUM FROM DUAL
UNION
SELECT 5 FROM DUAL
UNION
SELECT 3 FROM DUAL
UNION
SELECT 6 FROM DUAL
UNION
SELECT 3 FROM DUAL;
NUM
-------
1
3
5
6
To be noted, the columns selected in the SELECT queries must be of compatible data type.
Oracle throws an error message when the rule is violated.
SELECT TO_DATE('12-OCT-03') FROM DUAL
UNION
SELECT '13-OCT-03' FROM DUAL;
SELECT TO_DATE('12-OCT-03') FROM DUAL
*
ERROR at line 1:
ORA-01790: expression must have same datatype as corresponding expression
UNION ALL
UNION and UNION ALL are similar in their functioning with a slight difference. But UNION
ALL gives the result set without removing duplication and sorting the data. For example, in
above query UNION is replaced by UNION ALL to see the effect.
Consider the query demonstrated in UNION section. Note the difference in the output which is
generated without sorting and deduplication.
SELECT 1 NUM FROM DUAL
UNION ALL
SELECT 5 FROM DUAL
@ Ashik’s Edition Page 50
UNION ALL
SELECT 3 FROM DUAL
UNION ALL
SELECT 6 FROM DUAL
UNION ALL
SELECT 3 FROM DUAL;
NUM
-------
1
5
3
6
3
INTERSECT
Using INTERSECT operator, Oracle displays the common rows from both the SELECT
statements, with no duplicates and data arranged in sorted order (ascending by default).
For example, the below SELECT query retrieves the salary which are common in department 10
and 20.As per ISO SQL Standards, INTERSECT is above others in precedence of evaluation of
set operators but this is not still incorporated by Oracle.
SELECT SALARY
FROM employees
WHERE DEPARTMENT_ID = 10
INTRESECT
SELECT SALARY
FROM employees
WHERE DEPARTMENT_ID = 20
SALARY
---------
1500
1200
2000
MINUS
Minus operator displays the rows which are present in the first query but absent in the second
query, with no duplicates and data arranged in ascending order by default.
SELECT JOB_ID
FROM employees
WHERE DEPARTMENT_ID = 10
MINUS
SELECT JOB_ID
FROM employees
WHERE DEPARTMENT_ID = 20;
@ Ashik’s Edition Page 51
JOB_ID
-------------
HR
FIN
ADMIN
Matching the SELECT statement
There may be the scenarios where the compound SELECT statements may have different count
and data type of selected columns. Therefore, to match the column list explicitly, NULL columns
are inserted at the missing positions so as match the count and data type of selected columns in
each SELECT statement. For number columns, zero can also be substituted to match the type of
the columns selected in the query.
In the below query, the data type of employee name (varchar2) and location id (number) do not
match. Therefore, execution of the below query would raise error due to compatibility issue.
SELECT DEPARTMENT_ID "Dept", first_name "Employee"
FROM employees
UNION
SELECT DEPARTMENT_ID, LOCATION_ID
FROM departments;
ERROR at line 1:
ORA-01790: expression must have same datatype as corresponding expression
Explicitly, columns can be matched by substituting NULL for location id and Employee name.
SELECT DEPARTMENT_ID "Dept", first_name "Employee", NULL "Location"
FROM employees
UNION
SELECT DEPARTMENT_ID, NULL "Employee", LOCATION_ID
FROM departments;
Using ORDER BY clause in SET operations
The ORDER BY clause can appear only once at the end of the query containing compound
SELECT statements. It implies that individual SELECT statements cannot have ORDER BY
clause. Additionally, the sorting can be based on the columns which appear in the first SELECT
query only. For this reason, it is recommended to sort the compound query using column
positions.
The compound query below unifies the results from two departments and sorts by the SALARY
column.
@ Ashik’s Edition Page 52
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id=10
UNION
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id=20
ORDER BY 3;
@ Ashik’s Edition Page 53
11. Using Manipulating Data
Oracle provide Data Manipulation Language commands to exercise data operations in the
database. Data operations can be populating the database tables with the application or business
data, modifying the data and removing the data from the database, whenever required. Besides
the data operations, there are set of commands which are used to control these operations. These
commands are grouped as Transaction Control Language.
There are three types of DML statements involved in a logical SQL transaction namely, Insert,
Update, Delete and Merge. A transaction is the logical collection of DML actions within a
database session.
INSERT statement
The INSERT command is used to store data in tables. The INSERT command is often used in
higher-level programming languages such as Visual Basic.NET or C++ as an embedded SQL
command; however, this command can also be executed at the SQL*PLUS prompt in command
mode. There are two different forms of the INSERT command. The first form is used if a new
row will have a value inserted into each column of the row. The second form of the INSERT
command is used to insert rows where some of the column data is unknown or defaulted from
another business logic. This form of the INSERT command requires that you specify column
names for which data are being stored.
Syntax:
The below syntax can be followed if the values for all the columns in the table is definite and
known.
INSERT INTO table
VALUES (column1 value, column2 value,
...);
The below syntax can be used if only few columns from the table have to be populated with a
value. Rest of the columns can deduce their values either as NULL or from a different business
logic.
INSERT INTO table (column1 name, column2 name, . . .)
VALUES (column1 value, column2 value, . . .);
The INSERT statement below creates a new employee record in the EMPLOYEES table. Note
that it inserts the values for the primary columns EMPLOYEE_ID, FIRST_NAME, SALARY
and DEPARTMENT_ID.
INSERT INTO employees (EMPLOYEE_ID, FIRST_NAME, SALARY, DEPARTMENT_ID)
VALUES (130, 'KEMP', 3800, 10);
@ Ashik’s Edition Page 54
Otherwise, complete employee data can be inserted in the EMPLOYEES table without
specifying the column list using the below INSERT statement - provided the values are known
beforehand and must be in compliance with the data type and position of columns in the table.
INSERT INTO employees
VALUES (130, 'KEMP','GARNER', '[email protected]', '48309290',TO_DATE ('01-
JAN-2012'), 'SALES', 3800, 0, 110, 10);
Values to be inserted must be compatible with the data type of the column. Literals, fixed values
and special values like functions, SYSDATE, CURRENT_DATE, SEQ.CURRVAL
(NEXTVAL), or USER can be used as column values. Values specified must follow the generic
rules. String literals and date values must be enclosed within quotes. Date value can be supplied
in DD-MON-RR or D-MON-YYYY format, but YYYY is preferred since it clearly specifies the
century and does not depend on internal RR century calculation logic.
INSERT-AS-SELECT (IAS) statement
Data can be populated into the target table from the source table using INSERT..AS..SELECT
(IAS) operation. It’s a direct path read operation. It’s a simple way of creating copy of the data
from one table to another or creating a backup copy of the table which the source table
operations are online.
For example, data can be copied from EMPLOYEES table to EMP_HISTORY table.
INSERT INTO EMP_HISTORY
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, SALARY, DEPARTMENT_ID
FROM employees;
UPDATE statement
The UPDATE command modifies the data stored in a column. It can update single or multiple
rows at a time depending on the result set filtered by conditions specified in WHERE clause.
Note that Updating columns is different from altering columns. Earlier in this chapter, you
studied the ALTER command. The ALTER command changes the table structure, but leaves the
table data unaffected. The UPDATE command changes data in the table, not the table structure.
Syntax: UPDATE table
SET column = value [, column = value ...]
[WHERE condition]
From the syntax,
The SET column = expression can be any combination of characters, formulas, or functions that
will update data in the specified column name. The WHERE clause is optional, but if it is
included, it specifies which rows will be updated. Only one table can be updated at a time with
an UPDATE command.
@ Ashik’s Edition Page 55
The UPDATE statement below updates the salary of employee JOHN to 5000.
UPDATE employees
SET salary = 5000
WHERE UPPER (first_name) = 'JOHN';
Though WHERE predicates are optional, but must be logically appended so as to modify only
the required row in the table. The UPDATE statement below updates the salaries of all the
employees in the table.
UPDATE employees
SET salary = 5000;
Multiple columns can also be updated by specifying multiple columns in SET clause separated
by a comma. For example, if both salary and job role has to be changed to 5000 and SALES
respectively for JOHN, the UPDATE statement looks like,
UPDATE employees
SET SALARY = 5000,
JOB_ID = 'SALES'
WHERE UPPER (first_name) = 'JOHN';
1 row updated.
Another way of updating multiple columns of the same row shows the usage of subquery.
UPDATE employees
SET (SALARY, JOB_ID) = (SELECT 5000, 'SALES' FROM DUAL)
WHERE UPPER (ENAME) = 'JOHN'
DELETE statement
The DELETE command is one of the simplest of the SQL statements. It removes one or more
rows from a table. Multiple table delete operations are not allowed in SQL.The syntax of the
DELETE command is as below.
DELETE FROM table_name
[WHERE condition];
The DELETE command deletes all rows in the table that satisfy the condition in the optional
WHERE clause. Since the WHERE clause is optional, one can easily delete all rows from a table
by omitting a WHERE clause since the WHERE clause limits the scope of the DELETE
operation.
The below DELETE statement would remove EDWIN's details from EMP table.
DELETE employees
WHERE UPPER (ENAME) = 'EDWIN'
1 row deleted.
@ Ashik’s Edition Page 56
Note: DELETE [TABLE NAME] and DELETE FROM [TABLE NAME] hold the same
meaning.
The WHERE condition in the conditional delete statements can make use of subquery as shown
below.
DELETE FROM employees
WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID
FROM LOCATIONS
WHERE LOCATION_CODE = 'SFO')
TRUNCATE
Truncate is a DDL command which is used to flush out all records from a table but retaining the
table structure. It does not supports WHERE condition to remove the selected records.
Syntax: TRUNCATE [table name]
It is Auto Commit i.e. it commits the current active transaction in the session. Truncating the
table does not drops dependent indexes, triggers or table constraints. If a table A is parent of a
reference constraint of a table B in the database, the table A could not be truncated.
Transaction
A transaction is a logical unit of work done in database. It can either contain -
Multiple DML commands ending with a TCL command i.e. COMMIT or ROLLBACK
One DDL command
One DCL command
Beginning of a transaction is marked with the first DML command. It ends with a TCL, DDL or
DCL command. A TCL command i.e. COMMIT or ROLLBACK is issues explicitly to end an
active transaction. By virtue of their basic behavior, if any of DDL or DCL commands get
executed in a database session, commit the ongoing active transaction in the session. If the
database instance crashes abnormally, the transaction is stopped.
COMMIT, ROLLBACK and SAVEPOINT are the transaction control language. COMMIT
applies the data changes permanently into the database while ROLLBACK does anti-commit
operation. SAVEPOINT controls the series of a transaction by setting markers at different
transaction stages. User can roll back the current transaction to the desired save point, which was
set earlier.
COMMIT - Commit ends the current active transaction by applying the data changes
permanently into the database tables. COMMIT is a TCL command which explicitly ends the
transaction. However, the DDL and DCL command implicitly commit the transaction.
@ Ashik’s Edition Page 57
SAVEPOINT - Savepoint is used to mark a specific point in the current transaction in the
session. Since it is logical marker in the transaction, savepoints cannot be queried in the data
dictionaries.
ROLLBACK - The ROLLBACK command is used to end the entire transaction by discarding
the data changes. If the transaction contains marked savepoints, ROLLBACK TO SAVEPOINT
[name] can be used to rollback the transaction upto the specified savepoint only. As a result, all
the data changes upto the specified savepoint will be discarded.
Demonstration
Consider the EMPLOYEES table which gets populated with newly hired employee details
during first quarter of every year. The clerical staff appends each employee detail with a
savepoint, so as to rollback any faulty data at any moment during the data feeding activity. Note
that he keeps the savepoint names same as the employee names.
INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary,
department_id)
VALUES (105, 'Allen',TO_DATE ('15-JAN-2013','SALES',10000,10);
SAVEPOINT Allen;
INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary,
department_id)
VALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',10000,20);
SAVEPOINT Kate;
INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary,
department_id)
VALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',12000,30);
SAVEPOINT McMan;
Suppose, the data feeding operator realises that he has wrongly entered the salary of 'Kate' and
'McMan'. He rolls back the active transaction to the savepoint Kate and re-enters the employee
details for Kate and McMan.
ROLLBACK TO SAVEPOINT Kate;
INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary,
department_id)
VALUES (106, 'Kate',TO_DATE ('15-JAN-2013','PROD',12500,20);
SAVEPOINT Kate;
INSERT INTO employees (employee_id, first_name, hire_date, job_id, salary,
department_id)
VALUES (107, 'McMan',TO_DATE ('15-JAN-2013','ADMIN',13200,30);
SAVEPOINT McMan;
@ Ashik’s Edition Page 58
Once he is done with the data entry, he can commit the entire transaction by issuing COMMIT in
the current session.
Read Consistency
Oracle maintains consistency among the users in each session in terms of data access and
read/write actions.
When a DML occurs on a table, the original data values changed by the action are recorded in
the database undo records. As long as transaction is not committed into database, any user in
other session that later queries the modified data views the original data values. Oracle uses
current information in the system global area and information in the undo records to construct a
read-consistent view of a table's data for a query. Only when a transaction is committed, the
changes of the transaction made permanent. The transaction is the key to Oracle's strategy for
providing read consistency.
Start point for read-consistent views is generated on behalf of readers
Controls when modified data can be seen by other transactions of the database for reading or
updating
@ Ashik’s Edition Page 59
12. Using DDL Statements
Using DDL Statements to Create and Manage Tables
A schema is the collection of multiple database objects, which are known as schema objects.
These objects have direct access by their owner schema. Below table lists the schema objects.
Table - to store data
View - to project data in a desired format from one or more tables
Sequence - to generate numeric values
Index - to improve performance of queries on the tables
Synonym - alternative name of an object
One of the first steps in creating a database is to create the tables that will store an organization's
data. Database design involves identifying system user requirements for various organizational
systems such as order entry, inventory management, and accounts receivable. Regardless of
database size and complexity, each database is comprised of tables.
Creating the table
To create a table in the database, a DBA must have certain information in hand - the table name,
column name, column data types, and column sizes. All this information can be modified later
using DDL commands.
Table Naming Conventions -
The name you choose for a table must follow these standard rules:
The name must begin with a letter A-Z or a-z
Can contain numbers and underscores
Can be in UPPER of lower case
Can be up to 30 characters in length
Cannot use the same name of another existing object in your schema
Must not be a SQL reserved word
Following the above guidelines, 'EMP85' can be a valid table name. But 85EMP is not.
Similarly, UPDATE cannot be a chosen as a table name since it a SQL reserved keyword.
CREATE TABLE statement
The CREATE TABLE is a DDL statement which is used to create tables in the database. The
table gets created as soon as the CREATE TABLE script is executed and is ready to hold the
data onwards. The user must have the CREATE TABLE system privilege to create the table in
its own schema. But to create a table in any user's schema, user must have CREATE ANY
TABLE schema.
@ Ashik’s Edition Page 60
Here is the syntax of a basic CREATE TABLE statement. There may be many additional clauses
to explicitly provide the storage specifications or segment values.
CREATE TABLE [schema.]table
( { column datatype [DEFAULT expr] [column_constraint] ...
| table_constraint}
[, { column datatype [DEFAULT expr] [column_constraint] ...
| table_constraint} ]...)
[AS subquery]
In the above syntax, DEFAULT specifies default value which can be used during INSERT
statement if the column is ignored. It cannot contain references to other table columns or pseudo
columns (CURRVAL, NEXTVAL, LEVEL, and ROWNUM) except SYSDATE and USER, or
date constants that are not fully specified.
Constraints are the rules defined optionally at the column level or table level (covered later in
this chapter).These rules are checked during any data action (Insert, update) on the table and
raise error to abort the action upon its violation.
For example, the CREATE TABLE statement below creates a table EMP_TEST. Note the
column specifications, data type and precision.
CREATE TABLE SCOTT.EMP_TEST
(EMPID NUMBER,
ENAME VARCHAR2(100),
DEPARTMENT_ID NUMBER,
SALARY NUMBER,
JOB_ID VARCHAR2(3),
HIREDATE DATE,
COMM NUMBER);
A user can refer the tables from other user's schema by prefixing the username or schema with
the table name. For example, a user GUEST wishes to query the employee name and salary from
the EMP_TEST table which is owned by SCOTT. He can issue the below query -
SELECT ENAME, SALARY,
FROM GUEST.EMP_TEST;
A column can hold a default value during the time of table creation. It helps to restrict the NULL
values getting into the column. Default value can be deduced from either a literal, expression or
SQL function which must return a compatible data type to the column. In the below CREATE
TABLE statement, note that the LOCATION_ID column has default value 100.
CREATE TABLE SCOTT.DEPARTMENT
(DEPARTMENT_ID NUMBER,
DNAME VARCHAR2 (100),
LOCATION_ID NUMBER DEFAULT 100);
@ Ashik’s Edition Page 61
CTAS - Create table using subquery
A table can be created from an existing table in the database using a subquery option. It copies
the table structure as well as the data from the table. Data can also be copied based on conditions.
The column data type definitions including the explicitly imposed NOT NULL constraints are
copied into the new table.
The below CTAS script creates a new table EMP_BACKUP. Employee data of department 20
gets copied into the new table.
CREATE TABLE EMP_BACKUP
AS
SELECT * FROM EMP_TEST
WHERE department_id=20;
Data types
Data types are used to specify the basic behavior of a column in the table. On a broader basis,
column behavior can either belong to number, character or a date family. There are multiple
other subtypes which belong to these families.
Number data type
The NUMBER datatype encompasses both integer, fixed-point, and floating-point numeric
values. Early versions of Oracle defined different datatypes for each of these different types of
numbers, but now the NUMBER datatype serves all of these purposes. Choose the NUMBER
datatype when a column must store numerical data that can be used in mathematical calculations.
Occasionally, the NUMBER datatype is used to store identification numbers where those
numbers are generated by the DBMS as sequential numbers.
NUMBER (p, s), where p is the precision up to 38 digits and s is the scale (number of digits to
the right of the decimal point).The scale can range between -84 to 127.
NUMBER (p),is a fixed-point number with a scale of zero and a precision of p.
FLOAT [(p)],where p is the binary precision that can range from 1 to 126. If p is not specified
the default value is binary 126.
Date data type
For each DATE data type, Century, Year, Month, Day, Hour, Minute, Second are stored in
database. Every database system has a default date format that is defined by the initialization
parameter NLS_DATE_FORMAT. This parameter is usually set to DD-MON-YY.If you do not
specify a time, the default time is 12:00:00 a.m.
@ Ashik’s Edition Page 62
Character data type
Oracle supports three predefined character data types including CHAR, VARCHAR,
VARCHAR2, and LONG.VARCHAR and VARCHAR2 are actually synonymous, and Oracle
recommends using VARCHAR2 instead of VARCHAR. Use the CHAR data type when the
column will store character values that are fixed-length. For example, a Social Security number
(SSN) in the United States is assigned to every citizen and is always 9 characters in size (even
though an SSN is strictly composed of digits, the digits are treated as characters), and would be
specified as CHAR(9). Use the VARCHAR2 data type to store alphanumeric data that is
variable-length. For example, a customer name or address will vary considerably in terms of the
number of characters to be stored. The maximum size of a VARCHAR2 column is 4,000
characters.
LOB data type
Oracle provides several different LOB data types, including CLOB (character large object) and
BLOB (binary large object).Columns of these data types can store unstructured data including
text, image, video, and spatial data. The CLOB data type can store up to eight terabytes of
character data using the CHAR database character set. The BLOB data type is used to store
unstructured binary large objects such as those associated with image and video data where the
data is simply a stream of "bit" values. A BLOB data type can store up to eight terabytes of
binary data. The NCLOB data type can store character large objects in multi byte national
character set up to 8TB to 128TB.The BFILE data type value works as a file locator or pointer to
file on the server's file system. The maximum file size supported is 8TB to 128TB.
Constraints
Constraints are the set of rules defined in Oracle tables to ensure data integrity. These rules are
enforced placed for each column or set of columns. Whenever the table participates in data
action, these rules are validated and raise exception upon violation. The available constraint
types are NOT NULL, Primary Key, Unique, Check, and Foreign Key.
The below syntax can be used to impose constraint at the column level.
Syntax: column [data type] [CONSTRAINT constraint_name] constraint_type
All constraints except NOT NULL, can also be defined at the table level. Composite constraints
can only be specified at the table level.
NOT NULL Constraint
A NOT NULL constraint means that a data row must have a value for the column specified as
NOT NULL. If a column is specified as NOT NULL, the Oracle RDBMS will not allow rows to
@ Ashik’s Edition Page 63
be stored to the employee table that violate this constraint. It can only be defined at column level,
and not at the table level.
Syntax: COLUMN [data type] [NOT NULL]
UNIQUE constraint
Sometimes it is necessary to enforce uniqueness for a column value that is not a primary key
column. The UNIQUE constraint can be used to enforce this rule and Oracle will reject any rows
that violate the unique constraint. Unique constraint ensures that the column values are distinct,
without any duplicates.
Syntax:
Column Level:
COLUMN [data type] [CONSTRAINT <name>] [UNIQUE]
Table Level: CONSTRAINT [constraint name] UNIQUE (column name)
Note: Oracle internally creates unique index to prevent duplication in the column values. Indexes
would be discussed later in PL/SQL.
CREATE TABLE TEST
( ... ,
NAME VARCHAR2(20)
CONSTRAINT TEST_NAME_UK UNIQUE,
... );
In case of composite unique key, it must be defined at table level as below.
CREATE TABLE TEST
( ... ,
NAME VARCHAR2(20),
STD VARCHAR2(20) ,
CONSTRAINT TEST_NAME_UK UNIQUE (NAME, STD)
);
Primary Key
Each table must normally contain a column or set of columns that uniquely identifies rows of
data that are stored in the table. This column or set of columns is referred to as the primary key.
Most tables have a single column as the primary key. Primary key columns are restricted against
NULLs and duplicate values.
@ Ashik’s Edition Page 64
Points to be noted -
A table can have only one primary key.
Multiple columns can be clubbed under a composite primary key.
Oracle internally creates unique index to prevent duplication in the column values.
Indexes would be discussed later in PL/SQL.
Syntax:
Column level:
COLUMN [data type] [CONSTRAINT <constraint name> PRIMARY KEY]
Table level:
CONSTRAINT [constraint name] PRIMARY KEY [column (s)]
The following example shows how to use PRIMARY KEY constraint at column level.
CREATE TABLE TEST
( ID NUMBER CONSTRAINT TEST_PK PRIMARY KEY,
... );
The following example shows how to define composite primary key using PRIMARY KEY
constraint at the table level.
CREATE TABLE TEST
( ...,
CONSTRAINT TEST_PK PRIMARY KEY (ID)
);
Foreign Key
When two tables share the parent child relationship based on specific column, the joining column
in the child table is known as Foreign Key. This property of corresponding column in the parent
table is known as Referential integrity. Foreign Key column values in the child table can either
be null or must be the existing values of the parent table. Please note that only primary key
columns of the referenced table are eligible to enforce referential integrity.
If a foreign key is defined on the column in child table then Oracle does not allow the parent row
to be deleted, if it contains any child rows. However, if ON DELETE CASCADE option is given
at the time of defining foreign key, Oracle deletes all child rows while parent row is being
deleted. Similarly, ON DELETE SET NULL indicates that when a row in the parent table is
deleted, the foreign key values are set to null.
@ Ashik’s Edition Page 65
Syntax:
Column Level:
COLUMN [data type] [CONSTRAINT] [constraint name] [REFERENCES] [table name
(column name)]
Table level:
CONSTRAINT [constraint name] [FOREIGN KEY (foreign key column name)
REFERENCES] [referenced table name (referenced column name)]
The following example shows how to use FOREIGN KEY constraint at column level.
CREATE TABLE TEST
(ccode varchar2(5)
CONSTRAINT TEST_FK REFERENCES PARENT_TEST(ccode),
...
);
Usage of ON DELETE CASCADE clause
CREATE TABLE TEST
(ccode varchar2(5)
CONSTRAINT TEST_FK REFERENCES PARENT_TEST (ccode)
ON DELETE CASCADE,
...
);
Check constraint
Sometimes the data values stored in a specific column must fall within some acceptable range of
values. A CHECK constraint requires that the specified check condition is either true or
unknown for each row stored in the table. Check constraint allows to impose a conditional rule
on a column, which must be validated before data is inserted into the column. The condition
must not contain a sub query or pseudo column CURRVAL NEXTVAL, LEVEL, ROWNUM,
or SYSDATE.
Oracle allows a single column to have more than one CHECK constraint. In fact, there is no
practical limit to the number of CHECK constraints that can be defined for a column.
Syntax:
Column level:
COLUMN [data type] CONSTRAINT [name] [CHECK (condition)]
@ Ashik’s Edition Page 66
Table level:
CONSTRAINT [name] CHECK (condition)
The following example shows how to use CHECK constraint at column level.
CREATE TABLE TEST
( ...,
GRADE char (1) CONSTRAINT TEST_CHK
CHECK (upper (GRADE) in ('A','B','C')),
...
);
The following example shows how to use CHECK constraint at table level.
CREATE TABLE TEST
( ...,
CONSTRAINT TEST_CHK
CHECK (stdate < = enddate),
);
ALTER TABLE statement
A DBA can make changes to the table structure or column definitions after the table has been
created in the database. The DDL command ALTER TABLE is used to perform such actions.
Alter command provides multiple utilities exclusive for schema objects. The ALTER TABLE
statement is used to add, drop, rename, and modify a column in a table.
The below ALTER TABLE statement renames the table EMP to EMP_NEW.
ALTER TABLE EMP RENAME TO EMP_NEW;
The below ALTER TABLE statement adds a new column TESTCOL to the EMP_NEW table
ALTER TABLE EMP_NEW ADD (TESTCOL VARCHAR2 (100))
The below ALTER TABLE statement renames the column TESTCOL to TESTNEW.
ALTER TABLE EMP_NEW RENAME COLUMN TESTCOL TO TESTNEW
The below ALTER TABLE statement drop the column TESTNEW from EMP_NEW table
ALTER TABLE EMP_NEW DROP COLUMN TESTNEW;
The below ALTER TABLE statement adds primary key on the EMPLOYEE_ID column.
ALTER TABLE EMP_NEW ADD PRIMARY KEY (EMPLOYEE_ID)
The below ALTER TABLE statement drop the primary key.
@ Ashik’s Edition Page 67
ALTER TABLE EMP_NEW DROP PRIMARY KEY;
The below ALTER TABLE statement switches the table mode to read only.
ALTER TABLE EMP_NEW READ ONLY;
Read Only Tables
Read only tables came as an enhancement in Oracle 11g.It allows the tables to be used for read
only purpose. In earlier oracle versions, tables were made read only by granting SELECT
privilege to the other users, but owner still had the read write privilege. But now, if a table is set
as Read only, even owner doesn't have access on data manipulation.
Syntax: ALTER TALE [TABLE NAME] READ ONLY
ALTER TALE [TABLE NAME] READ WRITE
Illustration SQL>CREATE TABLE ORATEST (id NUMBER)
SQL>INSERT INTO ORATEST VALUES (1);
SQL>ALTER TABLE ORATEST READ ONLY;
SQL> INSERT INTO ORATEST VALUES (2);
INSERT INTO ORATEST VALUES (2)
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "TEST"."ORATEST"
SQL> UPDATE ORATEST SET id = 2;
UPDATE ORATEST SET id = 2
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "TEST"."ORATEST"
SQL> DELETE FROM ORATEST;
DELETE FROM ORATEST
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "TEST"."ORATEST"
SQL> TRUNCATE TABLE ORATEST;
TRUNCATE TABLE ORATEST
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "TEST"."ORATEST"
SQL> ALTER TABLE ORATEST ADD (description VARCHAR2 (50));
ALTER TABLE ORATEST ADD (description VARCHAR2 (50))
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "TEST"."ORATEST"
@ Ashik’s Edition Page 68
SQL> ALTER TABLE ORATEST READ WRITE;
Table altered.
SQL> DELETE FROM ORATEST;
1 row deleted.
DROP TABLE statement
The DROP TABLE statement is used to remove a table from the database. The dropped table
and its data remain no longer available for selection. Dropped table can be recovered using
FLASHBACK utility, if available in recycle bin. Dropping a table drops the index and triggers
associated with it.
Syntax: DROP TABLE [TABLE NAME] [PURGE]
The below statement will drop the table and place it into the recycle bin.
DROP TABLE emp_new;
The below statement will drop the table and flush it out from the recycle bin also.
DROP TABLE emp_new PURGE;
@ Ashik’s Edition Page 69
13. Creating Other Schema Objects
Apart from tables, other essential schema objects are view, sequences, indexes and synonyms. A
view is a logical or virtual table. Synonyms are simply alias names for database objects.
Synonyms also simplify query writing and provide an element of system security by disguising
the actual name of a database object. Sequences are special database objects that support the
automatic generation of integer values, and are often used to generate primary key values for
tables. Indexes are created on table columns to facilitate the rapid retrieval of information from
tables.
Views
A database view is a logical or virtual table based on a query. Views are queried just like tables.
This means that from your perspective as a developer or from a database system user's
perspective, a view looks like a table. The definition of a view as an object is stored within a
database's data dictionary; however, a view stores no data itself. A database also stores the
execution plan for creating a view-this means that data can be retrieved rapidly through use of a
view even though the actual data presented by a SELECT query of a view is not stored as part of
a view. Rather, the data is "gathered together" each time that a view is queried from the database
tables for which a view is defined-these are termed base tables.
The general syntax is given below.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW [ViewName]
[(Column Alias Name...)]
AS [Query]
[WITH [CHECK OPTION] [READ ONLY] [CONSTRAINT]];
From the syntax,
The FORCE option allows a view to be created even if a base table that the view references does
not already exist. This option is used to create a view prior to the actual creation of the base
tables and accompanying data.
The NOFORCE option is the opposite of FORCE and allows a system user to create a view if
they have the required privileges to create a view, and if the tables from which the view is
created already exist. This is the default option.
The WITH READ ONLY option allows creation of a view that is read-only. You cannot use the
DELETE,INSERT, or UPDATE commands to modify data for a read-only view.
The WITH CHECK OPTION clause allows the update of rows that can be selected through the
view. It also enables you to specify constraints on values. The CONSTRAINT clause works in
conjunction with the WITH CHECK OPTION clause to enable a database administrator to
assign a unique name to the CHECK OPTION. If a database administrator omits the
@ Ashik’s Edition Page 70
CONSTRAINT clause, Oracle will automatically assign the constraint a system-generated name
that will not be very meaningful.
Types of Views
A Simple view is created on top of one table only. It is a simple SELECT query with no
functions or group clause, but just selection of columns from the table without any
transformation. If a DML is performed on the view, it is straightaway reflected in the base table.
A Complex view is created on multiple tables using joins. It can contain SQL functions, Group
by functions. But since the view is on multiple data and selection of columns is also not simple,
it does not allow DML operation on it.
Illustration
Simple View: The below simple view select employee name, department id and salary for the
employees with JOB ID as DEV.
CREATE OR REPLACE VIEW v_emp_dev
AS
SELECT first_name, department_id, salary
FROM employees
WHERE job_id = 'DEV';
Complex view: The below example shows the department name, average salary drawn in the
department and the count of employees working in it.
CREATE OR REPLACE VIEW EMP_VU
AS
SELECT department_name, AVG (salary) avg_sal, COUNT (first_name) count
FROM employees E, departments D
WHERE E.department_id = D.department_id
GROUP BY department_name;
DESCRIBE [view name] describes the view structure. Columns are listed in the same sequence
as in the view definition.
DML operations on a View
DML operations can be easily exercised on simple views. As stated earlier, the insert, update and
delete operations actually happen on the base table.
When you execute an UPDATE, DELETE, or INSERT DML statement on a view, you are
actually manipulating the data rows for the base table or tables on which the view is defined.
There are restrictions on the use of UPDATE, DELETE, and INSERT statements with views.
First, to use the UPDATE, DELETE, or INSERT statement with a view, the view must be
updateable. A view is updateable if the SELECT clause does not specify any aggregate function
@ Ashik’s Edition Page 71
in the SELECT listing. Additionally, the view could not have been created through use of a
GROUP BY, DISTINCT, or UNION clause or clauses. It is permissible for aggregate functions
to be used in a SELECT subquery in a FROM clause. Also, the view cannot have any derived
columns in the SELECT list. Next, if a view is created as the result of a JOIN operation (a join
view), the UPDATE and INSERT statements can only modify or insert rows into one of the base
tables at a time. You cannot modify rows from two or more tables with a single data
manipulation language (DML) statement. Finally, a DELETE statement can only execute against
a view if a table is referenced in a FROM clause. This simply means that you cannot delete rows
from a table that has not been specified.
WITH CHECK OPTION clause
WITH CHECK OPTION is an optional clause that specifies the level of checking to be done
when inserting or updating data through a view. If a view is created using WITH CHECK
OPTION clause, every row which gets inserted or updated in the base table through the view
must comply with the view definition. Note that the option cannot be specified if the view is
created as read-only.
For example, a view V_EMP_DEV is created for employees who are developers
(JOB_ID=DEV).
CREATE OR REPLACE VIEW v_emp_dev
AS
SELECT first_name, department_id, salary,
FROM employees
WHERE job_id = 'DEV'
WITH CHECK OPTION empvu_dev;
A user attempts to update salary of an HR employee through the view but encounters an
exception. Its because the view was created WITH CHECK OPTION.
UPDATE v_emp_dev
SET salary = salary+500
WHERE JOB_ID = 'HR';
ORA-01402: view WITH CHECK OPTION where-clause violation
If it would have been a simple view, the UPDATE statement would not have raised any
exception.
Dropping the view
A database administrator (DBA) or view owner can drop a view with the DROP VIEW
statement. If a view has defined constraints, then you need to specify the CASCADE
CONSTRAINTS clause when dropping a view; otherwise, the DROP VIEW statement fails to
process. If another view or other database object such as a synonym or materialized view (both
of these objects are discussed later in this chapter) references a dropped view, Oracle does not
@ Ashik’s Edition Page 72
drop these database objects; rather, Oracle marks them as invalid. You can drop these invalid
objects or redefine them in order to make them valid again.
The below DROP VIEW command drops the view EMP_VU from the database.
DROP VIEW EMP_VU;
Sequences
Oracle provides the capability to generate sequences of unique numbers for this type of use, and
they are called sequences. Generally, sequences are used to generate unique, sequential integer
values that are used as primary key values in database tables. A sequence of numbers can be
generated in either ascending or descending order. Note that a number once generated by
sequence cannot be rolled back.
Syntax CREATE SEQUENCE <sequence name>
[INCREMENT BY < number >]
[START WITH < start value number>]
[MAXVALUE < MAXIMUM VLAUE NUMBER>]
[NOMAXVALUE]
[MINVALUE < minimum value number>]
[CYCLE | NOCYCLE]
[CACHE < number of sequence value to cache> | NOCACHE]
[ORDER | NOORDER];
From the syntax,
The CREATE SEQUENCE statement must specify a unique sequence name. This is the only
required clause in the statement. If you do not specify any of the other clauses, all sequence
numbers generated will follow the Oracle default settings.
The INCREMENT BY clause determines how a sequence increments as each number is
generated. The default increment is one; however, If you have a good reason for a sequence to
skip numbers, you can specify a different increment. A positive numeric increment generates
ascending sequence numbers with an interval equal to the interval you select. A negative
numeric increment generates descending sequence numbers.
The START WITH clause specifies the starting numeric value for the sequence-the default
starting number is one. Additionally, you must specify a start value if you already have some
rows with data in the column that will now store sequence values.
The MAXVALUE clause specifies the maximum value to which a sequence can be incremented.
In the absence of a MAXVALUE, the maximum allowable value that can be generated for a
sequence is quite large, 10 to the 27th power - 1. The default is NOMAXVALUE.
The MINVALUE clause specifies the minimum value of a sequence for a decrementing
sequence (one that generates numbers in descending order). The default is NOMINVALUE.
@ Ashik’s Edition Page 73
The CYCLE clause specifies that sequence values can be reused if the sequence reaches the
specified MAXVALUE. If the sequence cycles, numbers are generated starting again at the
START WITH value.
The CACHE clause can improve system performance by enabling Oracle to generate a specified
batch of sequenced numbers to be stored in cache memory.
If you specify CACHE without specifying a number, the default cache size is 20 sequence
numbers. Optionally, you can specify NOCACHE to prevent the cache of sequence numbers.
The ORDER clause specifies that sequence numbers are allocated in the exact chronological
order in which they are requested.
NEXTVAL and CURRVAL
Sequence values are generated through the use of two pseudo columns named currval and
nextval. A pseudo column behaves like a table column, but pseudo columns are not actually
stored in a table. The first time you select the nextval pseudo column, the initial value in the
sequence is returned. Subsequent selections of the nextval pseudo column cause the sequence to
increment as specified in the INCREMENT BY clause and return the newly generated sequence
value. The currval pseudo column returns the current value of the sequence, which is the value
returned by the last reference to nextval.
In a session, NEXTVAL, and not the CURRVAL must be the first action on the sequence. This
is because in a session, when NEXTVAL generates the first number of the session from the
sequence, Oracle keeps the current value in the CURRVAL.
Syntax: Sequence.NEXTVAL
Sequence.CURRVAL
Points to be noted -
CURRVAL and NEXTVAL can only be used in the Outer SQL of a select statement.
CURRVAL and NEXTVAL can be used in INSERT statement to substitute a column
primary key. It can be used both as a subquery clause and also in VALUES clause.
CURRVAL and NEXTVAL can be used to update values in the tables.
CURRVAL and NEXTVAL cannot be in VIEW select list, with DISTINCT keyword,
with GROUP BY, HAVING, or ORDER BY clauses, and DEFAULT expression in a
CREATE TABLE or ALTER TABLE statement.
Modifying the sequence
@ Ashik’s Edition Page 74
Sequence owner can modify a sequence to alter the attributes like INCREMENT BY value,
MINVALUE, MAXVALUE, CYCLE or CACHE clauses only. Note that the changes done
would be reflected in the upcoming numbers.
Syntax: ALTER SEQUENCE [sequence name]
INCREMENT BY n
MAXVALUE n
NOCACHE
NOCYCLE
Dropping the sequence
The DROP SEQUENCE command drops sequences that need to be recreated or are no longer
needed.
DROP SEQUENCE [sequence name]
Indexes
Indexes are the database objects that are used to tune the performance of the SELECT query.
There are different types of indexes including those used to enforce primary key constraints,
unique indexes, non-unique indexes, and concatenated indexes, among others. Without indexes,
queries would require Oracle to scan all rows in a table in order to return the required rows for
the result table. An index is created on table columns, which then stores all the values of the
column under index segment. Unlike sequence, indexes are table specific. They are
automatically dropped once the table has been dropped.
Indexes can be created automatically or manually. When you specify a PRIMARY KEY
constraint or UNIQUE constraint, Oracle will automatically create a unique index to support
rapid data retrieval for the specified table.
Alternatively, user can create indexes manually to optimize the query performance. Manually
created indexes can be unique or non unique. Non-unique indexes can be B-Tree, Bitmap or
Function based index. By default, Oracle creates B-Tree indexes on columns. Here is the syntax
Syntax CREATE [UNIQUE][BITMAP]INDEX index
ON table (column [, column]...);
Note that UNIQUE and BITMAP must be specified only for unique and bitmap indexes. By
default, Oracle creates B-Tree indexes for normal indexes.
A composite index (also called a concatenated index) is an index created on multiple columns of
a table. Columns in a composite index can appear in any order and need not be adjacent columns
in the table. Composite indexes enhance row retrieval speed for queries in which the WHERE
@ Ashik’s Edition Page 75
clause references all or the leading portion of the columns in the composite index. An index can
contain a maximum of 32 columns.
For example, a user creates index IDX_EMP on HIRE_DATE column of EMPLOYEES table.
The index usage will reduce the disk I/O by traversing the indexed path scan and finds the data
which is filtered on HIRE_DATE column.
CREATE INDEX IDX_EMP ON employees(hire_date);
Dropping the Index
Indexes cannot be modified but can be altered for analysis, rebuilding or stats computation
purposes. If the index definition has to be modified, it has to be dropped and recreated. The
syntax of the DROP INDEX command is simple.
DROP INDEX index_name;
Synonyms
A synonym is an alias, that is, a form of shorthand used to simplify the task of referencing a
database object. The concept is analogous to the use of nicknames for friends and acquaintances.
Referencing an object owned by another user requires the schema name to be prefixed with it.
With the help of a synonym, you reduce the effort of referencing the object along with the
schema name. In this way, synonym provides location transparency because the synonym name
hides the actual object name and its owner.
There are two categories of synonyms, public and private. A public synonym can be used to
allow easy access to an object for all system users. In fact, the individual creating a public
synonym does not own the synonym-rather, it will belong to the PUBLIC user group that exists
within Oracle. Private synonyms, on the other hand, belong to the system user that creates them
and reside in that user's schema.
Syntax CREATE [PUBLIC] SYNONYM [synonym name]
FOR OBJECT;
A system user can grant the privilege to use private synonyms that they own to other system
users. In order to create synonyms, you need to have the CREATE SYNONYM privilege.
Further, you must have the CREATE PUBLIC SYNONYM privilege in order to create public
synonyms. If a synonym is declared as public, the synonym name cannot already be in use as a
public synonym. Attempting to create a public synonym that already exists will cause the
CREATE PUBLIC SYNONYM command to fail, and Oracle will return the ORA-00955: name
is already used by an existing object error message.
@ Ashik’s Edition Page 76
Illustration
Consider two users U1 and U2.U1 has access to EMPLOYEES table. So to enable the access on
EMPLOYEES table to U2 also, a synonym can be created in U2 schema. Access must be granted
by U1 to U2.
CONN U2/U2
SQL> CREATE SYNONYM EMP_SYN FOR U1.employees;
CONN U1/U1
SQL> GRANT ALL ON EMP_SYN TO U2;
CONN U2/U2
SQL> SELECT * FROM EMP_SYN;
Dropping a Synonym
A uer can drop the synonym which it owns. To drop a public synonym, you must have the DROP
PUBLIC SYNONYM privilege.
DROP SYNONYM EMP_SYN;
Reference
http://www.tutorialspoint.com/sql_certificate/index.htm