Oracle SQL Sat PDF
Oracle SQL Sat PDF
Data Base
User
Schema
Table
Colums/Rows
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 1 of 89
There are four types of SQL Statements
1. D.D.L (Data Define Language)
2. D.C.L (Data Control Language)
3. D.M.L (Data Manipulation Language)
4. T.C.L (Transaction Control Language)
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 2 of 89
Writing Basic SQL SELECT Statements
SQL is an ANSI (American National Standards Institute) standard computer language
for accessing and manipulating databases. SQL statements are used to retrieve and
update data in a database. SQL works with database programs like MS Access, DB2,
Informix, MS SQL Server, Oracle, Sybase, etc.
What is SQL?
SQL stands for Structured Query Language
SQL allows you to access a database
SQL is an ANSI standard computer language
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
SQL can update records in a database
SQL is easy to learn
SQL Queries
With SQL, we can query a database and have a result set returned.
A query like this:
What is Clause?
SELECT ...
FROM ...
WHERE ...
ORDER BY ...
GROUP BY ...
etc.
What is Keyword?
SELECT
FROM
WHERE
ORDER BY
GROUP BY
etc.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 3 of 89
What is SQL Statement?
SELECT * FROM EMP;
SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP;
SELECT * FROM EMP WHERE SAL>2000;
etc.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 4 of 89
Tab is listing the table and views
SQL>select * from tab;
TABLE_NAME TABLE_TYPE
------------------------------------------------
BONUS TABLE
DEPT TABLE
EMP TABLE
EMP_ATTEND TABLE
EMP_COP TABLE
EMP_COPY TABLE
EMP_TEST VIEW
S4 SEQUENCE
SALGRADE TABLE
How to display structure of a table?
Mean how many columns are there in a table, data type, width and either null is allowed or not. User
DESCRIBE / DESC command
There are eight columns in EMP table. Data type and width of each column is also displayed.
NOT NULL is written in front of EMPNO.
SQL> DESC DEPT
Name Null? Type
------------------------------- -------- ----
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 5 of 89
Selecting specific columns and notice the heading of each column.
SQL>Select empno, ename, job, sal from emp;
JOB SAL
--------- -------------------
CLERK 800
SALESMAN 1600
SALESMAN 1250
MANAGER 2975
SALESMAN 1250
MANAGER 2850
MANAGER 2450
ANALYST 3000
PRESIDENT 5000
SALESMAN 1500
CLERK 1100
CLERK 950
ANALYST 3000
CLERK 1300
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 6 of 89
ORDER BY Clause
Sorting Data
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 7 of 89
Sorting By Column Position
SQL> SELECT * FROM EMP ORDER BY 2;
SQL> SELECT * FROM EMP ORDER BY 2 DESC;
SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP ORDER BY 2;
SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP ORDER BY 4,1;
SQL> SELECT EMPNO, ENAME, SAL SALARY FROM EMP ORDER BY SALARY;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 8 of 89
What is DUAL Table?
The DUAL table is owned by the user SYS and can be accessed by all users. It contains one
column, DUMMY, and one row with the value X. The DUAL table is useful when you want to
return a value once only, for instance, the value of a constant, pseudo column, or expression
that is not derived from a table with user data. The DUAL table is generally used for SELECT
clause syntax completeness, because both SELECT and FROM clauses are mandatory, and
several calculations do not need to select from actual tables.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 9 of 89
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
SQL> SELECT EMPNO, ENAME, SAL, SAL+100, SAL-100, SAL*12, SAL/30 FROM EMP;
14 rows selected
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 10 of 89
Performing calculations with columns, Notice heading of each column
WITH DATE COLUMNS
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 11 of 89
NVL
NULL value can be controlled with NVL () function
SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, SAL+COMM, SAL+NVL(COMM,0) FROM EMP;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 12 of 89
Column Alias / Column Heading
When displaying the result of a query, SQL*Plus normally uses the name of the selected column as the
column heading. This heading may not be descriptive and hence may be difficult to understand. You
can change a column heading by using a column alias.
Specify the alias after the column in the SELECT list using a space as a separator. By default, alias
headings appear in uppercase. If the alias contains spaces or special characters (such as # or $), or is
case sensitive, enclose the alias in double quotation marks (" ").
AS is optional
SQL> SELECT EMPNO, ENAME, JOB AS DESIGNATION, SAL AS SALARY, COMM COMMISSION
FROM EMP;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 13 of 89
SQL> SELECT EMPNO, ENAME, JOB, SAL MONTHLY_SALARY, SAL+NVL(COMM,0) GROSS_SALARY,
2 SAL*12 ANNUAL_SALARY FROM EMP;
By default, alias headings appear in uppercase. If the alias contains spaces or special characters (such
as # or $), or is case sensitive, enclose the alias in double quotation marks (" ").
SQL> SELECT EMPNO, ENAME, JOB "JOB TITLE", SAL "salary", COMM COMMISSION
2 FROM EMP;
Table Alias
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 14 of 89
Concatenation Operator
You can link columns to other columns, arithmetic expressions, or constant values to create a
character expression by using the concatenation operator (||). Columns on either side of the operator
are combined to make a single output column.
sadfdaf
EMPNO||ENAME
--------------------------------------------------
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER
EMPLOYEE_INFO
-----------------------------------------------------------
7369SMITHCLERK
7499ALLENSALESMAN
7521WARDSALESMAN
7566JONESMANAGER
7654MARTINSALESMAN
7698BLAKEMANAGER
7782CLARKMANAGER
7788SCOTTANALYST
7839KINGPRESIDENT
7844TURNERSALESMAN
7876ADAMSCLERK
7900JAMESCLERK
7902FORDANALYST
7934MILLERCLERK
14 rows selected.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 15 of 89
Literal
SQL> SELECT EMPNO, ENAME, JOB, 5000, 'KARACHI', '14-AUG-1947' FROM EMP;
EMPLOYEE
--------------
Mr. SMITH
Mr. ALLEN
Mr. WARD
Mr. JONES
Mr. MARTIN
Mr. BLAKE
Mr. CLARK
Mr. SCOTT
Mr. KING
Mr. TURNER
Mr. ADAMS
Mr. JAMES
Mr. FORD
Mr. MILLER
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 16 of 89
SQL> SELECT ENAME||' works as '||JOB||' in Dept No. '||DEPTNO
"Employee Information" FROM EMP;
Employee Information
--------------------------------------------------------------------------------
SMITH works as CLERK in Dept No. 20
ALLEN works as SALESMAN in Dept No. 30
WARD works as SALESMAN in Dept No. 30
JONES works as MANAGER in Dept No. 20
MARTIN works as SALESMAN in Dept No. 30
BLAKE works as MANAGER in Dept No. 30
CLARK works as MANAGER in Dept No. 10
SCOTT works as ANALYST in Dept No. 20
KING works as PRESIDENT in Dept No. 10
TURNER works as SALESMAN in Dept No. 30
ADAMS works as CLERK in Dept No. 20
JAMES works as CLERK in Dept No. 30
FORD works as ANALYST in Dept No. 20
MILLER works as CLERK in Dept No. 10
SQL> SELECT ENAME||' Earn Monthly '||SAL||' And His Annual Salary Is '||SAL*12
"Employee Salary Info..." FROM EMP;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 17 of 89
DISTINCT
Duplicate Rows
SQL> SELECT DEPTNO FROM EMP;
DEPTNO
---------
20
30
20
30
30
10
20
10
30
20
30
20
10
Eliminating Duplicate Rows
To eliminate duplicate rows in the result, include the DISTINCT keyword in the SELECT clause
immediately after the SELECT keyword. In the example on the slide, the EMPLOYEES table actually
contains 20 rows but there are only seven unique department numbers in the table. You can specify
multiple columns after the DISTINCT qualifier. The DISTINCT qualifier affects all the selected columns,
and the result is every distinct combination of the columns.
DEPTNO
---------
30
20
10
JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
DEPTNO JOB
--------- ---------
20 CLERK
30 SALESMAN
20 MANAGER
30 CLERK
10 PRESIDENT
30 MANAGER
10 CLERK
10 MANAGER
20 ANALYST
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 18 of 89
WHERE Clause
Limiting the Rows Selected (WHERE Clause)
You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause
contains a condition that must be met, and it directly follows the FROM clause. If the condition is true,
the row meeting the condition is returned.
In the following example, the SELECT statement retrieves records of all employees
who belong to department number 10.
The following query retrieves records of all employees who are working as CLERK.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 19 of 89
Comparison Operator
Comparison conditions are used in conditions that compare one expression to another value or
expression.
1. Equal
2.Not Equal
3. Greater Then
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 21 of 89
Other Comparison
1. In 2. Not In
3. Between 4. Not Between
5. Is Null 6. Is Not Null
7. Like 8. Not Like
SQL> Select* from emp Where sal between 800 and 1000;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 22 of 89
4.NotBetween:Not Between two values (inclusive)
SQL> Select* from emp Where sal Not between 800 and 1000;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 23 of 89
7.Like: Match a character pattern
SQL> Select* from emp Where ename like '____S'; (S After 4 digit)
SQL> Select* from emp Where ename like '____'; (Only 4 digit name)
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 24 of 89
8.Not Like: Not Match a character pattern
SQL> Select* from emp Where ename not like 'S%';
SQL> Select* from emp Where ename not like '____S'; (S After 4 digit)
SQL> Select* from emp Where ename not like '____'; (Only 4 digit name)
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 25 of 89
Logical Operator
A logical condition combines the result of two component conditions to produce a single result based on
them or inverts the result of a single condition. A row is returned only if the overall result of the
condition is true. Three logical operators are available in SQL:
AND (Returns TRUE if both component conditions are true)
OR (Returns TRUE if either component condition is true)
All the examples so far have specified only one condition in the WHERE clause. You can use several
conditions in one WHERE clause using the AND and OR operators.
Using the AND Operator
AND requires both conditions to be true
If either condition is FALSE result will be FALSE in case of AND
CONDITION 1 CONDITION 2 RESULT
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
UPPER(ENAME)
------------
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 27 of 89
2.LOWER(LOWER: Converts mixed case or uppercase character strings to lowercase)
SQL> Select lower (ename) from emp;
LOWER(ENAME)
------------
smith
allen
ward
jones
martin
blake
clark
scott
3.INITCAP(INITCAP: Converts the first letter of each word to uppercase and remaining letters to
lowercase)
INITCAP(ENAME)
--------------
Smith
Allen
Ward
Jones
Martin
Blake
Clark
Scott
King
Turner
LPAD(RPAD(SAL,8,'*'),9,'$')
---------------------------
$800*****
$1600****
$1250****
$2975****
$1250****
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 29 of 89
6. LTRIM(Remove one digit from left side in word)
SQL> Select ltrim(ename,'S'),ename from emp;
LTRIM(ENAME,'S') ENAME
---------------- --------------------------
MITH SMITH
ALLEN ALLEN
WARD WARD
JONES JONES
MARTIN MARTIN
BLAKE BLAKE
CLARK CLARK
COTT SCOTT
KING KING
TURNER TURNER
ADAMS ADAMS
RTRIM(ENAME,'S') ENAME
---------------- ----------
SMITH SMITH
ALLEN ALLEN
WARD WARD
JONE JONES
MARTIN MARTIN
BLAKE BLAKE
CLARK CLARK
SCOTT SCOTT
KING KING
TURNER TURNER
ADAM ADAMS
8. REPLACE(Replace word)
SQL> Select replace(ename,'S','A'),ename from emp;
REPLACE(ENAME,'S','A') ENAME
---------------------- --------------------------------
AMITH SMITH
ALLEN ALLEN
WARD WARD
JONEA JONES
MARTIN MARTIN
BLAKE BLAKE
CLARK CLARK
ACOTT SCOTT
KING KING
TURNER TURNER
ADAMA ADAMS
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 30 of 89
9. LENGTH(Shows the length of a string as a numeric value)
SQL> Select length (ename),ename from emp;
LENGTH(ENAME) ENAME
------------- -----------------------
5 SMITH
5 ALLEN
4 WARD
5 JONES
6 MARTIN
5 BLAKE
5 CLARK
5 SCOTT
4 KING
6 TURNER
5 ADAMS
5 JAMES
4 FORD
SUBSTR('PETROMAN',1,3)
----------------------
PET
SUBSTR('PETROMAN',-3,3)
-----------------------
MAN
ENAME
-----
SMI
ALL
WAR
JON
MAR
BLA
CLA
SCO
KIN
TUR
ADA
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 31 of 89
11. INSTR(Finds numeric position of a named character)
SQL> Select instr(ename,'A'),ename from emp;
INSTR(ENAME,'A') ENAME
---------------- -----------------------
0 SMITH
1 ALLEN
2 WARD
0 JONES
2 MARTIN
3 BLAKE
3 CLARK
0 SCOTT
0 KING
0 TURNER
1 ADAMS
2 JAMES
0 FORD
0 MILLER
INSTR(ENAME,'A',1,2) ENAME
-------------------- ----------
0 SMITH
0 ALLEN
0 WARD
0 JONES
0 MARTIN
0 BLAKE
0 CLARK
0 SCOTT
0 KING
0 TURNER
3 ADAMS
0 JAMES
0 FORD
0 MILLER
14 rows selected
SIGN(-1000)
-----------
-1
SIGN(1000)
----------
1
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 32 of 89
13. CEIL(The CEIL() will rounded up any positive or negative decimal value within the function upwards.)
SQL> Select ceil(9.1) from dual;
CEIL(9.1)
---------
10
CEIL(9.99)
----------
10
14. FLOOR(The SQL FLOOR() rounded up any positive or negative decimal value down to the next
least integer value. SQL DISTINCT along with the SQL FLOOR() function is used to retrieve only unique
value after rounded down to the next least integer value depending on the column specified.)
FLOOR(17.36)
------------
17
SQL> SELECT FLOOR(17.99) from dual;
FLOOR(17.99)
------------
17
FLOOR(-17.36)
-------------
-18
15. TRUNC(The TRUNC function truncates the column, expression, or value to n decimal places.
The TRUNC function works with arguments similar to those of the ROUND function. If the second
argument is 0 or is missing, the value is truncated to zero decimal places. If the second argument is 2,
the value is truncated to two decimal places. Conversely, if the second argument is -2, the value is
truncated to two decimal places to the left. Like the ROUND function, the TRUNC function can be used
with date functions.)
TRUNC(9.1)
----------
9
TRUNC(9.99)
-----------
9
TRUNC(-9.99)
------------
-9
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 33 of 89
16. ROUND(The ROUND function rounds the column, expression, or value to n decimal places. If
the secondargument is 0 or is missing, the value is rounded to zero decimal places. If the
secondargument is 2, the value is rounded to two decimal places. Conversely, if the second argumentis
-2, the value is rounded to two decimal places to the left.
The ROUND function can also be used with date functions. You will see examples later in thislesson.)
ROUND(9.45)
-----------
9
ROUND(9.51)
-----------
10
MOD(11,4)
---------
3
MOD(25,5)
---------
0
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 34 of 89
Multi Row Function
Group Function
Aggregate Function
Aggregating Data Using Group Functions
Group Functions
Unlike single-row functions, group functions operate on sets of rows to give one result per group.
These sets may be the whole table or the table split into groups.
1.Sum
Select sum(sal) from emp;
2.Min
Select min(sal) from emp;
3.Max
Select max(sal) from emp;
4.Count
Select count(sal), from emp;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 35 of 89
You can use the group function in the ORDER BY clause.
SQL> SELECT DEPTNO, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL)
2 FROM EMP
3 GROUP BY DEPTNO
4 ORDER BY SUM(SAL);
MAX(AVG(SAL))
-------------
2916.6667
MAX(SUM(SAL))
-------------
10875
SUM(MAX(SAL))
-------------
10850
HAVING Clause
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 37 of 89
The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the
GROUP BY clause first because that is more logical. Groups are formed and group functions are
calculated before the HAVING clause is applied to the groups in the SELECT list.
SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)
2 FROM EMP
3 GROUP BY DEPTNO
4 HAVING SUM(SAL)>9000;
DEPTNO COUNT(*) SUM(SAL)
--------- --------- ---------
30 6 9400
20 5 10875
The following example displays department numbers and maximum salaries for those departments
whose maximum salary is greater or equal to 3,000. You can use the GROUP BY clause without using a
group function in the SELECT list. If you restrict rows based on the result of a group function, you must
have a GROUP BY clause as well as the HAVING clause. The following example displays the department
numbers and maximum salaries for those departments whose maximum salary is greater than 3,000:
DEPTNO MAX(SAL)
--------- ---------
20 3000
10 5000
DEPTNO
---------
20
10
SQL> SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*)
2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'RRRR')
4 HAVING COUNT(*)>1
5 ORDER BY TO_CHAR(HIREDATE,'RRRR');
TO_C COUNT(*)
---- ---------
1981 10
1987 2
SQL> SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*)
2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'RRRR')
4 ORDER BY TO_CHAR(HIREDATE,'RRRR');
TO_C COUNT(*)
---- ---------
1980 1
1981 10
1987 2
2082 1
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 38 of 89
Date Functions
1. Months_between 2. Add_months
5. Round 6. Trunc
1. Months_between
2. Add_months
3. Next day
4.Last day
5. Round
6. Trunc
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 39 of 89
The SYSDATE Function
SYSDATE is a date function that returns the current database server date and time. You can use
SYSDATE just as you would use any other column name. For example, you can display the current date
by selecting SYSDATE from a table. It is customary to select SYSDATE from a dummy table called
DUAL.
Date Functions
Date functions operate on Oracle dates. All date functions return a value of DATE data type except
MONTHS_BETWEEN, which returns a numeric value.
• ADD_MONTHS(date, n): Adds n number of calendar months to date. The value of n must be an
integer and can be negative.
• NEXT_DAY(date, 'char'): Finds the date of the next specified day of the week ('char') following
date. The value of char may be a number representing a day or a character string.
• LAST_DAY(date): Finds the date of the last day of the month that contains date.
• ROUND(date[,'fmt']): Returns date rounded to the unit specified by the format model fmt. If the
format model fmtis omitted, date is rounded to the nearest day.
• TRUNC(date[, 'fmt']): Returns date with the time portion of the day truncated to the unit specified
by the format model fmt. If the format model fmtis omitted, date is truncated to the nearest day.
SQL> SELECT
2 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947') TOT_MONTHS,
3 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')/12 TOT_YEARS,
4 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*4 TOT_WEEKS,
5 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30 TOT_DAYS,
6 MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30*24 TOT_HOURS
7 FROM DUAL;
SQL> SELECT
2 ADD_MONTHS('14-AUG-2008',1) AFTER_1_MONTH,
3 ADD_MONTHS('14-AUG-2008',6) AFTER_6_MONTHS,
4 ADD_MONTHS('14-AUG-2008',12) AFTER_1_YEAR,
5 ADD_MONTHS('14-AUG-2008',12*3) AFTER_3_YEARS,
6 ADD_MONTHS('14-AUG-2008',-3) BEFORE_3_MONTHS,
7 ADD_MONTHS('14-AUG-2008',-12*3) BEFORE_3_YEARS
8 FROM DUAL;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 40 of 89
What was the first Thursday, Friday, Saturday & Sunday after August
14, 1947
SQL> SELECT
2 NEXT_DAY('14-AUG-1947','THURSDAY') FIRST_THU,
3 NEXT_DAY('14-AUG-1947','FRIDAY') FIRST_FRI,
4 NEXT_DAY('14-AUG-1947','SATURDAY') FIRST_SAT,
5 NEXT_DAY('14-AUG-1947','SUNDAY') FIRST_SUN
6 FROM DUAL;
SQL> SELECT
2 LAST_DAY('14-AUG-1947'),
3 LAST_DAY('14-FEB-1947'),
4 LAST_DAY('14-FEB-2008')
5 FROM DUAL;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 41 of 89
What was the first Sunday after hiring
What was the last day in which each employee was hired
What was the date after two months of hiring
SQL> SELECT
2 EMPNO, ENAME, HIREDATE,
3 NEXT_DAY(HIREDATE,'SUNDAY') FIRST_SUN,
4 LAST_DAY(HIREDATE) LAST_DAY,
5 ADD_MONTHS(HIREDATE,2) AFTER_2_MONTHS
6 FROM EMP;
ROUND (MONTH)
01-15 FIRST DAY OF SAME MONTH
16-31 FIRST DAY OF NEXT MONTH
ROUND (YEAR)
01-JAN ... 30-JUN FIRST DAY OF SAME YEAR
01-JUL ... 31-DEC FIRST DAY OF NEXT YEAR
TRUNC (MONTH)
01-31 FIRST DAY OF SAME MONTH
TRUNC (YEAR)
01-JAN ... 31-DEC FIRST DAY OF SAME YEAR.
ROUND (DD) DEFAULT IF NOT SPECIFIED
LESS THAN 12:00PM SAM DAY
MORE THAN 12:00PM NEXT DAY
ROUND (DAY)
BEFORE 12:00PM WEDNESDAY, PREVIOUS SUNDAY OF THE WEEK
AFTER 12:00PM WEDNESDAY, NEXT SUNDAY OF THE WEEK
TRUNC (DD) Same Day, eliminating time portion from date
TRUNC (DAY) Previous Sunday
Assume SYSDATE is 24-JUL-2008
SQL> SELECT SYSDATE, ROUND(SYSDATE,'MONTH'), TRUNC(SYSDATE,'MONTH') FROM DUAL;
SYSDATE ROUND(SYS TRUNC(SYS
--------- --------- --------------------------------------------
24-JUL-08 01-AUG-08 01-JUL-08
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 42 of 89
SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'MONTH'),
4 TRUNC(SYSDATE-10,'MONTH')
5 FROM DUAL;
SYSDATE-1 ROUND(SYS TRUNC(SYS
--------- --------- ---------------------------
14-JUL-08 01-JUL-08 01-JUL-08
SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;
24-JUN-08 01-JUL-08 01-JUN-08
SQL> SELECT SYSDATE, ROUND(SYSDATE,'YEAR'), TRUNC(SYSDATE,'YEAR') FROM DUAL;
SYSDATE ROUND(SYS TRUNC(SYS
--------- --------- ---------------
24-JUL-08 01-JAN-09 01-JAN-08
SQL> SELECT
2 SYSDATE-10,
3 ROUND(SYSDATE-10,'YEAR'),
4 TRUNC(SYSDATE-10,'YEAR')
5 FROM DUAL;
SYSDATE-1 ROUND(SYS TRUNC(SYS
--------- --------- -------------------------------
14-JUL-08 01-JAN-09 01-JAN-08
SQL> SELECT
2 SYSDATE-30,
3 ROUND(SYSDATE-30,'MONTH'),
4 TRUNC(SYSDATE-30,'MONTH')
5 FROM DUAL;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 43 of 89
DECODE The DECODE function is analogous to the "IF THEN ELSE" conditional statement.
DECODE works with values, columns, and expressions of all data types.
JOB DECODE(JOB,'SALESMAN','BOOKER'
--------- ------------------------------
CLERK
SALESMAN Booker
SALESMAN Booker
MANAGER
SALESMAN Booker
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN Booker
CLERK
CLERK
ENAME DECODE(JOB,'SALESMAN','BOOKER'
---------- ------------------------------
SMITH CLERK
ALLEN Booker
WARD Booker
JONES MANAGER
MARTIN Booker
BLAKE MANAGER
CLARK MANAGER
SCOTT ANALYST
KING PRESIDENT
TURNER Booker
ADAMS CLERK
JAMES CLERK
FORD ANALYST
MILLER CLERK
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 44 of 89
CASE
The SQL CASE statement
The CASE statement is SQL’s way of handling if/then logic. The CASE statement is followed by at least
one pair of WHEN and THEN statements—SQL’s equivalent of IF/THEN in Excel. Because of this pairing,
you might be tempted to call this SQL CASE WHEN, but CASE is the accepted term. Every CASE
statement must end with the END statement. The ELSE statement is optional, and provides a way to
capture values not specified in the WHEN / THEN statements. CASE is easiest to understand in the
context of an example:
Select empno,ename,sal,
Case
When sal between 1 and 1000 then‘lowsal’
End
From emp;
Select empno,ename,sal,job,
Case
When sal> 2500 then‘hisal’
When sal< = 2500 then ‘losal’
End
From emp;
Select empno,ename,sal,job,
Case
When sal> 2500 then‘hisal’
When sal< = 2500 then ‘losal’
Else Null
End
From emp;
Select empno,ename,sal,job,
Case
When job = ‘SALESMAN’ then ‘BOOKER’
Else job
End
From emp;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 45 of 89
Conversion Functions
1. TO_CHAR
2. TO_DATE
3. TO_NUMBER
TO_CHAR
Select to_char (hiredate,’DD-MON-YYYY’)fromemp;
TO_DATE
Select to_char(to_date(‘01052015’,’dd-mm-yyyy’))from emp;
TO_NUMBER
selectto_number(to_char(hiredate,'dd'))*500 from emp;
Conversion Functions
In addition to Oracle data types, columns of tables in an Oracle9i database can be defined using ANSI,
DB2, and SQL/DS data types. However, the Oracle server internally converts such data types to Oracle
data types.
In some cases, Oracle server uses data of one data type where it expects data of a different data type.
When this happens, Oracle server can automatically convert the data to the expected data type. This
data type conversion can be done implicitly by Oracle server, or explicitly by the user.
Implicit data type conversions work according to the rules explained in the next two slides.
Explicit data type conversions are done by using the conversion functions. Conversion functions
convert a value from one data type to another. Generally, the form of the function names follows the
convention data type TO data type. The first data type is the input data type; the last data type is the
output.
Note: Although implicit data type conversion is available, it is recommended that you do explicit data
type conversion to ensure the reliability of your SQL statements.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 46 of 89
Using the TO_CHAR Function with Dates
Displaying a Date in a Specific Format
Previously, all Oracle date values were displayed in the DD-MON-YY format. You can use the TO_CHAR
function to convert a date from this default format to one specified by you.
The format model:
• Must be enclosed in single quotation marks and is case sensitive
• Can include any valid date format element
• Has an fmelement to remove padded blanks or suppress leading zeros
• Is separated from the date value by a comma
DD 01-31
MON JAN, FEB, ... DEC
Mon Jan, Feb, ... Dec
MONTH JANUARY, FEBRUARY, ... DECEMBER
Month January, February, ... December
YY 01, 02, 03 ... (Century)
RR 01, 02, 03 ... (Century)
YEAR SPELL OUT YEAR
Year Spell Out Year
HH12 1 - 12
HH24 0 - 23
AM
PM
MI 01 - 59 MINUTES
SS 01 - 59 SECONDS
DY MON, TUE, .... SUN
Dy Mon, Tue, .... Sun
DAY MONDAY, TUESDAY, ... SUNDAY
Day Monday, Tuesday, ... Sunday
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 47 of 89
How to display time portion
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 49 of 89
Using the TO_CHAR Function with Numbers
SQL> SELECT
2 TO_CHAR(58,'99.9') A,
3 TO_CHAR(58,'00.0') B,
4 TO_CHAR(58,'$99.9') C,
5 TO_CHAR(58,'$00.0') D
6 FROM DUAL;
A B C D
--------------------------
58.0 58.0 $58.0 $58.0
SQL> SELECT
2 TO_CHAR(58,'999.99') A,
3 TO_CHAR(58,'000.00') B,
4 TO_CHAR(58,'$999.99') C,
5 TO_CHAR(58,'$000.00') D
6 FROM DUAL;
A B C D
------- ------- -------- --------
58.00 058.00 $58.00 $058.00
SQL> SELECT
TO_CHAR(58,'99,999.99') A,
TO_CHAR(58,'00,000.00') B,
TO_CHAR(58,'$99,999.99') C,
TO_CHAR(58,'$00,000.00') D
FROM DUAL;
A B C D
---------- ---------- ----------- -------------------------------
58.00 00,058.00 $58.00 $00,058.00
SQL> SELECT
2 TO_CHAR(58755,'99,999.99') A,
3 TO_CHAR(58755,'00,000.00') B,
4 TO_CHAR(58755,'$99,999.99') C,
5 TO_CHAR(58755,'$00,000.00') D
6 FROM DUAL;
A B C D
---------- ---------- ----------- -----------
58,755.00 58,755.00 $58,755.00 $58,755.00
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 51 of 89
TO_NUMBER ( )
SQL> SELECT 4+3 FROM DUAL;
4+3
---------
7
SQL> SELECT '4'+'3' FROM DUAL;
'4'+'3'
---------
7
SQL> SELECT TO_NUMBER('4')+TO_NUMBER('3') FROM DUAL;
TO_NUMBER('4')+TO_NUMBER('3')
-----------------------------
7
SQL> SELECT
2 SUBSTR('SECTOR 5',-1,1),
3 SUBSTR('SECTOR 6',-1,1),
4 TO_NUMBER(SUBSTR('SECTOR 5',-1,1)),
5 TO_NUMBER(SUBSTR('SECTOR 6',-1,1))
6 FROM DUAL;
S S TO_NUMBER(SUBSTR('SECTOR5',-1,1)) TO_NUMBER(SUBSTR('SECTOR6',-1,1))
- - --------------------------------- ---------------------------------
565 6
SQL> SELECT SUBSTR('HOUSE # 5, SEC 11, KARACHI',9,1)*10 FROM DUAL;
SUBSTR('HOUSE#5,SEC11,KARACHI',9,1)*10
--------------------------------------
50
TO_DATE ( )
SQL> SELECT '14-AUG-1947' A FROM DUAL;
14-AUG-1947
SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL;
14-AUG-47
SQL> SELECT NEXT_DAY('14-AUG-1947','SUNDAY') A FROM DUAL;
17-AUG-47
SQL> SELECT NEXT_DAY(TO_DATE('14-AUG-1947'),'SUNDAY') A FROM DUAL;
17-AUG-47
SQL> SELECT TO_CHAR('14-AUG-1947','RRRR') A FROM DUAL;
SELECT TO_CHAR('14-AUG-1947','RRRR') FROM DUAL
*
ERROR at line 1:
ORA-01722: invalid number
SQL> SELECT
2 TO_CHAR(SYSDATE,'RRRR')
3-
4 TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR') TOT_YEARS
5 FROM DUAL;
TOT_YEARS
---------
61
SQL> SELECT
2 TO_NUMBER(TO_CHAR(SYSDATE,'RRRR'))
3-
4 TO_NUMBER(TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR')) TOT_YEARS
5 FROM DUAL;
TOT_YEARS
---------
61
SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL;
14-AUG-47
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 52 of 89
SQL> SELECT TO_DATE('14-AUG-1947','DD-MON-RRRR') A FROM DUAL;
14-AUG-47
SQL> SELECT TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A FROM DUAL;
14-AUG-47
SQL> SELECT
2 TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A,
3 TO_DATE('AUGUST 14, 1947','MON DD, RRRR') B,
4 TO_DATE('AUG 14, 1947','Mon DD, RRRR') C,
5 TO_DATE('14 AUG 1947','DD MONTH RRRR') D,
6 TO_DATE('AUG 1947','MONTH RRRR') E,
7 TO_DATE('1947','RRRR') F,
8 TO_DATE('AUG','MON') G,
9 TO_DATE('14','DD') H
10 FROM DUAL;
A B C D E F G H
--------- ------- --------- --------- --------- --------- --------- ---------
14-AUG-47 14-AUG-4714-AUG-4714-AUG-47 01-AUG-47 01-JUL-47 01-AUG-08 14-JUL-08
SQL> SELECT * FROM EMP WHERE HIREDATE=TO_DATE('17/12/1980','DD/MM/RRRR');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- ------ --------- ------------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 53 of 89
Set operator
1. Joining
2. Subqurery
3. Union
4. Union all
5. Minus
6. intersect
Joinin
1. Equal join
3. Outer join
4. Self Join
Equal join
14 rows selected.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 54 of 89
Non equal join
Outer join
15 rows selected.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 55 of 89
Self Join
13 rows selected.
Defining Joins
When data from more than one table in the database is required, a join condition is used. Rows
in one table can be joined to rows in another table according to common values existing in
corresponding columns, that is, usually primary and foreign key columns.
To display data from two or more related tables, write a simple join condition in the WHERE
clause.
In the syntax:
table1.columndenotes the table and column from which data is retrieved
table1.column1 = is the condition that joins (or relates) the tables together
table2.column2
Guidelines
• When writing a SELECT statement that joins tables, precede the column name with the table
name for clarity and to enhance database access.
• If the same column name appears in more than one table, the column name must be
prefixed with the table name.
• To join n tables together, you need a minimum of n-1 join conditions. For example, to join
four tables, a minimum of three joins is required. This rule may not apply if your table has a
concatenated primary key, in which case more than one column is required to uniquely
identify each row.
Equijoin
To determine an employee’s department name, you compare the value in the DEPTNO column
in the EMP table with the DEPTNO values in the DEPT table. The relationship between the EMP
and DEPT tables is an equijoin—that is, values in the DEPTNO column on both tables must be
equal. Frequently, this type of join involves primary and foreign key complements.
Note: Equijoins are also called simple joins or inner joins.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 56 of 89
EMP TABLE
EMPNO ENAME DEPTNO
--------- ---------- ------------------------
7369 SMITH 20
7499 ALLEN 30
7521 WARD 30
7566 JONES 20
7654 MARTIN 30
7698 BLAKE 30
7782 CLARK 10
7788 SCOTT 20
DEPT TABLE
DEPTNO DNAME LOC
--------- ------------ ----------------------------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 57 of 89
The above select statement retrieves 4 rows. There is a DEPTNO 40, while there is not any
employee in EMP table who belong to department 40.
Retrieving Records with Equijoins
Display all employees with their department names and location.
Employee information is stored in EMP table
Department information is stored in DEPT table
There is a column DEPTNO which exists in both tables
Match the value in DEPTNO of EMP table with DEPTNO of DEPT table.
SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC
2 FROM EMP, DEPT
3 WHERE EMP.DEPTNO=DEPT.DEPTNO;
EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- -------------------------------------------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
14 rows selected.
The query retrieve 14 rows, ASLAM’s record did not retrieved. Why?
In the example:
• The SELECT clause specifies the column names to retrieve:
• employee number, name, job, salary, and department number, which are columns in
the EMP table
• department name, and location, which are columns in the DEPT table
• The FROM clause specifies the two tables that the database must access:
• EMP table
• DEPT table
• The WHERE clause specifies how the tables are to be joined:
EMP.DEPTNO = DEPT.DEPTNO
Because the DEPTNO column is common to both tables, it must be prefixed by the table name
to avoid ambiguity or Use table prefixes to qualify column names that are in multiple tables.
Improve performance by using table prefixes
SELECT EMP.EMPNO, EMP.ENAME, EMP.JOB, EMP.SAL, EMP.DEPTNO, DEPT.DNAME, DEPT.LOC
FROM EMP, DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
Using Table Alias
SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC
FROM EMP E, DEPT D
WHERE E.DEPTNO=D.DEPTNO;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 58 of 89
Additional Search Conditions
SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND SAL>2000;
Cartesian / Cross Products (rows of one table multiply with rows of another table)
DEPTNO is missing
When joining EMP and DEPT tables:
ASLAM’s record is not displaying from EMP table
Operations’s record is not displaying from DEPT table
Aslam does not belong to any department because there is a null value in DEPTNO column.
So when you join EMP and DEPT tables using equijoin, the values of DEPTNO column of EMP
table matches with the values of DEPTNO column of DEPT table, and only those records will be
displayed which values matches.
There is an Opeations’s department, DEPTNO 40 in DEPT table, but No Employee is working in
DEPTNO 40 in EMP table, so value is not matching. Only those records will by displayed using
equijoin which values matches in both tables.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 62 of 89
SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC FROM EMP, DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO(+);
EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- -------------------------------------------
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7900 JAMES CLERK 950 30 SALES CHICAGO
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
1 ASLAM CLERK 1200
Placed (+) on the “side” of the join that is deficient (missing) in information. Aslam’s record
exists in EMP table, but NULL DEPTNO does not exists in DEPT table, so put (+) on DEPT side
because DEPT side is missing information.
SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC FROM EMP, DEPT
WHERE EMP.DEPTNO(+)=DEPT.DEPTNO;
EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- -----------------------------------------------
7782 CLARK MANAGER 2450 10 ACCOUNTING NEW YORK
7934 MILLER CLERK 1300 10 ACCOUNTING NEW YORK
7839 KING PRESIDENT 5000 10 ACCOUNTING NEW YORK
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
7369 SMITH CLERK 800 20 RESEARCH DALLAS
7788 SCOTT ANALYST 3000 20 RESEARCH DALLAS
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
7876 ADAMS CLERK 1100 20 RESEARCH DALLAS
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7900 JAMES CLERK 950 30 SALES CHICAGO
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
OPERATIONS BOSTON
Placed (+) on the “side” of the join that is deficient (missing) in information. Operations
department DEPTNO 40 exists in DEPT table, but DEPTNO 40 is not assigned to any employee,
so put (+) on EMP side because EMPT side is missing information.
Display all departments in which no employee was hired.
SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC FROM EMP, DEPT
WHERE EMP.DEPTNO(+)=DEPT.DEPTNO
AND EMP.DEPTNO IS NULL;
EMPNO ENAME JOB SAL DEPTNO DNAME LOC
--------- ---------- --------- --------- --------- -------------- ------------------------------
OPERATIONS BOSTON
Outer Join Restrictions
• The outer join operator can appear on only one side of the expression—the side that has
information missing. It returns those rows from one table that have no direct match in the
other table.
• A condition involving an outer join cannot use the IN operator or be linked to another
condition by the OR operator.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 63 of 89
Self Joins
Sometimes you need to join a table to itself. To find the name of each employee’s manager,
you need to join the EMP table to itself, or perform a self join. For example, to find the name of
ALLEN’s manager, you need to:
• Find ALLEN in the EMP table by looking at ENAME column.
• Find the manager number for ALLEN by looking at the MGR column. ALLEN’s manager
number is 7698.
• Find the name of the manager with MGR 7698 by looking at the ENAME column. BLAKE’s
employee number is 7698, so BLAKE is ALLEN’s manager.
In this process, you look in the table twice. The first time you look in the table to find ALLEN in
the ENAME column and MGR value of 7698. The second time you look in EMPNO column to find
7698 and the ENAME column to find BLAKE.
SQL> SELECT * FROM EMP;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- --------------------------------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 ASLAM CLERK 7566 26-JUL-08 1200
15 rows selected.
SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME
FROM EMP W, EMP M
WHERE W.MGR=M.EMPNO;
EMPNO ENAME MGR ENAME
--------- ---------- --------- --------------------------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
7934 MILLER 7782 CLARK
1 ASLAM 7566 JONES
14 rows selected.
KING’s record did not display because KING’s MGR is null, which did not match with any EMPNO.
To display KING’s record, you have to use outer join condition, because KING’s MGR is null
which, which did not match with any EMPNO. You have to put (+) on manager side because
manager is missing but worker (KING) exists.
In another words KING’s manager is missing and you have to put (+) on missing side.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 64 of 89
SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME
2 FROM EMP W, EMP M
3 WHERE W.MGR=M.EMPNO(+);
EMPNO ENAME MGR ENAME
--------- ---------- --------- ----------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7839 KING
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
7934 MILLER 7782 CLARK
1 ASLAM 7566 JONES
15 rows selected.
The example joins the EMP table to itself. To simulate two tables in the FROM clause, there are
two aliases, namely w and m, for the same table, EMP.
In this example, the WHERE clause contains the join that means “where a worker’s manager
number matches the employee number for the manager.”
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 65 of 89
Subqurery
1. Single-row subqueries
2. Multiple-row subqueries
Single-row subqueries
SQL> Select empno,ename,sal from emp
2 Wheresal = (select min(sal) from emp);
Multiple-row subqueries
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 66 of 89
Subqueries
A subquery is a query within a query. In Oracle, you can create subqueries within your SQL
statements. These subqueries can reside in the WHERE clause, HAVING clause, the FROM
clause, or the SELECT clause.
Use a subquery when there is an unknown criteria.
For example,
I want to retrieve all employees who are working in SMITH’S department.
Smith’s Department is unknown, first find Smith’s department by using the following query:
SQL> SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE ENAME='SMITH');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- --------------------------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
In the above example, the inner query determines the department of employee SMITHl. The
outer query takes the result of the inner query and uses this result to display all the employees
who belong to this department.
Without subquery:
SQL> SELECT SAL FROM EMP WHERE ENAME='JONES'; �2975
SQL> SELECT * FROM EMP WHERE SAL>2975;
Using subquery:
SQL> SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='JONES');
Display all employees who are working on the same post as BLAKE
BLAKE’s job is unknown, first find BLAKE’s job by using the following query:
SQL> SELECT JOB FROM EMP WHERE ENAME='BLAKE';
JOB
---------
MANAGER
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 67 of 89
And now use MANAGER in criteria for retrieving all employees of that job.
SQL> SELECT * FROM EMP WHERE JOB='MANAGER';
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- -----------------------------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
But you can achieve the above task by using the following subquery in where clause.
SQL> SELECT * FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME='BLAKE');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- -----------------------------------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
Types of Subqueries
• Single-row subqueries: Queries that return only one row from the inner SELECT
statement
• Multiple-row subqueries: Queries that return more than one row from the inner SELECT
statement
Note: There are also multiple-column subqueries: Queries that return more than one column
from the inner SELECT statement.
Single-Row Subqueries
A single-row subquery is one that returns one row from the inner SELECT statement. This type
ofsubquery uses a single-row operator.
SELECT * FROM EMP WHERE HIREDATE=(SELECT HIREDATE FROM EMP WHERE EMPNO=7902);
SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE LOC='NEW YORK');
SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE EMPNO=7900);
The HAVING Clause with Subqueries
You can use subqueries not only in the WHERE clause, but also in the HAVING clause. The
Oracle server executes the subquery, and the results are returned into the HAVING clause of
the main query.
The SQL statement on in the following example displays all the departments that have a
minimum salary greater than that of department 30.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 69 of 89
SQL> SELECT DEPTNO, MIN(SAL) FROM EMP
2 GROUP BY DEPTNO;
DEPTNO MIN(SAL)
--------- ---------
30 950
20 800
10 1300
SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30;
MIN(SAL)
---------
950
Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You use a
multiple-row operator, instead of a single-row operator, with a multiple-row subquery. The
multiple-row operator expects one or more values.
What is wrong with this Statement?
SQL> SELECT * FROM EMP
2 WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);
WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO)
*
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row
One common error with subqueries is more than one row returned for a single-row subquery.
In the SQL statement in the above example, the subquery contains a GROUP BY clause, which
implies that the subquery will return multiple rows, one for each group it finds. In this case, the
result of the subquery will be 2850, 3000 and 5000.
SQL> SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO;
MAX(SAL)
---------
2850
3000
5000
The outer query takes the results of the subquery (2850, 3000, 5000) and uses these results in
its WHERE clause. The WHERE clause contains an equal (=) operator, a single-row comparison
operator expecting only one value. The = operator cannot accept more than one value from the
subquery and therefore generates the error.
To correct this error, change the = operator to IN.
Find the employees who earn the same salary as the minimum salary for each department.
SQL> SELECT * FROM EMP
2 WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- -------------------------------
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
The inner query is executed first, producing a query result. The main query block is then
processed and uses the values returned by the inner query to complete its search condition. In
fact, the main query would appear to the Oracle server as follows:
SELECT last_name, salary, department_id
FROM employees
WHERE salary IN (2850, 3000, 5000);
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 70 of 89
Union
UNION is used to combine the results of two or more Select statements. However it will eliminate
duplicate rows from its result set. In case of union, number of columns and datatype must be same in
both the tables.
Tables for Example
Select deptno from emp; Select deptno from dept;
DEPTNO DEPTNO
------ ------
10 10
10 20
10 30
20 40
20
20
20
20
30
30
30
30
30
30
14 rows selected 4 rows selected
SQL> Select deptno from emp
2 union
3 Selectdeptno from dept;
DEPTNO
------
10
20
30
40
Union All
This operation is similar to Union. But it also shows the duplicate rows.
SQL> Select deptno from emp
2 Union all
3 Selectdeptno from dept;
DEPTNO
------
20
30
30
20
30
30
10
20
10
30
20
30
20
10
10
20
30
40
18 rows selected
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 71 of 89
Select deptnodept, ' ' loc from emp
Union all
Select deptnodept, locloc from dept
Selectto_char(deptno),' 'locfromemp
Unionall
Select' 'deptno,locfromdept
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records which
are common from both SELECT statements. In case of Intersect the number of columns and datatype
must be same.
DEPTNO
------
10
20
30
Minus
Minus operation combines result of two Select statements and return only those result which belongs
to first set of result.
DEPTNO
------
40
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 72 of 89
Analytic Functions
Analytic Functions are designed to address such problems as "Calculate a running total", "Find
percentages within a group", "Top-N queries", "Compute a moving average" and many more.
Most of these problems can be solved using standard PL/SQL, however the performance is often not
what it should be.
Analytic Functions add extensions to the SQL language that not only make these operations easier to
code; they make them faster than could be achieved with pure SQL or PL/SQL.
SAL SUM(SAL)OVER(ORDERBYHIREDATE)
--------- -----------------------------
800.00 800
1600.00 2400
1250.00 3650
2975.00 6625
2850.00 9475
2450.00 11925
1500.00 13425
1250.00 14675
5000.00 19675
950.00 23625
3000.00 23625
1300.00 24925
3000.00 27925
1100.00 29025
14 rows selected
14 rows selected
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 73 of 89
Creating Views
You can present logical subsets or combinations of data by creating views of tables. A view is a
logical table based on a table or another view. A view contains no data of its own but is like a
window through which data from tables can be viewed or changed. The tables on which a view
is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.
Advantages of Views
• Views restrict access to the data because the view can display selective columns from
the table.
• Views can be used to make simple queries to retrieve the results of complicated queries.
For example, views can be used to query information from multiple tables without the
user knowing how to write a join statement.
• Views provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
• Views provide groups of users access to data according to their particular criteria.
Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is related to
the DML (INSERT, UPDATE, and DELETE) operations.
• A simple view is one that:
• Derives data from only one table
• Contains no functions or groups of data
• Can perform DML operations through the view
• A complex view is one that:
• Derives data from many tables
• Contains functions or groups of data
• Does not always allow DML operations through the view
The following query will create a view based on EMP table having only six columns. The view is
created for restricting users from view salary and commission information.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 74 of 89
Retrieving data using view
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 75 of 89
Modifying a View
With the OR REPLACE option, a view can be created even if one exists with this name already, thus
replacing the old version of the view for its owner. This means that the view can be altered without
dropping, re-creating, and regranting object privileges.
The following view has been creating to view employee department # 10.
SQL> CREATE OR REPLACE VIEW EMP_VIEW_D10
2 AS SELECT * FROM EMP WHERE DEPTNO=10;
View created.
SQL> DESC EMP_VIEW_D10
Name Null? Type
------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
SQL> SELECT * FROM EMP_VIEW_D10;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- -----------------------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
You can add an alias for each column name.
SQL> CREATE OR REPLACE VIEW EMP_V2
2 (EMP_ID, EMP_NAME, DESG, SALARY, DEPT_ID) AS
3 SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
4 FROM EMP WHERE SAL>2000;
View created.
SQL> DESC EMP_V2
Name Null? Type
------------------------------- -------- ----
EMP_ID NOT NULL NUMBER(4)
EMP_NAME VARCHAR2(10)
DESG VARCHAR2(9)
SALARY NUMBER(7,2)
DEPT_ID NUMBER(2)
SQL> SELECT * FROM EMP_V2;
EMP_ID EMP_NAME DESG SALARY DEPT_ID
--------- ---------- ----------------- --------- ------------------------------
7566 JONES MANAGER 2975 20
7698 BLAKE MANAGER 2850 30
7782 CLARK MANAGER 2450 10
7788 SCOTT ANALYST 3000 20
7839 KING PRESIDENT 5000 10
7902 FORD ANALYST 3000 20
2 ASLAM MANAGER 2975 55
3 SALEEM ASST IT 2300 55
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 77 of 89
Inline Views
• An inline view is a subquery with an alias (or correlation name) that you can use within
a SQL statement.
• A named subquery in the FROM clause of the main query is an example of an inline
view.
• An inline view is not a schema object.
Top-N Analysis
• Top-N queries ask for the n largest or smallest values of a column. For example:
– What are the ten best selling products?
– What are the ten worst selling products?
• Both largest values and smallest values sets are considered Top-N queries.
To display the top three earner names and salaries from the EMP table:
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 78 of 89
Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
Primary key A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
Foreign key Uniquely identifies a row/record in another table
Unique key Ensures that all values in a column are different
Check key Ensures that all values in a column satisfies a specific condition
Not null Ensures that a column cannot have a NULL value
Primary key
Alter table student
Add constraint std_pk00
Primary key (std_id);
Foreign key
Alter table student
Add constraint std_fk00
Foreign key (teach_id) Refrences teacher (teach_id);
Unique key
Alter table student
Add constraint std_uk00
uniqyw key (std_id);
Check key
Alter table student
Add constraint std_ch01
uniqyw key (std_gender in (‘F’,’M’));
Not null
ALTER TABLE studentMODIFY (std_id NOT NULL);
Disable constraint
Disable constraint std_pk00
Enable constraint
Enable constraint std_pk00
Drop constraint
alter table student
drop constraint std_pk00
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 79 of 89
Creating a table
Create tables to store data by using CREATE TABLE statement. Create Table is a DDL
Statement.
ADD Column
After you create a table, you may need to change the table structure because: you omitted a
column, your column definition needs to be changed, or you need to remove columns. You can
do this by using the ALTER TABLE statement.
You can add, modify, and drop columns to a table by using the ALTER TABLE statement.
You use the ADD clause to add columns.
MODIFY Column
You can modify a column definition by using the ALTER TABLE statement with the MODIFY
clause. Column modification can include changes to a column’s data type, size, and default
value.
You use the MODIFY clause to add columns.
Rename Column
Changing the Name of an Object
Alter table student
Rename column Roll_no to Roll#;
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 80 of 89
Dropping a Column
You can drop a column from a table by using the ALTER TABLE statement with the DROP
COLUMN clause.
Dropping a Table
The DROP TABLE statement removes the definition of an Oracle table. When you drop a table,
the database loses all the data in the table and all the indexes associated with it.
Drop student;
You can add new rows to a table by using the INSERT statement.
Insert a new row containing values for each column.
Optionally, list the columns in the INSERT clause.
If you do not use the column list, the values must be listed according to the default order of the
columns in the table, and a value must be provided for each column.
Substitution Variables
A variable can be thought of as a container in which the values are temporarily stored. When
the statement is run, the value is substituted.
In SQL*Plus, you can use single ampersand (&) substitution variables to temporarily store
values. You can predefine variables in SQL*Plus by using the DEFINE command. DEFINE
creates and assigns a value to a variable.
Use SQL*Plus substitution variables to:
• Temporarily store values
– Single ampersand (&)
– Double ampersand (&&)
– DEFINE command
• Pass variable values between SQL statements
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 81 of 89
Update data in a Table
You can modify existing rows by using the UPDATE statement.
• Specific row or rows are modified if you specify the WHERE clause.
• All rows in the table are modified if you omit the WHERE clause.
Update student
Set std_name = ‘Asif’
Where std_id = 6;
Update student
Set std_f_name = ‘Muhammad Ishaq’
Where std_name = ‘Asif’;
All rows in the table are deleted if you omit the WHERE clause.
Delete student
Truncating a Table
Another DDL statement is the TRUNCATE TABLE statement, which is used to remove all rows
from a table and to release the storage space used by that table. When using the TRUNCATE
TABLE statement, you cannot roll back row removal.
You must be the owner of the table or have DELETE TABLE system privileges to truncate a
table.
The DELETE statement can also remove all rows from a table, but it does not release storage
space. The TRUNCATE command is faster. Removing rows with the TRUNCATE statement is
faster than removing them with the DELETE statement for the following reasons:
• The TRUNCATE statement is a data definition language (DDL) statement and generates
no rollback information.
• Truncating a table does not fire the delete triggers of the table.
• If the table is the parent of a referential integrity constraint, you cannot truncate the
table. Disable the constraint before issuing the TRUNCATE statement.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 82 of 89
Create Copy Table
Create Synonyms
Creating an Index
Create an index on one or more columns by issuing the CREATE INDEX statement.
Automatically index creation:
Add a new column NIC in EMP table,
Add a unique constraint on NIC column
Unique index will be created automatically
ALTER TABLE EMP
ADD NIC VARCHAR2(15) CONSTRAINT EMP_NIC_U UNIQUE;
Table altered.
Manually index creation:
Create an index on ENAME to improve the speed of query access to the ENAME column in the
EMP table.
CREATE INDEX INDX_EMP_ENAME
ON EMP (ENAME);
Index created.
Create an index on SAL, COMM to improve the speed of query access.
CREATE INDEX INDX_EMP_SAL_COMM
ON EMP (SAL,COMM);
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 83 of 89
Controlling User Access
Users in Oracle
In Oracle terminology, a user is someone who can connect to a database (if granted enough
privileges) and optionally (again, if granted the appropriate privileges) can own objects (such
as tables) in the database.
The objects a user owns are collectively called schema. A schema, on its part, is always bound
to exactly one user. Because there is obviously a 1 to 1 relationship between a user and a
schema, these two terms are often used interchangeable.
In order to find out what users are created on the database, one can use DBA_USERS.
Database rights (Privileges)
Users can be assigned rights what they're allowed to do in a database and what not. These
rights are called privileges.
Privileges
A privilege is a right to execute an SQL statement or to access another user's object.
In Oracle, there are two types of privileges:
• System privileges
• Object privileges.
A privilege can be assigned to a user or a privilege.
The set of privileges is fixed, that is, there is no SQL statement like create privilege xyz...
System privileges
Once a user is created, the DBA can grant specific system privileges to a user.
There are quite a few system privileges:
in Oracle 9.2, we count 157 of them, and 10g has even 173. Those can be displayed with:
SQL> SELECT NAME FROM SYSTEM_PRIVILEGE_MAP
Executing this statement, we find privileges like create session, drop user, alter database.
Arguably, the most important system privileges are:
• CREATE SESSION
(A user cannot login without this privilege. If he tries, he gets an ORA-01045).
• CREATE TABLE
• CREATE VIEW
• CREATE PROCEDURE
• SYSDBA
• SYSOPER
System privileges can be displayed using USER_SYS_PRIVS data dictionary view Object privileges
An object privilege is a privilege or right to perform a particular action on a specific object
(table, view, sequence, or procedure ect.) Each object has a particular set of grantable
privileges.
Some objects privileges are:
• Tables (SELECT, INSERT, UPDATE, DELETE, ALTER etc.)
• Views (SELECT, INSERT, UPDATE, DELETE etc.)
• Sequence (ALTER, SELECT)
• Packeges, Procedures, Functions (EXECUTE, DEBUG)
• Directories (READ, WRITE )
For a user to be able to access an object in another user's schema, he needs the according
object privilege.
Object privileges can be displayed using all_tab_privs_madeor user_tab_privs_made.
Public
If a privilege is granted to the special role public, this privilege can be executed by all other
users. However, sysdba cannot be granted to public.
Role
A role is a named group of related privileges that can be granted to the user. This method
makes it easier to revoke and maintain privileges.
A user can have access to several roles, and several users can be assigned the same role. Roles
are typically created for a database application.
Predefined Roles
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 84 of 89
Along with the installation, more exactly with the creation of an oracle database, Oracle creates
predefined roles. These are:
• connect, resource, dba
These might not be created anymore in future versions of Oracle.
Oracle 9.2 grants create session, alter session, create synonym, create view, create
database link, create table, create cluster and create sequence to connect.
It also grants create table, create cluster, create sequence, create trigger create procedure,
create type, create indextype and create operator to resource.
The role dbagets basically everything and that with admin option.
Creating user
The DBA creates the user by executing the CREATE USER statement. The user does not have
any privileges at this point. The DBA can then grant privileges to that user. These privileges
determine what the user can do at the database level.
SQL> CONN SYS/ORACLE AS SYSDBA
Connected.
SQL>
SQL> SHOW USER
USER is "SYS"
SQL>
SQL> CREATE USER ATIF IDENTIFIED BY ASATTAR;
User created.
The user does not have any privileges at this point. The DBA can then grant privileges to that
user. These privileges determine what the user can do at the database level.
SQL> CONN ATIF/ASATTAR
ERROR:
ORA-01045: user ATIF lacks CREATE SESSION privilege; logon denied
Warning: You are no longer connected to ORACLE.
SQL>
Granting System Privileges
The DBA uses the GRANT statement to allocate system privileges to the user or role. Once the
user has been granted the privileges, the user can immediately use those privileges.
In the example, user ATIF has been assigned the privileges to create sessions, tables,
sequences, and views.
SQL> GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW
2 TO ATIF;
Grant succeeded.
SQL> CONN ATIF/ASATTAR
Connected.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 85 of 89
SQL> DESC USER_USERS
Name Null? Type
----------------------------------------- -------- ----------------------------
USERNAME NOT NULL VARCHAR2(30)
USER_ID NOT NULL NUMBER
ACCOUNT_STATUS NOT NULL VARCHAR2(32)
LOCK_DATE DATE
EXPIRY_DATE DATE
DEFAULT_TABLESPACE NOT NULL VARCHAR2(30)
TEMPORARY_TABLESPACE NOT NULL VARCHAR2(30)
CREATED NOT NULL DATE
INITIAL_RSRC_CONSUMER_GROUP VARCHAR2(30)
EXTERNAL_NAME VARCHAR2(4000)
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 86 of 89
SQL> SELECT * FROM USER_TS_QUOTAS;
TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO
------------------------------ ---------- ---------- ---------- ---------- ---
USERS 0 5242880 0 640 NO
SQL> CREATE TABLE EMPLOYEE
2(
3 EMPNO NUMBER(4) PRIMARY KEY,
4 ENAME VARCHAR2(20)
5 );
Table created.
You can remove privileges granted to other users by using the REVOKE statement. When you
use the REVOKE statement, the privileges that you specify are revoked from the users you
name and from any other users to whom those privileges were granted through the WITH
GRANT OPTION clause.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 87 of 89
SQL> CREATE TABLE STUDENT
2(
3 GRNO NUMBER(4) PRIMARY KEY,
4 NAME VARCHAR2(20)
5 );
CREATE TABLE STUDENT
*
ERROR at line 1:
ORA-01031: insufficient privileges
If you want to access objects of any other user, then you must have rights/privileges on that
objects to access them. Owner of objects grants rights on his objects.
SQL> CONN SCOTT/TIGER
Connected.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 88 of 89
SQL> SELECT COUNT(*) FROM SCOTT.EMP;
COUNT(*)
----------
18
SCOTT can not revoke privileges directly on EMP table from MR user
SCOTT can revoke privileges from ATIF user, and indirectly revoke from MR user
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 89 of 89