Sei sulla pagina 1di 89

SQL

STRUCTURE QUREY LANGUAGE


R.D.B.M.S
Relational Database Management System

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)

DML (Data Manipulation Language)


DML statements affect records in a table. These are basic operations we perform on
data such as selecting a few records from a table, inserting new records, deleting
unnecessary records, and updating/modifying existing records.
DML statements include the following:

SELECT – select records from a table


INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records

DDL (Data Definition Language)


DDL statements are used to alter/modify a database or table structure and schema.
These statements handle the design and storage of database objects.
CREATE – create a new Table, database, schema
ALTER – alter existing table, column description
DROP – delete existing objects from database

DCL (Data Control Language)


DCL statements control the level of access that users have on database objects.
GRANT – allows users to read/write on certain database objects
REVOKE – keeps users from read/write permission on database objects

TCL (Transaction Control Language)


TCL statements allow you to control and manage transactions to maintain the
integrity of data within SQL statements.
BEGIN Transaction – opens a transaction
COMMIT Transaction – commits a transaction
ROLLBACK Transaction – ROLLBACK a transaction in case of any error

_________________________________________________________________________
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:

SELECT EMPNO, ENAME, JOB, SAL FROM EMP;


SQL Query is also called SQL statement.
Result of the above query:
EMPNO ENAME JOB SAL
---------------------------------------------------------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500
7876 ADAMS CLERK 1100

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.

SELECT & FROM Keywords


Specify number of columns just after SELECT.
Specify table name just after FROM keyword.

Solve the following:


Display all columns and all rows of EMP table.

SQL> SELECT * FROM EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- --------- --------- --------- --------- ------------------------------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 LLEN 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
14 rows selected.

Display all columns and all rows of DEPT table.

SQL> SELECT * FROM DEPT;

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 4 of 89
Tab is listing the table and views
SQL>select * from tab;

TNAME TABTYPE CLUSTERID


--------------------------------------------------------------------------
BONUS TABLE
DEPT TABLE
EMP TABLE
EMP_ATTEND TABLE
EMP_COP TABLE
EMP_COPY TABLE
EMP_TEST VIEW
SALGRADE TABLE

CAT is listing all the tables, views and sequences also.


SQL> select * from cat;

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

SQL> DESC EMP


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)

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;

EMPNO ENAME JOB SAL


----------------------------------------------------------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

SQL> SELECT ENAME, JOB, SAL, DEPTNO FROM EMP;

ENAME JOB SAL DEPTNO


---------- --------- --------- -----------------------------
SMITH CLERK 800 20
ALLEN SALESMAN 1600 30
WARD SALESMAN 1250 30
JONES MANAGER 2975 20
MARTIN SALESMAN 1250 30
BLAKE MANAGER 2850 30
CLARK MANAGER 2450 10
SCOTT ANALYST 3000 20
KING PRESIDENT 5000 10
TURNER SALESMAN 1500 30
ADAMS CLERK 1100 20
JAMES CLERK 950 30
FORD ANALYST 3000 20
MILLER CLERK 1300 10

SQL> SELECT 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

The ORDER BY Clause


The order of rows returned in a query result is undefined. The ORDER BY clause can be used to sort
the rows. If you use the ORDER BY clause, it must be the last clause of the SQL statement. You can
specify an expression, or an alias, or column position as the sort condition.

Sorting By Column Name


SQL> SELECT * FROM EMP ORDER BY ENAME;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----------------- --------- --------- --------- --------- --------- ------------------------------------
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

Sorting on Multiple Columns


SQL> SELECT * FROM EMP ORDER BY DEPTNO, ENAME;

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
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

SQL> SELECT * FROM EMP ORDER BY ENAME DESC;


SQL> SELECT * FROM EMP ORDER BY DEPTNO, ENAME DESC;
SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB;
SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB DESC;

_________________________________________________________________________
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;

Sorting By Column Alias


SQL> SELECT ENAME,SAL,COMM, SAL*12 ANN_SAL FROM EMP ORDER BY ANN_SAL;

ENAME SAL COMM ANN_SAL


---------- --------- --------- -------------------------
SMITH 800 9600
JAMES 950 11400
ADAMS 1100 13200
WARD 1250 500 15000
MARTIN 1250 1400 15000
MILLER 1300 15600
TURNER 1500 0 18000
ALLEN 1600 300 19200
CLARK 2450 29400
BLAKE 2850 34200
JONES 2975 35700
SCOTT 3000 36000
FORD 3000 36000
KING 5000 60000

SQL> SELECT EMPNO, ENAME, SAL SALARY FROM EMP ORDER BY SALARY;

How Null Values Appear When Ordering (Sorting)

SQL> SELECT * FROM EMP ORDER BY COMM;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ------- --------- --------- --------- --------- --------- ------------------------------------
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
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
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7782 CLARK MANAGER 7839 09-JUN-81 2450 10

_________________________________________________________________________
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.

SQL> DESC DUAL

Name Null? Type


------------------------------- -------- ----
DUMMY VARCHAR2(1)

SQL> SELECT * FROM DUAL;


D
-
X
Display Current Date using DUAL Table

SQL> SELECT SYSDATE FROM DUAL;


SYSDATE
---------
01-JAN-17

Display Current User using DUAL Table

SQL> SELECT USER FROM DUAL;


USER
------------------------------
SCOTT

Display Calculation using DUAL Table

SQL> SELECT 7+10 FROM DUAL;


7+10
----------
17

SQL> SELECT 7+10-2+5 FROM DUAL;


7+10-2+5
----------
20

SQL> SELECT 7+10*2+5 FROM DUAL;


7+10*2+5
----------
32

SQL> SELECT 7+10-2*5 FROM DUAL;


7+10-2*5
----------
7

_________________________________________________________________________
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;

EMPNO ENAME SAL SAL+100 SAL-100 SAL*12 SAL/30


----- ---------- --------- ---------- ---------- ---------- -------------------------------------------------------
7369 SMITH 800.00 900 700 9600 26.6666666
7499 ALLEN 1600.00 1700 1500 19200 53.3333333
7521 WARD 1250.00 1350 1150 15000 41.6666666
7566 JONES 2975.00 3075 2875 35700 99.1666666
7654 MARTIN 1250.00 1350 1150 15000 41.6666666
7698 BLAKE 2850.00 2950 2750 34200 95
7782 CLARK 2450.00 2550 2350 29400 81.6666666
7788 SCOTT 3000.00 3100 2900 36000 100
7839 KING 5000.00 5100 4900 60000 166.666666
7844 TURNER 1500.00 1600 1400 18000 50
7876 ADAMS 1100.00 1200 1000 13200 36.6666666
7900 JAMES 950.00 1050 850 11400 31.6666666
7902 FORD 3000.00 3100 2900 36000 100
7934 MILLER 1300.00 1400 1200 15600 43.3333333

14 rows selected

SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM FROM EMP;

EMPNO ENAME SAL COMM SAL+COMM


---------------------------------------------------------------------
7369 SMITH 800
7499 ALLEN 1600 300 1900
7521 WARD 1250 500 1750
7566 JONES 2975
7654 MARTIN 1250 1400 2650
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000
7839 KING 5000
7844 TURNER 1500 0 1500
7876 ADAMS 1100
7900 JAMES 950
7902 FORD 3000
7934 MILLER 1300

_________________________________________________________________________
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

SQL> SELECT SYSDATE, SYSDATE+1, SYSDATE-1 FROM DUAL;

SYSDATE SYSDATE+1 SYSDATE-1


---------------------------------------------------
14-JUL-08 15-JUL-08 13-JUL-08

SQL> SELECT SYSDATE, SYSDATE+7, SYSDATE+30, SYSDATE+365 FROM DUAL;

SYSDATE SYSDATE+7 SYSDATE+3 SYSDATE+3


-----------------------------------------------------------------
14-JUL-08 21-JUL-08 13-AUG-08 14-JUL-09

SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE+1, HIREDATE+7 FROM EMP;

EMPNO ENAME HIREDATE HIREDATE+ HIREDATE+


-------------------------------------------------------------------------------------------
7369 SMITH 17-DEC-80 18-DEC-80 24-DEC-80
7499 ALLEN 20-FEB-81 21-FEB-81 27-FEB-81
7521 WARD 22-FEB-81 23-FEB-81 01-MAR-81
7566 JONES 02-APR-81 03-APR-81 09-APR-81
7654 MARTIN 28-SEP-81 29-SEP-81 05-OCT-81
7698 BLAKE 01-MAY-81 02-MAY-81 08-MAY-81
7782 CLARK 09-JUN-81 10-JUN-81 16-JUN-81
7788 SCOTT 19-APR-87 20-APR-87 26-APR-87
7839 KING 17-NOV-81 18-NOV-81 24-NOV-81
7844 TURNER 08-SEP-81 09-SEP-81 15-SEP-81
7876 ADAMS 23-MAY-87 24-MAY-87 30-MAY-87
7900 JAMES 03-DEC-81 04-DEC-81 10-DEC-81
7902 FORD 03-DEC-81 04-DEC-81 10-DEC-81
7934 MILLER 23-JAN-82 24-JAN-82 30-JAN-82

SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE-7 FROM EMP;

EMPNO ENAME HIREDATE HIREDATE-


-----------------------------------------------------------------------
7369 SMITH 17-DEC-80 10-DEC-80
7499 ALLEN 20-FEB-81 13-FEB-81
7521 WARD 22-FEB-81 15-FEB-81
7566 JONES 02-APR-81 26-MAR-81
7654 MARTIN 28-SEP-81 21-SEP-81
7698 BLAKE 01-MAY-81 24-APR-81
7782 CLARK 09-JUN-81 02-JUN-81
7788 SCOTT 19-APR-87 12-APR-87
7839 KING 17-NOV-81 10-NOV-81
7844 TURNER 08-SEP-81 01-SEP-81
7876 ADAMS 23-MAY-87 16-MAY-87
7900 JAMES 03-DEC-81 26-NOV-81
7902 FORD 03-DEC-81 26-NOV-81
7934 MILLER 23-JAN-82 16-JAN-82

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 11 of 89
NVL
NULL value can be controlled with NVL () function

NVL (column_name, replaced_value)

SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,0) FROM EMP;


NULL will be replaced with 0

SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,100) FROM EMP;


NULL will be replaced with 100

SQL> SELECT EMPNO, ENAME, COMM, NVL(COMM,0), NVL(COMM,50) FROM EMP;

EMPNO ENAME COMM NVL(COMM,0) NVL(COMM,50)


-------------------------------------------------------------------------------------------------
7369 SMITH 0 50
7499 ALLEN 300 300 300
7521 WARD 500 500 500
7566 JONES 0 50
7654 MARTIN 1400 1400 1400
7698 BLAKE 0 50
7782 CLARK 0 50
7788 SCOTT 0 50
7839 KING 0 50
7844 TURNER 0 0 0
7876 ADAMS 0 50
7900 JAMES 0 50
7902 FORD 0 50
7934 MILLER 0 50

SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, SAL+COMM, SAL+NVL(COMM,0) FROM EMP;

EMPNO ENAME JOB SAL COMM SAL+COMM


SAL+NVL(COMM,0)
----- ---------- --------- --------- --------- ---------- ---------------
7369 SMITH CLERK 800.00 800
7499 ALLEN SALESMAN 1600.00 300.00 1900 1900
7521 WARD SALESMAN 1250.00 500.00 1750 1750
7566 JONES MANAGER 2975.00 2975
7654 MARTIN SALESMAN 1250.00 1400.00 2650 2650
7698 BLAKE MANAGER 2850.00 2850
7782 CLARK MANAGER 2450.00 2450
7788 SCOTT ANALYST 3000.00 3000
7839 KING PRESIDENT 5000.00 5000
7844 TURNER SALESMAN 1500.00 0.00 1500 1500
7876 ADAMS CLERK 1100.00 1100
7900 JAMES CLERK 950.00 950
7902 FORD ANALYST 3000.00 3000
7934 MILLER CLERK 1300.00 1300

_________________________________________________________________________
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;

EMPNO ENAME DESIGNATION SALARY COMMISSION


----------------------------------------------------------------------------------------------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600 300
7521 WARD SALESMAN 1250 500
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250 1400
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500 0
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

SQL> SELECT EMPNO, ENAME, SAL, SAL*12 ANN_SAL FROM EMP;

EMPNO ENAME SAL ANN_SAL


---------------------------------------------------------------
7369 SMITH 800 9600
7499 ALLEN 1600 19200
7521 WARD 1250 15000
7566 JONES 2975 35700
7654 MARTIN 1250 15000
7698 BLAKE 2850 34200
7782 CLARK 2450 29400
7788 SCOTT 3000 36000
7839 KING 5000 60000
7844 TURNER 1500 18000
7876 ADAMS 1100 13200
7900 JAMES 950 11400
7902 FORD 3000 36000
7934 MILLER 1300 15600

_________________________________________________________________________
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;

EMPNO ENAME JOB MONTHLY_SALARY GROSS_SALARYANNUAL_SALARY


--------- ---------- --------- -------------- ------------ ---------------------------------------------------------
7369 SMITH CLERK 800 800 9600
7499 ALLEN SALESMAN 1600 1900 19200
7521 WARD SALESMAN 1250 1750 15000
7566 JONES MANAGER 2975 2975 35700
7654 MARTIN SALESMAN 1250 2650 15000
7698 BLAKE MANAGER 2850 2850 34200
7782 CLARK MANAGER 2450 2450 29400
7788 SCOTT ANALYST 3000 3000 36000
7839 KING PRESIDENT 5000 5000 60000
7844 TURNER SALESMAN 1500 1500 18000
7876 ADAMS CLERK 1100 1100 13200
7900 JAMES CLERK 950 950 11400
7902 FORD ANALYST 3000 3000 36000
7934 MILLER CLERK 1300 1300 15600

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;

EMPNO ENAME JOB TITLE salary COMMISSION


--------- ---------- --------- --------- ----------------------------------------------
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600 300
7521 WARD SALESMAN 1250 500
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250 1400
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500 0
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

Table Alias

SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO


FROM EMP E;

SELECT D.DNAME, D.LOC


FROM DEPT D;

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 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

SQL> SELECT EMPNO||ENAME FROM EMP;

EMPNO||ENAME
--------------------------------------------------
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER

SQL> SELECT EMPNO||ENAME||JOB EMPLOYEE_INFO FROM EMP;

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

Literal Character Strings


A literal is a character, a number, or a date that is included in the SELECT list and that is not a column
name or a column alias. It is printed for each row returned. Literal strings of free format text can be
included in the query result and are treated the same as a column in the SELECT list. Date and
character literals must be enclosed within single quotation marks (' '); number literals need not.

SQL> SELECT EMPNO, ENAME, JOB, 5000, 'KARACHI', '14-AUG-1947' FROM EMP;

EMPNO ENAME JOB 5000 'KARACH '14-AUG-1947


--------- ---------- --------- --------- ------- -------------------------------------------
7369 SMITH CLERK 5000 KARACHI 14-AUG-1947
7499 ALLEN SALESMAN 5000 KARACHI 14-AUG-1947
7521 WARD SALESMAN 5000 KARACHI 14-AUG-1947
7566 JONES MANAGER 5000 KARACHI 14-AUG-1947
7654 MARTIN SALESMAN 5000 KARACHI 14-AUG-1947
7698 BLAKE MANAGER 5000 KARACHI 14-AUG-1947
7782 CLARK MANAGER 5000 KARACHI 14-AUG-1947
7788 SCOTT ANALYST 5000 KARACHI 14-AUG-1947
7839 KING PRESIDENT 5000 KARACHI 14-AUG-1947
7844 TURNER SALESMAN 5000 KARACHI 14-AUG-1947
7876 ADAMS CLERK 5000 KARACHI 14-AUG-1947
7900 JAMES CLERK 5000 KARACHI 14-AUG-1947
7902 FORD ANALYST 5000 KARACHI 14-AUG-1947
7934 MILLER CLERK 5000 KARACHI 14-AUG-1947

SQL> SELECT 'Mr. '||ENAME EMPLOYEE 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

SQL> SELECT 'Rs. '||SAL SALAR FROM EMP;


SQL> SELECT ENAME||' WORKS IN DEPARTMENT NUMBER '||DEPTNO EMPLOYEE FROM EMP;
SQL> SELECT ENAME||' IS EARNING '||SAL||' PER MONTH' SALARY FROM EMP;

_________________________________________________________________________
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;

Employee Salary Info...


----------------------------------------------------------------------------
SMITH Earn Monthly 800 And His Annual Salary Is 9600
ALLEN Earn Monthly 1600 And His Annual Salary Is 19200
WARD Earn Monthly 1250 And His Annual Salary Is 15000
JONES Earn Monthly 2975 And His Annual Salary Is 35700
MARTIN Earn Monthly 1250 And His Annual Salary Is 15000
BLAKE Earn Monthly 2850 And His Annual Salary Is 34200
CLARK Earn Monthly 2450 And His Annual Salary Is 29400
SCOTT Earn Monthly 3000 And His Annual Salary Is 36000
KING Earn Monthly 5000 And His Annual Salary Is 60000
TURNER Earn Monthly 1500 And His Annual Salary Is 18000
ADAMS Earn Monthly 1100 And His Annual Salary Is 13200
JAMES Earn Monthly 950 And His Annual Salary Is 11400
FORD Earn Monthly 3000 And His Annual Salary Is 36000
MILLER Earn Monthly 1300 And His Annual Salary Is 15600

_________________________________________________________________________
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.

SQL> SELECT DISTINCT DEPTNO FROM EMP;

DEPTNO
---------
30
20
10

SQL> SELECT DISTINCT JOB FROM EMP;

JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST

SQL> SELECT DISTINCT DEPTNO, JOB FROM EMP;

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.

SQL> SELECT * FROM EMP WHERE DEPTNO=10;

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

Display all employees who are earning 5000.

SQL> SELECT * FROM EMP WHERE SAL = 5000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ----- --------- --------- --------- -----------------------------------------------------------------
7839 KING PRESIDENT 17-NOV-81 5000 10

The following query retrieves records of all employees who are working as CLERK.

SQL> SELECT * FROM EMP WHERE JOB='CLERK';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----------------- --------- --------- --------- --------- --------- -------------------------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7934 MILLER CLERK 7782 23-JAN-82 1300 10
Note that the job title CLERK has been specified in uppercase to ensure that it matches the job column
in the EMP table. Character strings are case sensitive. If data is stored in uppercase and you specify
condition in lowercase then the result retrieve no record.

SQL> SELECT * FROM EMP WHERE JOB='clerk';


no rows selected

Retrieve all employees who were hired on 03-DEC-1981

SQL> SELECT * FROM EMP WHERE HIREDATE='03-DEC-1981';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ------- --------- --------- --------- --------- --------- ------------------------------------
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Character Strings and Dates
Character strings and dates in the WHERE clause must be enclosed in single quotation marks ('').
Number constants, however, should not be enclosed in single quotation marks.
All character searches are case sensitive. In the following example, no rows are returned because the
EMP table stores all names in upper case:
SELECT * FROM EMP WHERE JOB='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 > 4. Less Then <
5. Greater Then Equal >= 6. Less Then Equal <=

1. Equal

SQL> Select* from emp Where sal = 1500;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- ------------------------------------------ ------
7844 TURNER SALESMAN 7698 08/Sep/81 1500 0 30

2.Not Equal

SQL> Select* from emp Where sal<> 5000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20
13 rows selected

3. Greater Then

SQL> Select* from emp Where sal>3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- -------------------------------------------
7839 KING PRESIDENT 17/Nov/81 5000.00 10

1 rows selected ows selected


_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 20 of 89
4.Less Then
SQL> Select* from emp Where sal< 3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30
7934 MILLER CLERK 7782 23/Jan/82 1300.00 10
11 rows selected

5. Greater Then Equal


SQL> Select* from emp Where sal>= 3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ---------------------------------------------------
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7839 KING PRESIDENT 17/Nov/81 5000.00 10
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20

6. Less Then Equal


SQL> Select* from emp Where sal<= 3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- -------------------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20
7934 MILLER CLERK 7782 23/Jan/82 1300.00 10
13 rows selected

_________________________________________________________________________
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

1. In: Match any of a list of values

SQL> Select* from emp Where deptno in (10, 20);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ----------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7839 KING PRESIDENT 17/Nov/81 5000.00 10
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20
7934 MILLER CLERK 7782 23/Jan/82 1300.00 10
8 rows selected

2.NotIn:Not match any of a list of values

SQL> Select* from emp Where deptno not in (10, 20);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- -------------------------------------------
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30
7900 JAMES CLERK 7698 03/Dec/81 950.00 30
6 rows selected

3. Between:Between two values (inclusive)

SQL> Select* from emp Where sal between 800 and 1000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- -----------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30

_________________________________________________________________________
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;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7839 KING PRESIDENT 17/Nov/81 5000.00 10
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20
7934 MILLER CLERK 7782 23/Jan/82 1300.00 10
12 rows selected

5.IsNull:Is a null value

SQL> Select* from emp Where comm is null;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- --------------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7839 KING PRESIDENT 17/Nov/81 5000.00 10
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20
7934 MILLER CLERK 7782 23/Jan/82 1300.00 10
11 rows selected

6.Is Not Null: Is a not null value

SQL> Select* from emp Where comm is not null;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ----------------------------------------------
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7844 TURNER SALESMAN 7698 08/Sep/81 1500.00 0.00 30

_________________________________________________________________________
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%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ----------------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20

SQL> Select* from emp Where ename like '%S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ---------------------------------------------
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30

SQL> Select* from emp Where ename like '%S%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------------------------------------------------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30

SQL> Select* from emp Where ename like '____S'; (S After 4 digit)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ----------------------------------------------
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7876 ADAMS CLERK 7788 23/May/87 1100.00 20
7900 JAMES CLERK 7698 03/Dec/81 950.00 30

SQL> Select* from emp Where ename like '____'; (Only 4 digit name)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- --------------------------------------------------
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7839 KING PRESIDENT 17/Nov/81 5000.00 10
7902 FORD ANALYST 7566 03/Dec/81 3000.00 20

_________________________________________________________________________
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%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30

SQL> Select* from emp Where ename not like '%S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30

SQL> Select* from emp Where ename not like '%S%';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30
7782 CLARK MANAGER 7839 09/Jun/81 2450.00 10

SQL> Select* from emp Where ename not like '____S'; (S After 4 digit)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7521 WARD SALESMAN 7698 22/Feb/81 1250.00 500.00 30
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30

SQL> Select* from emp Where ename not like '____'; (Only 4 digit name)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7499 ALLEN SALESMAN 7698 20/Feb/81 1600.00 300.00 30
7566 JONES MANAGER 7839 02/Apr/81 2975.00 20
7654 MARTIN SALESMAN 7698 28/Sep/81 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 01/May/81 2850.00 30

_________________________________________________________________________
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

Retrieve all clerks of department number 20


SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' AND DEPTNO=20;
EMPNO ENAME JOB DEPTNO
--------- ---------- --------- ----------------------
7369 SMITH CLERK 20
7876 ADAMS CLERK 20

Retrieve all salesman who are earning more than 1500


SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND SAL>1500;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ----------------- --------- --------- --------- --------- -------------------------------------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Retrieve all salesman who were hired before mar 1981


SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND HIREDATE<'01-MAR-1981';
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
Using the OR Operator
OR requires either condition to be true.
If either condition is TRUE result will be TRUE in case of OR
CONDITION 1 CONDITION 2 RESULT
TRUE TRUETRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSEFALSE
Retrieve either all clerks or all employees of department number 20
SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' OR DEPTNO=20;
EMPNO ENAME JOB DEPTNO
--------- ---------- --------- -----------------------------------
7369 SMITH CLERK 20
7566 JONES MANAGER 20
7788 SCOTT ANALYST 20
7876 ADAMS CLERK 20
7900 JAMES CLERK 30
7902 FORD ANALYST 20
7934 MILLER CLERK 10
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 26 of 89
Single-Row Functions
Single row functions:
Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the data type
Can be nested
Accept arguments which can be a column or an expression

Types of Single Row Functions


1.Upper 2.Lower 3.Initcap 4.Lpad 5.Rpad 6.Ltrim
7.Rtrim 8.Replace 9.Length 10.Substr 11.Instr 12.Sign
13.Ceil 14.Floor 15.Trunc 16.Round 17. Mod

LOWER, UPPER, and INITCAP are the three case-conversion functions.

1.UPPER (UPPER: Converts mixed case or lowercase character strings to uppercase)


SQL> Select upper (ename) from emp;

UPPER(ENAME)
------------
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

SQL> Select empno,ename,job,sal, upper (ename) from emp;

EMPNO ENAME JOB SAL UPPER(ENAME)


----- ---------- --------- --------- -----------------------------------------------------------
7369 SMITH CLERK 800.00 SMITH
7499 ALLEN SALESMAN 1600.00 ALLEN
7521 WARD SALESMAN 1250.00 WARD
7566 JONES MANAGER 2975.00 JONES
7654 MARTIN SALESMAN 1250.00 MARTIN
7698 BLAKE MANAGER 2850.00 BLAKE
7782 CLARK MANAGER 2450.00 CLARK
7788 SCOTT ANALYST 3000.00 SCOTT
7839 KING PRESIDENT 5000.00 KING
7844 TURNER SALESMAN 1500.00 TURNER
7876 ADAMS CLERK 1100.00 ADAMS
7900 JAMES CLERK 950.00 JAMES
7902 FORD ANALYST 3000.00 FORD
7934 MILLER CLERK 1300.00 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

SQL> Select empno,ename,job,sal, lower(ename) from emp;

EMPNO ENAME JOB SAL LOWER(ENAME)


----- ---------- --------- --------- ------------
7369 SMITH CLERK 800.00 smith
7499 ALLEN SALESMAN 1600.00 allen
7521 WARD SALESMAN 1250.00 ward
7566 JONES MANAGER 2975.00 jones
7654 MARTIN SALESMAN 1250.00 martin
7698 BLAKE MANAGER 2850.00 blake
7782 CLARK MANAGER 2450.00 clark

3.INITCAP(INITCAP: Converts the first letter of each word to uppercase and remaining letters to
lowercase)

SQL> Select initcap(ename) from emp;

INITCAP(ENAME)
--------------
Smith
Allen
Ward
Jones
Martin
Blake
Clark
Scott
King
Turner

SQL> Select empno,ename,job,sal, initcap(ename) from emp;

EMPNO ENAME JOB SAL INITCAP(ENAME)


----- ---------- --------- --------- ------------------------------------------------------
7369 SMITH CLERK 800.00 Smith
7499 ALLEN SALESMAN 1600.00 Allen
7521 WARD SALESMAN 1250.00 Ward
7566 JONES MANAGER 2975.00 Jones
7654 MARTIN SALESMAN 1250.00 Martin
7698 BLAKE MANAGER 2850.00 Blake
7782 CLARK MANAGER 2450.00 Clark
7788 SCOTT ANALYST 3000.00 Scott
7839 KING PRESIDENT 5000.00 King
7844 TURNER SALESMAN 1500.00 Turner
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 28 of 89
4. LPAD(Pads the character value to left side)
SQL> Select lpad(sal,8,'*') from emp;
LPAD(SAL,8,'*')
---------------
*****800
****1600
****1250
****2975

SQL> Select empno,ename,job, lpad(sal,8,'*'),sal,deptno from emp;


EMPNO ENAME JOB LPAD(SAL,8,'*') SAL DEPTNO
----- ---------- --------- --------------- --------- -----------------------------------------------------
7369 SMITH CLERK *****800 800.00 20
7499 ALLEN SALESMAN ****1600 1600.00 30
7521 WARD SALESMAN ****1250 1250.00 30
7566 JONES MANAGER ****2975 2975.00 20

5. RPAD(Pads the character value to right side)


SQL> Select rpad(sal,8,'*') from emp;
RPAD(SAL,8,'*')
---------------
800*****
1600****
1250****
2975****

SQL> Select empno,ename,job,rpad(sal,8,'*'),sal,deptno from emp;


EMPNO ENAME JOB RPAD(SAL,8,'*') SAL DEPTNO
----- ---------- --------- --------------- --------- -------------------------------------------
7369 SMITH CLERK 800***** 800.00 20
7499 ALLEN SALESMAN 1600**** 1600.00 30
7521 WARD SALESMAN 1250**** 1250.00 30
7566 JONES MANAGER 2975**** 2975.00 20

LPAD &RPAD(Pads the character value to both side)


SQL> Select lpad(rpad(sal,8,'*'),9,'$') from emp;

LPAD(RPAD(SAL,8,'*'),9,'$')
---------------------------
$800*****
$1600****
$1250****
$2975****
$1250****

SQL> Select empno,ename,job, lpad(rpad(sal,8,'*'),9,'$'),sal,deptno from emp;

EMPNO ENAME JOB LPAD(RPAD(SAL,8,'*'),9,'$') SAL DEPTNO


----- ---------- --------- --------------------------- --------- ------
7369 SMITH CLERK $800***** 800.00 20
7499 ALLEN SALESMAN $1600**** 1600.00 30
7521 WARD SALESMAN $1250**** 1250.00 30
7566 JONES MANAGER $2975**** 2975.00 20
7654 MARTIN SALESMAN $1250**** 1250.00 30

_________________________________________________________________________
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

7. RTRIM(Remove one digit from right side in word)


SQL> Select rtrim(ename,'S'),ename from emp;

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

10. SUBSTR(Extracts a string of determined length (specified named character)


SQL> SELECT SUBSTR('PETROMAN',1,3) FROM DUAL;

SUBSTR('PETROMAN',1,3)
----------------------
PET

SQL> SELECT SUBSTR('PETROMAN',-3,3) FROM DUAL;

SUBSTR('PETROMAN',-3,3)
-----------------------
MAN

SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,1,1)='S';

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 17/Dec/80 800.00 20
7788 SCOTT ANALYST 7566 19/Apr/87 3000.00 20

SQL> Select substr(ename,1,3)ename from emp;

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

SQL> Select instr(ename,'A',1,2),ename from emp;

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

12. SIGN(The number to test for its sign ( - or + if ))


SQL> Select sign(-1000) from dual;

SIGN(-1000)
-----------
-1

SQL> Select sign(1000) from dual;

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

SQL> Select ceil(9.99) from dual;

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.)

SQL> SELECT FLOOR(17.36) from dual;

FLOOR(17.36)
------------
17
SQL> SELECT FLOOR(17.99) from dual;

FLOOR(17.99)
------------
17

SQL> SELECT FLOOR(-17.36) from dual;

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.)

SQL> Select trunc(9.1) from dual;

TRUNC(9.1)
----------
9

SQL> Select trunc(9.99) from dual;

TRUNC(9.99)
-----------
9

SQL> Select trunc(-9.99) from dual;

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.)

SQL> Select round(9.45) from dual;

ROUND(9.45)
-----------
9

SQL> Select round(9.51) from dual;

ROUND(9.51)
-----------
10

17.MOD(The MOD function finds the remainder of value1 divided by value2.)


Note: The MOD function is often used to determine if a value is odd or even.

SQL> Select mod(11,4) from dual;

MOD(11,4)
---------
3

SQL> Select mod(25,5) from dual;

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.

Types of Group Functions:


1. Sum
2. Min
3. Max
4. Count
5. Avg

1.Sum
Select sum(sal) from emp;

Select sum(sal),deptno from emp


Group by deptno

2.Min
Select min(sal) from emp;

SQL> SELECT MIN(HIREDATE) FROM EMP;

Select min(sal),job from emp;


Group by job

3.Max
Select max(sal) from emp;

SQL> SELECT MAX(HIREDATE) FROM EMP;

Select max(sal),deptno from emp;


Group by deptno

4.Count
Select count(sal), from emp;

Select count(sal) from emp;


Group by deptno
5.Avg
Select avg(sal) from emp;

Select avg(sal),deptno from emp;


Group by deptno

_________________________________________________________________________
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);

DEPTNO COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)


--------- --------- --------- --------- --------- ---------------------------------------------
10 3 8750 2916.6667 5000 1300
30 6 9400 1566.6667 2850 950
20 5 10875 2175 3000 800

Summary information according to job wise


SQL> SELECT JOB, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL)
2 FROM EMP
3 GROUP BY JOB
4 ORDER BY 2;

JOB COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)


--------- --------- --------- --------- --------- -------------------------------------------------
PRESIDENT 1 5000 5000 5000 5000
ANALYST 2 6000 3000 3000 3000
MANAGER 3 8275 2758.3333 2975 2450
SALESMAN 4 5600 1400 1600 1250
CLERK 4 4150 1037.5 1300 800

Summary information according to year wise


SQL> SELECT
2 TO_CHAR(HIREDATE,'RRRR'), COUNT(*), SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL)
3 FROM EMP
4 GROUP BY TO_CHAR(HIREDATE,'RRRR')
5 ORDER BY 1;
TO_C COUNT(*) SUM(SAL) MAX(SAL) MIN(SAL) AVG(SAL)
---- --------- --------- --------- --------- ---------
1980 1 800 800 800 800
1981 10 22825 5000 950 2282.5
1987 2 4100 3000 1100 2050
2082 1 1300 1300 1300 1300

Summary information according to mon_year wise


SQL> SELECT TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR, COUNT(*), SUM(SAL)
2 FROM EMP
3 GROUP BY TO_CHAR(HIREDATE,'MON-RRRR')
4 ORDER BY 1;

MON_YEAR COUNT(*) SUM(SAL)


-------- --------- ---------
APR-1981 1 2975
APR-1987 1 3000
DEC-1980 1 800
DEC-1981 2 3950
FEB-1981 2 2850
JAN-2082 1 1300
JUN-1981 1 2450
MAY-1981 1 2850
MAY-1987 1 1100
NOV-1981 1 5000
SEP-1981 2 2750
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 36 of 89
Nesting Group Functions
Group functions can be nested to a depth of two. The example displays the maximum average salary.
SQL> SELECT MAX(AVG(SAL))
2 FROM EMP
3 GROUP BY DEPTNO;

MAX(AVG(SAL))
-------------
2916.6667

SQL> SELECT MAX(SUM(SAL))


2 FROM EMP
3 GROUP BY DEPTNO;

MAX(SUM(SAL))
-------------
10875

SQL> SELECT SUM(MAX(SAL)) FROM EMP


2 GROUP BY DEPTNO;

SUM(MAX(SAL))
-------------
10850

HAVING Clause

Excluding Group Results: The HAVING Clause


Restricting Group Results
In the same way that you use the WHERE clause to restrict the rows that you select, you use the
HAVING clause to restrict groups. To find the summation of salary of each department, but show only
the departments that have a summation of salary more than 9,000, you need to do the following:
1. Find the summation of salary for each department by grouping by department number.
2. Restrict the groups to those departments with a sum of salary greater than 9,000.

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL)


2 FROM EMP
3 HAVING SUM(SAL)>9000
4 GROUP BY DEPTNO;

DEPTNO COUNT(*) SUM(SAL)


--------- --------- ---------
30 6 9400
20 5 10875

The HAVING Clause


You use the HAVING clause to specify which groups are to be displayed, and thus, you further restrict
the groups on the basis of aggregate information.
In the syntax:
group_conditionrestricts the groups of rows returned to those groups for which
the specified condition is true The Oracle server performs the following steps when you use the
HAVING clause:
1. Rows are grouped.
2. The group function is applied to the group.
3. The groups that match the criteria in the HAVING clause are displayed.

_________________________________________________________________________
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:

SQL> SELECT DEPTNO, MAX(SAL)


2 FROM EMP
3 GROUP BY DEPTNO
4 HAVING MAX(SAL)>=3000;

DEPTNO MAX(SAL)
--------- ---------
20 3000
10 5000

SQL> SELECT DEPTNO


2 FROM EMP
3 GROUP BY DEPTNO
4 HAVING MAX(SAL)>=3000;

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

3. Next day 4. Last day

5. Round 6. Trunc

1. Months_between

Select months_between(sysdate,hiredate) from emp;

Select Round(months_between(sysdate,hiredate)) from emp;

2. Add_months

Select add_months(sysdate,3) from dual;

Select add_months(sysdate,-3) from dual;

3. Next day

Select next_day(sysdate,’friday’) from dual;

4.Last day

Select last_day(sysdate) from dual;

5. Round

Select round(sysdate) from dual;

6. Trunc

Select trunc(sysdate) from dual;

Oracle Date Format


Oracle database stores dates in an internal numeric format, representing the century, year, month,
day, hours, minutes, and seconds.
The default display and input format for any date is DD-MON-RR. Valid Oracle dates are between
January 1, 4712 B.C. and December 31, 9999 A.D.

This data is stored internally as follows:


CENTURY YEAR MONTH DAY HOUR MINUTE SECOND
19 94 06 07 5 10 43

Centuries and the Year 2000


The Oracle server is year 2000 compliant. When a record with a date column is inserted into a table,
the century information is picked up from the SYSDATE function. However, when the date column is
displayed on the screen, the century component is not displayed by default. The DATE data type
always stores year information as a four-digit number internally: two digits for the century and two
digits for the year. For example, the Oracle database stores the year as 1996 or 2001, and not just as
96 or 01.

_________________________________________________________________________
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.

• MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and


date2. The result can be positive or negative. If date1 is later than date2, the result is positive; if
date1 is earlier than date2, the result is negative. The non integer part of the result represents a
portion of the month.

• 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;

TOT_MONTHS TOT_YEARS TOT_WEEKS TOT_DAYS TOT_HOURS


---------- --------- --------- --------- ---------
732 61 2928 21960 527040

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;

AFTER_1_M AFTER_6_M AFTER_1_Y AFTER_3_Y BEFORE_3_ BEFORE_3_


--------- --------- --------- --------- --------- ------------------------------------------------------
14-SEP-08 14-FEB-09 14-AUG-09 14-AUG-11 14-MAY-08 14-AUG-05

_________________________________________________________________________
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;

FIRST_THU FIRST_FRI FIRST_SAT FIRST_SUN


--------- --------- --------- -------------------------------------------
21-AUG-47 15-AUG-47 16-AUG-47 17-AUG-47

How to find last day of the month

SQL> SELECT
2 LAST_DAY('14-AUG-1947'),
3 LAST_DAY('14-FEB-1947'),
4 LAST_DAY('14-FEB-2008')
5 FROM DUAL;

LAST_DAY( LAST_DAY( LAST_DAY(


--------- --------- ---------------------------------------
31-AUG-47 28-FEB-47 29-FEB-08

Find out duration of each employee

SQL> SELECT EMPNO, ENAME, SYSDATE, HIREDATE,


2 MONTHS_BETWEEN(SYSDATE,HIREDATE) IN_MONTHS,
3 MONTHS_BETWEEN(SYSDATE,HIREDATE)/12 IN_YEARS,
4 MONTHS_BETWEEN(SYSDATE,HIREDATE)*30 IN_DAYS
5 FROM EMP;

EMPNOENAME SYSDATE HIREDATE IN_MONTHS IN_YEARS IN_DAYS


--------- ---------- --------- --------- --------- --------- ---------------------------------------------
7369 SMITH 24-JUL-08 17-DEC-80 331.25276 27.604397 9937.5828
7499 ALLEN 24-JUL-08 20-FEB-81 329.15598 27.429665 9874.6795
7521 WARD 24-JUL-08 22-FEB-81 329.09147 27.424289 9872.7441
7566 JONES 24-JUL-08 02-APR-81 327.73663 27.311386 9832.0989
7654 MARTIN 24-JUL-08 28-SEP-81 321.89792 26.824827 9656.9376
7698 BLAKE 24-JUL-08 01-MAY-81 326.76889 27.230741 9803.0666
7782 CLARK 24-JUL-08 09-JUN-81 325.51082 27.125902 9765.3247
7788 SCOTT 24-JUL-08 19-APR-87 255.18824 21.265687 7655.6473
7839 KING 24-JUL-08 17-NOV-81 320.25276 26.68773 9607.5828
7844 TURNER 24-JUL-08 08-SEP-81 322.54308 26.87859 9676.2924
7876 ADAMS 24-JUL-08 23-MAY-87 254.05921 21.171601 7621.7763
7900 JAMES 24-JUL-08 03-DEC-81 319.70437 26.642031 9591.1311
7902 FORD 24-JUL-08 03-DEC-81 319.70437 26.642031 9591.1311
7934 MILLER 24-JUL-08 23-JAN-82 318.05921 26.504934 9541.7763

_________________________________________________________________________
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;

EMPNO ENAME HIREDATE FIRST_SUN LAST_DAY AFTER_2_M


--------- ---------- --------- --------- --------- -------------------------------------------------
7369 SMITH 17-DEC-80 21-DEC-80 31-DEC-80 17-FEB-81
7499 ALLEN 20-FEB-81 22-FEB-81 28-FEB-81 20-APR-81
7521 WARD 22-FEB-81 01-MAR-81 28-FEB-81 22-APR-81
7566 JONES 02-APR-81 05-APR-81 30-APR-81 02-JUN-81
7654 MARTIN 28-SEP-81 04-OCT-81 30-SEP-81 28-NOV-81
7698 BLAKE 01-MAY-81 03-MAY-81 31-MAY-81 01-JUL-81
7782 CLARK 09-JUN-81 14-JUN-81 30-JUN-81 09-AUG-81
7788 SCOTT 19-APR-87 26-APR-87 30-APR-87 19-JUN-87
7839 KING 17-NOV-81 22-NOV-81 30-NOV-81 17-JAN-82
7844 TURNER 08-SEP-81 13-SEP-81 30-SEP-81 08-NOV-81
7876 ADAMS 23-MAY-87 24-MAY-87 31-MAY-87 23-JUL-87
7900 JAMES 03-DEC-81 06-DEC-81 31-DEC-81 03-FEB-82
7902 FORD 03-DEC-81 06-DEC-81 31-DEC-81 03-FEB-82
7934 MILLER 23-JAN-82 24-JAN-82 31-JAN-82 23-MAR-82

ROUND ( ) & TRUNC ( ) functions with date


The ROUND and TRUNC functions can be used for number and date values. When used with dates,
these functions round or truncate to the specified format model. Therefore, you can round dates to the
nearest year or month.

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;

SYSDATE-3 ROUND(SYS TRUNC(SYS


--------- --------- ---------------------------------
24-JUN-08 01-JUL-08 01-JUN-08
SQL> SELECT
2 SYSDATE,
3 NEXT_DAY(SYSDATE,'SUNDAY') COMMING_SUNDAY,
4 ROUND(SYSDATE,'DAY') COMMING_SUNDAY,
5 TRUNC(SYSDATE,'DAY') LAST_SUNDAY
6 FROM DUAL;
SYSDATE COMMING_S COMMING_S LAST_SUND
--------- --------- --------- ------------------------------------------
24-JUL-08 27-JUL-08 27-JUL-08 20-JUL-08
Suppose date is 24-JUL-2008 and time is 13:55
SQL> SELECT SYSDATE, ROUND(SYSDATE), TRUNC(SYSDATE) FROM DUAL;
SYSDATE ROUND(SYS TRUNC(SYS
--------- --------- --------------------------------------
24-JUL-08 25-JUL-08 24-JUL-08
Note: Oracle also store time with date. When comparing date column without time portion, it is
recommended to use trunc() function with that column. Because trunc ( ) eliminate time portion.
Remember TRUNC (DD) remove time portion and TRUNC(DD) is default.
SQL> SELECT * FROM EMP WHERE TRUNC(HIREDATE)='17-DEC-1980';
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 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.

Select decode (job , ‘SALESMAN’,’Booker’) from emp;


Select empno,ename,sal,decode (job , ‘SALESMAN’,’Booker’) from emp;
Select lower(decode, ‘SALESMAN’,’Booker’,job),sal+500 from emp Where job = ‘SALESMAN’;
SQL> Select JOB,decode(job , 'SALESMAN','Booker') from emp;

JOB DECODE(JOB,'SALESMAN','BOOKER'
--------- ------------------------------
CLERK
SALESMAN Booker
SALESMAN Booker
MANAGER
SALESMAN Booker
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN Booker
CLERK
CLERK

SQL> Select empno,ename,sal,decode (job , 'SALESMAN','Booker') from emp;

EMPNO ENAME SAL DECODE(JOB,'SALESMAN','BOOKER'


----- ---------- --------- ------------------------------
7369 SMITH 800.00
7499 ALLEN 1600.00 Booker
7521 WARD 1250.00 Booker
7566 JONES 2975.00
7654 MARTIN 1250.00 Booker
7698 BLAKE 2850.00
7782 CLARK 2450.00
7788 SCOTT 3000.00
7839 KING 5000.00
7844 TURNER 1500.00 Booker
7876 ADAMS 1100.00

SQL> Select ename,decode(JOB,'SALESMAN','Booker',job) from emp Where job = 'SALESMAN';

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;

GREATEST & LEAST


GREATEST The SQL GREATEST function returns the greatest value in a list of expressions.

SQL> Select greatest (100,1000) from dual;


GREATEST(100,1000)
------------------
1000
LEAST The SQL LEAST function returns the smallest value in a list of expressions.

SQL> Select least (100,1000) from dual;


LEAST(100,1000)
---------------
100

_________________________________________________________________________
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

SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH24:MI:SS') FROM DUAL;


24-JUL-08 14:29:37

SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS AM') FROM DUAL;


24-JUL-08 02:29:41 PM

SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS') FROM DUAL;


24-JUL-08 02:30:03

SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS') FROM DUAL;


02:31:40

SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS AM') FROM DUAL;


02:31:55 PM

SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM DUAL;


14:32:05

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/YY HH12:MI:SS AM') FROM DUAL;


24/07/08 02:38:33 PM

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RR HH12:MI:SS AM') FROM DUAL;


24/07/08 02:38:44 PM

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RRRR HH12:MI:SS AM') FROM DUAL;


24/07/2008 02:38:49 PM
Adding 3 Days

SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'),


2 TO_CHAR(SYSDATE+3,'DD-MON-RR HH24:MI:SS')
3 FROM DUAL;
24-JUL-08 15:16:18 27-JUL-08 15:16:18
Adding 3 Hours

SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'),


2 TO_CHAR(SYSDATE+3/24,'DD-MON-RR HH24:MI:SS')
3 FROM DUAL;
24-JUL-08 15:16:44 24-JUL-08 18:16:44

SQL> SELECT TO_CHAR(SYSDATE,'DAY, MONTH DD RRRR') FROM DUAL;


THURSDAY , JULY 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Month DD RRRR') FROM DUAL;


Thursday , July 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Mon DD RRRR') FROM DUAL;


Thursday , Jul 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Dy, Mon DD RRRR') FROM DUAL;


Thu, Jul 24 2008

SQL> SELECT TO_CHAR(SYSDATE,'DAY Day DY Dy') from dual;


THURSDAY Thursday THU Thu

SQL> SELECT TO_CHAR(SYSDATE,'DD DDTH DDSP DDSPTH DdthDdSPDdSPTH') FROM DUAL;


24 24TH TWENTY-FOUR TWENTY-FOURTH 24th Twenty-Four Twenty-Fourth
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 48 of 89
SQL> SELECT TO_CHAR(SYSDATE,'MM MmTHMmSPMmSPTH MON Mon MONTH Month') FROM
DUAL;
07 07th Seven Seventh JUL Jul JULY July

SQL> SELECT TO_CHAR(SYSDATE,'YY RR YYYY RRRR YEAR, Year') FROM DUAL;


08 08 2008 2008 TWO THOUSAND EIGHT, Two Thousand Eight

SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'Day, Month dd, rrrr') HIREDATE


FROM EMP;

ENAME HIREDATE HIREDATE


---------- --------- -----------------------------
SMITH 17-DEC-80 Wednesday, December 17, 1980
ALLEN 20-FEB-81 Friday , February 20, 1981
WARD 22-FEB-81 Sunday , February 22, 1981
JONES 02-APR-81 Thursday , April 02, 1981
MARTIN 28-SEP-81 Monday , September 28, 1981
BLAKE 01-MAY-81 Friday , May 01, 1981
CLARK 09-JUN-81 Tuesday , June 09, 1981
SCOTT 19-APR-87 Sunday , April 19, 1987
KING 17-NOV-81 Tuesday , November 17, 1981
TURNER 08-SEP-81 Tuesday , September 08, 1981
ADAMS 23-MAY-87 Saturday , May 23, 1987
JAMES 03-DEC-81 Thursday , December 03, 1981
FORD 03-DEC-81 Thursday , December 03, 1981
MILLER 23-JAN-82 Saturday , January 23, 1982

SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'fmDay, Month dd, rrrr') HIREDATE


FROM EMP;

ENAME HIREDATE HIREDATE


---------- --------- -----------------------------
SMITH 17-DEC-80 Wednesday, December 17, 1980
ALLEN 20-FEB-81 Friday, February 20, 1981
WARD 22-FEB-81 Sunday, February 22, 1981
JONES 02-APR-81 Thursday, April 2, 1981
MARTIN 28-SEP-81 Monday, September 28, 1981
BLAKE 01-MAY-81 Friday, May 1, 1981
CLARK 09-JUN-81 Tuesday, June 9, 1981
SCOTT 19-APR-87 Sunday, April 19, 1987
KING 17-NOV-81 Tuesday, November 17, 1981
TURNER 08-SEP-81 Tuesday, September 8, 1981
ADAMS 23-MAY-87 Saturday, May 23, 1987
JAMES 03-DEC-81 Thursday, December 3, 1981
FORD 03-DEC-81 Thursday, December 3, 1981
MILLER 23-JAN-82 Saturday, January 23, 1982

SQL> SELECT TO_CHAR(SYSDATE,'DdTH "of" Month RRRR') FROM DUAL;


24th of July 2008

_________________________________________________________________________
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

SQL> SELECT EMPNO, ENAME,


_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 50 of 89
2 HIREDATE,
3 TO_CHAR(HIREDATE,'DD DDSP') "DATE",
4 TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR,
5 TO_CHAR(HIREDATE,'RRRR') YEAR,
6 TO_CHAR(SAL,'99,999.99') SALARY
7 FROM EMP;

EMPNO ENAME HIREDATE DATE MON_YEAR YEAR SALARY


--------- ---------- --------- -------------------- -------- ---- ----------
7369 SMITH 17-DEC-80 17 SEVENTEEN DEC-1980 1980 800.00
7499 ALLEN 20-FEB-81 20 TWENTY FEB-1981 1981 1,600.00
7521 WARD 22-FEB-81 22 TWENTY-TWO FEB-1981 1981 1,250.00
7566 JONES 02-APR-81 02 TWO APR-1981 1981 2,975.00
7654 MARTIN 28-SEP-81 28 TWENTY-EIGHT SEP-1981 1981 1,250.00
7698 BLAKE 01-MAY-81 01 ONE MAY-1981 1981 2,850.00
7782 CLARK 09-JUN-81 09 NINE JUN-1981 1981 2,450.00
7788 SCOTT 19-APR-87 19 NINETEEN APR-1987 1987 3,000.00
7839 KING 17-NOV-81 17 SEVENTEEN NOV-1981 1981 5,000.00
7844 TURNER 08-SEP-81 08 EIGHT SEP-1981 1981 1,500.00
7876 ADAMS 23-MAY-87 23 TWENTY-THREE MAY-1987 1987 1,100.00
7900 JAMES 03-DEC-81 03 THREE DEC-1981 1981 950.00
7902 FORD 03-DEC-81 03 THREE DEC-1981 1981 3,000.00
7934 MILLER 23-JAN-82 23 TWENTY-THREE JAN-1982 1982 1,300.00
14 rows selected.

SQL> SELECT ENAME, HIREDATE,


2 TO_CHAR(HIREDATE,'Day') HIRE_DAY,
3 NEXT_DAY(HIREDATE,'SUNDAY') SUNDAY,
4 TO_CHAR(NEXT_DAY(HIREDATE,'SUNDAY'),'DD') SUNDAY,
5 TO_CHAR(LAST_DAY(HIREDATE),'Day') LAST_DAY,
6 TO_CHAR(ADD_MONTHS(HIREDATE,1),'Day') AFTER_2_MONTHS,
7 TO_CHAR(SAL,'09,999.99') SALARY
8 FROM EMP;

ENAME HIREDATE HIRE_DAY SUNDAY SU LAST_DAY AFTER_2_M SALARY


---------- --------- --------- --------- -- --------- --------- ----------
SMITH 17-DEC-80 Wednesday 21-DEC-80 21 Wednesday Saturday 00,800.00
ALLEN 20-FEB-81 Friday 22-FEB-81 22 Saturday Friday 01,600.00
WARD 22-FEB-81 Sunday 01-MAR-81 01 Saturday Sunday 01,250.00
JONES 02-APR-81 Thursday 05-APR-81 05 Thursday Saturday 02,975.00
MARTIN 28-SEP-81 Monday 04-OCT-81 04 Wednesday Wednesday 01,250.00
BLAKE 01-MAY-81 Friday 03-MAY-81 03 Sunday Monday 02,850.00
CLARK 09-JUN-81 Tuesday 14-JUN-81 14 Tuesday Thursday 02,450.00
SCOTT 19-APR-87 Sunday 26-APR-87 26 Thursday Tuesday 03,000.00
KING 17-NOV-81 Tuesday 22-NOV-81 22 Monday Thursday 05,000.00
TURNER 08-SEP-81 Tuesday 13-SEP-81 13 Wednesday Thursday 01,500.00
ADAMS 23-MAY-87 Saturday 24-MAY-87 24 Sunday Tuesday 01,100.00
JAMES 03-DEC-81 Thursday 06-DEC-81 06 Thursday Sunday 00,950.00
FORD 03-DEC-81 Thursday 06-DEC-81 06 Thursday Sunday 03,000.00
MILLER 23-JAN-82 Saturday 24-JAN-82 24 Sunday Tuesday 01,300.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

2. Non equal join

3. Outer join

4. Self Join

Equal join

Select e.empnoempno, e.enameename, e.salsal, e.deptnodeptno, d.dnamedname


From emp e, dept d
Where e.deptno = d.deptno;

EMPNO ENAME SAL DEPTNO DNAME


----- ---------- ---------- ---------- -------------
7782 CLARK 2450 10 ACCOUNTING
7839 KING 5000 10 ACCOUNTING
7934 MILLER 1300 10 ACCOUNTING
7566 JONES 2975 20 RESEARCH
7902 FORD 3000 20 RESEARCH
7876 ADAMS 1100 20 RESEARCH
7369 SMITH 800 20 RESEARCH
7788 SCOTT 3000 20 RESEARCH
7521 WARD 1250 30 SALES
7844 TURNER 1500 30 SALES
7499 ALLEN 1600 30 SALES
7900 JAMES 950 30 SALES
7698 BLAKE 2850 30 SALES
7654 MARTIN 1250 30 SALES

14 rows selected.

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 54 of 89
Non equal join

Select e.empnoempno, e.enameename, e.salsal, g.grade grade


From emp e, salgrade g
Where e.sal between g.losal andg.hisal;

EMPNO ENAME SAL GRADE


------ ---------- ---------- ----------
7369 SMITH 800 1
7900 JAMES 950 1
7876 ADAMS 1100 1
7521 WARD 1250 2
7654 MARTIN 1250 2
7934 MILLER 1300 2
7844 TURNER 1500 3
7499 ALLEN 1600 3
7782 CLARK 2450 4
7698 BLAKE 2850 4
7566 JONES 2975 4
7788 SCOTT 3000 4
7902 FORD 3000 4
7839 KING 5000 5
14 rows selected.

Outer join

Select e.empnoempno, e.enameename, e.deptnodeptno, d.dnamedname


From emp e, dept d
Where e.deptno (+)=d.deptno
EMPNO ENAME DEPTNO DNAME
---------- ---------- ---------- -------------
7782 CLARK 10 ACCOUNTING
7839 KING 10 ACCOUNTING
7934 MILLER 10 ACCOUNTING
7566 JONES 20 RESEARCH
7902 FORD 20 RESEARCH
7876 ADAMS 20 RESEARCH
7369 SMITH 20 RESEARCH
7788 SCOTT 20 RESEARCH
7521 WARD 30 SALES
7844 TURNER 30 SALES
7499 ALLEN 30 SALES
7900 JAMES 30 SALES
7698 BLAKE 30 SALES
7654 MARTIN 30 SALES
OPERATIONS

15 rows selected.

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 55 of 89
Self Join

Select e.empnoempno, e.enameename, m.empnoempno, m.enameename


From emp e, emp m
Where e.mgr = m.empno;

EMPNO ENAME EMPNO ENAME


---------- ---------- ---------- ----------
7902 FORD 7566 JONES
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7499 ALLEN 7698 BLAKE
7521 WARD 7698 BLAKE
7900 JAMES 7698 BLAKE
7654 MARTIN 7698 BLAKE
7934 MILLER 7782 CLARK
7876 ADAMS 7788 SCOTT
7698 BLAKE 7839 KING
7566 JONES 7839 KING
7782 CLARK 7839 KING
7369 SMITH 7902 FORD

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

Insert a record in EMP table by using the following query:


SQL> INSERT INTO EMP
2 (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
3 VALUES
4 (1,'ASLAM','CLERK',7566,SYSDATE,1200,NULL,NULL);
1 row created.
SQL> COMMIT;
Commit complete.

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.
The above select statement retrieves 15 rows. Employee ASLAM does not belong to any
department, because there is a NULL value in DEPTNO column of ASLAM’s record.
SQL> SELECT * FROM DEPT;
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;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- --------------------------------------------
7566 JONES MANAGER 2975 20 RESEARCH DALLAS
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
7902 FORD ANALYST 3000 20 RESEARCH DALLAS
6 rows selected.

SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC


2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND DNAME='SALES';
OR
SQL> SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
2 FROM EMP E, DEPT D
3 WHERE E.DEPTNO=D.DEPTNO
4 AND E.DEPTNO=30;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC


--------- ---------- --------- --------- --------- -------------- -------------------------------------
7499 ALLEN SALESMAN 1600 30 SALES CHICAGO
7521 WARD SALESMAN 1250 30 SALES CHICAGO
7654 MARTIN SALESMAN 1250 30 SALES CHICAGO
7698 BLAKE MANAGER 2850 30 SALES CHICAGO
7844 TURNER SALESMAN 1500 30 SALES CHICAGO
7900 JAMES CLERK 950 30 SALES CHICAGO
6 rows selected.

Is there any difference in the following two queries?

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC


FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND SAL>2000;
SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
FROM EMP E, DEPT D WHERE SAL>2000 AND E.DEPTNO=D.DEPTNO;

Cartesian / Cross Products (rows of one table multiply with rows of another table)

• A Cartesian product is formed when:


– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all rows in the second table
• To avoid a Cartesian product, always include a valid join condition in a WHERE clause.
SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME FROM EMP E, DEPT D
Non-Equijoins
A non-equijoin is a join condition containing something other than an equality operator.
The relationship between the EMP table and the SALGRADE table has an example of a nonequijoin.
A relationship between the two tables is that the SAL column in the EMPL table must
be between the values in the LOSAL and HISAL columns of the SALGRADE table. The
relationship is obtained using an operator other than equals (=).
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 59 of 89
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
14 rows selected.

SQL> SELECT * FROM SALGRADE;


GRADE LOSAL HISAL
--------- --------- ----------------------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999

SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, G.GRADE


2 FROM EMP E, SALGRADE G
3 WHERE E.SAL BETWEEN G.LOSAL AND G.HISAL;
EMPNO ENAME JOB SAL GRADE
--------- ---------- --------- --------- --------------------------------
7369 SMITH CLERK 800 1
7900 JAMES CLERK 950 1
7876 ADAMS CLERK 1100 1
7521 WARD SALESMAN 1250 2
7654 MARTIN SALESMAN 1250 2
7934 MILLER CLERK 1300 2
7844 TURNER SALESMAN 1500 3
7499 ALLEN SALESMAN 1600 3
7782 CLARK MANAGER 2450 4
7698 BLAKE MANAGER 2850 4
7566 JONES MANAGER 2975 4
7788 SCOTT ANALYST 3000 4
7902 FORD ANALYST 3000 4
7839 KING PRESIDENT 5000 5
Non-Equijoins (continued)
The example creates a non-equijoin to evaluate an employee’s salary grade. The salary must be
betweenany pair of the low and high salary ranges.
It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
• None of the rows in the job grade table contain grades that overlap. That is, the salary
value for an employee can lie only between the low salary and high salary values of one of
the rows in the salary grade table.
• All of the employees’ salaries lie within the limits provided by the salgrade table. That is, no
employee earns less than the lowest value contained in the LOSAL column or more than the
highest value contained in the HISAL column.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 60 of 89
Note: Other conditions, such as <= and >= can be used, but BETWEEN is the simplest.
Remember to specify the low value first and the high value last when using BETWEEN.
Table aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.
More examples of Non-Equijoins
SQL> SELECT * FROM STD_MARKS;
RNO CID PER
---------- ---------- ----------
1 1 75.32
2 1 61.16
3 1 48.95
4 1 89.91
SQL> SELECT * FROM STD_GRADE;
GR MIN_PER MAX_PER
-- ---------- ----------
A1 90 100
A 80 89.99
B 70 79.99
C 60 69.99
D 50 59.99
F 0 49.99
6 rows selected.
SQL> SELECT RNO, PER, GRADE
2 FROM STD_MARKS, STD_GRADE
3 WHERE PER BETWEEN MIN_PER AND MAX_PER
4 ORDER BY 1;
RNO PER GR
---------- ---------- --
1 75.32 B
2 61.16 C
3 48.95 F
4 89.91 A
SQL>
Outer Joins
Returning Records with No Direct Match with Outer Joins
If a row does not satisfy a join condition, the row will not appear in the query result. For
example, in the equijoin condition of EMP and DEPT tables, employee ASLAM does not appear
because there is no department number recorded for his in the EMP table. Instead of seeing 15
employees in the result set, you see 14 records.
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.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 61 of 89
SQL> SELECT * FROM DEPT;
DEPTNO DNAME LOC
--------- -------------- ------------------------------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
No Employee is working in DEPTNO 40

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.

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.

Why we use Outer Joins?


We use outer join when mismatched values to be displayed. or
Using Outer Joins to Return Records with No Direct Match
The missing rows can be returned if an outer join operator is used in the join condition. The
operator is a plus sign enclosed in parentheses (+), and it is placed on the “side” of the join
that is deficient in information. This operator has the effect of creating one or more null rows,
to which one or more rows from the nondeficient table can be joined.
In the syntax:
table1.column = is the condition that joins (or relates) the tables together.
table2.column (+) is the outer join symbol, which can be placed on either side of the
WHERE clause condition, but not on both sides.
(Place the outer join symbol following the name of the column in
the table without the matching rows.)

_________________________________________________________________________
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);

EMPNO ENAME SAL


---------- ---------- --------------------------
7369 SMITH 800

SQL> Select empno,ename,deptno from emp


2 Wheredeptno = (select deptno from emp
3 Whereename ='SMITH');

EMPNO ENAME DEPTNO


---------- ---------- -------------------------
7369 SMITH 20
7566 JONES 20
7788 SCOTT 20
7876 ADAMS 20
7902 D 20

Multiple-row subqueries

SQL> Select deptno,empno,ename,sal from emp


2 Where (deptno,sal)in
3 (Select deptno,max(sal) from emp
4 Group by deptno);
DEPTNO EMPNO ENAME SAL
---------- ---------- ---------- --
30 7698 BLAKE 2850
20 7902 FORD 3000
20 7788 SCOTT 3000
10 7839 KING 5000
SQL> Select job,empno,ename,sal from emp
2 Where (job,sal)in
3 (Select job,max(sal) from emp
4 Group by job);

JOB EMPNO ENAME SAL


--------- ---------- ---------- ----------------------------------
CLERK 7934 MILLER 1300
SALESMAN 7499 ALLEN 1600
PRESIDENT 7839 KING 5000
MANAGER 7566 JONES 2975
ANALYST 7902 FORD 3000
ANALYST 7788 SCOTT 3000

_________________________________________________________________________
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 DEPTNO FROM EMP WHERE ENAME='SMITH';


DEPTNO
---------
20
And now use department number 20 for retrieving all employees of that department.

SQL> SELECT * FROM EMP WHERE DEPTNO=20;


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
But you can achieve the above task by using the following subquery in where clause.

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.

Display all employees who are earning more than JONES.

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

Display all employees who are working in SALES department


Department names are not saved in EMP table. Now you have to use DEPT table in subquery
because DEPT table contains department names.
SQL> SELECT * FROM DEPT;
DEPTNO DNAME LOC
--------- -------------- ---------------------------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
In the following query you used two tables DEPT in inner query and EMP in outer query.
SQL> SELECT * FROM EMP
WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30

Using Group Functions in a Subquery


You can display data from a main query by using a group function in a subquery to return a
single row. The subquery is in parentheses and is placed after the comparison condition.

Display employee who is (are) earning maximum salary


First find maximum salary by using the following query:
SQL> SELECT MAX(SAL) FROM EMP;
MAX(SAL)
---------
5000
Then put 5000 in WHERE clause for matching criteria:
SQL> SELECT * FROM EMP WHERE SAL=5000;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----------------------------------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10
But you can use the following subquery:
SQL> SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ----------------------------------
7839 KING PRESIDENT 17-NOV-81 5000 10
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 68 of 89
Guidelines for Using Subqueries
• A subquery must be enclosed in parentheses.
• Place the subquery on the right side of the comparison condition for readability.
• The ORDER BY clause in the subquery is not needed unless you are performing Top-N
analysis.
• Two classes of comparison conditions are used in subqueries: single-row operators and
multiple-row operators.
• Use single-row operators with single-row subqueries and use multiple-row operators
with multiple-row subqueries.

Write queries of the following:


1. Subordinates list of BLAKE (manager)
2. Employees working with ALLEN in the same department
3. Manager's record of Mr. SMITH
4. Employees who are working in NEW YORK
5. Employees who are senior than SCOTT
6. Employee with least salary in the company
7. Complete information of most experienced employee in the company
8. Display all employees who are working on the same job as SMITH'S job and are earning
more than ADAMS
What is the meaning of following queries?
SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'RRRR') =
(SELECT TO_CHAR(HIREDATE,'RRRR') FROM EMP WHERE ENAME='JONES');
SELECT * FROM EMP
WHERE LENGTH(ENAME)=(SELECT LENGTH(ENAME) FROM EMP WHERE EMPNO=7521);
SELECT * FROM EMP
WHERE SUBSTR(ENAME,2,1)=(SELECT SUBSTR(ENAME,2,1) FROM EMP WHERE EMPNO=7902);

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.

SQL> SELECT DEPTNO, MIN(SAL) FROM EMP


2 GROUP BY DEPTNO
3 HAVING MIN(SAL)>(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30);
DEPTNO MIN(SAL)
--------- ----------------------
10 1300

_________________________________________________________________________
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.

SQL> Select deptno from emp


2 Intersect
3 Selectdeptno from dept;

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.

SQL> Select deptno from dept


2 Minus
3 Selectdeptno from emp;

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.

SQL> Select sal, sum(sal)over (order by hiredate) from emp;

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

SQL> Select hiredate,sal,sum(sal)over(order by hiredate) from emp;

HIREDATE SAL SUM(SAL)OVER(ORDERBYHIREDATE)


----------- --------- -----------------------------
12/17/1980 800.00 800
2/20/1981 1600.00 2400
2/22/1981 1250.00 3650
4/2/1981 2975.00 6625
5/1/1981 2850.00 9475
6/9/1981 2450.00 11925
9/8/1981 1500.00 13425
9/28/1981 1250.00 14675
11/17/1981 5000.00 19675
12/3/1981 950.00 23625
12/3/1981 3000.00 23625
1/23/1982 1300.00 24925
4/19/1987 3000.00 27925
5/23/1987 1100.00 29025

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.

The CREATE VIEW statement

SQL> CREATE VIEW EMP_V1


2 AS SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, DEPTNO FROM EMP;
View created.

Display structure of a view

SQL> DESC EMP_V1

Name Null? Type


------------------------------- -------- ----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
DEPTNO NUMBER(2)

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 74 of 89
Retrieving data using view

SQL> SELECT * FROM EMP_V1;


EMPNO ENAME JOB MGR HIREDATE DEPTNO
--------- ---------- --------- --------- --------- ------------------------------
7369 SMITH CLERK 7902 17-DEC-80 20
7499 ALLEN SALESMAN 7698 20-FEB-81 30
7521 WARD SALESMAN 7698 22-FEB-81 30
7566 JONES MANAGER 7839 02-APR-81 20
7654 MARTIN SALESMAN 7698 28-SEP-81 30
7698 BLAKE MANAGER 7839 01-MAY-81 30
7782 CLARK MANAGER 7839 09-JUN-81 10
7788 SCOTT ANALYST 7566 19-APR-87 20
7839 KING PRESIDENT 17-NOV-81 10
7844 TURNER SALESMAN 7698 08-SEP-81 30
7876 ADAMS CLERK 7788 23-MAY-87 20
7900 JAMES CLERK 7698 03-DEC-81 30
7902 FORD ANALYST 7566 03-DEC-81 20
7934 MILLER CLERK 7782 23-JAN-82 10
1 SCOTT CLERK 2 06-AUG-08 55
2 ASLAM MANAGER 7839 28-JUL-08 55
3 SALEEM ASST IT 2 10-JAN-07 55
17 rows selected.

Inserting using view


SQL> INSERT INTO EMP_V1
2 (EMPNO, ENAME, JOB, DEPTNO)
3 VALUES
4 (4, 'ZIA','CLERK',10);
1 row created.

You inserted into EMP table through EMP_V1


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
4 ZIA CLERK 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
1 SCOTT CLERK 2 06-AUG-08 1000 55
2 ASLAM MANAGER 7839 28-JUL-08 2975 55
3 SALEEM ASST IT 2 10-JAN-07 2300 55
18 rows selected.

_________________________________________________________________________
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

Creating a Complex View


Create a complex view that contains display values from two tables.
SQL> CREATE OR REPLACE VIEW EMP_DEPT AS
2 SELECT E.EMPNO, E.ENAME, E.JOB, E.DEPTNO, D.DNAME, D.LOC
3 FROM EMP E, DEPT D
4 WHERE E.DEPTNO=D.DEPTNO;
View created.
_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 76 of 89
SQL> SELECT * FROM EMP_DEPT;

EMPNO ENAME JOB DEPTNO DNAME LOC


--------- ---------- --------- --------- -------------- ----------------------------------------------
7369 SMITH CLERK 20 RESEARCH DALLAS
7499 ALLEN SALESMAN 30 SALES CHICAGO
7521 WARD SALESMAN 30 SALES CHICAGO
7566 JONES MANAGER 20 RESEARCH DALLAS
7654 MARTIN SALESMAN 30 SALES CHICAGO
7698 BLAKE MANAGER 30 SALES CHICAGO
7782 CLARK MANAGER 10 ACCOUNTING NEW YORK
7788 SCOTT ANALYST 20 RESEARCH DALLAS
7839 KING PRESIDENT 10 ACCOUNTING NEW YORK
7844 TURNER SALESMAN 30 SALES CHICAGO
7876 ADAMS CLERK 20 RESEARCH DALLAS
7900 JAMES CLERK 30 SALES CHICAGO
7902 FORD ANALYST 20 RESEARCH DALLAS
4 ZIA CLERK 10 ACCOUNTING NEW YORK
7934 MILLER CLERK 10 ACCOUNTING NEW YORK
1 SCOTT CLERK 55 IT KARACHI
2 ASLAM MANAGER 55 IT KARACHI
3 SALEEM ASST IT 55 IT KARACHI
18 rows selected.
Create a complex view that contains group functions to display summary information.
SQL> CREATE OR REPLACE VIEW DEPT_SUMMARY AS
2 SELECT DEPTNO, COUNT(*) CNT, SUM(SAL) SUM_SAL, AVG(SAL) AVG_SAL
3 FROM EMP
4 GROUP BY DEPTNO;
View created.

SQL> SELECT * FROM DEPT_SUMMARY;


DEPTNO CNT SUM_SAL AVG_SAL
--------- --------- --------- ---------
30 6 9400 1566.6667
20 5 10875 2175
55 3 6275 2091.6667
10 4 8750 2916.6667
SQL> CREATE OR REPLACE VIEW AVAILABLE_JOBS AS
2 SELECT DISTINCT JOB FROM EMP;
View created.

SQL> SELECT * FROM AVAILABLE_JOBS;


JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
ASST IT
Removing a View
You use the DROP VIEW statement to remove a view. The statement removes the view
definition from the database. Dropping views has no effect on the tables on which the view was
based. Views or other applications based on deleted views become invalid.

SQL> DROP VIEW EMP_V1;


View dropped.

_________________________________________________________________________
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.

SQL> SELECT EMP_ID, EMP_NAME, DESG


2 FROM (SELECT EMPNO EMP_ID, ENAME EMP_NAME, JOB DESG
3 FROM EMP WHERE DEPTNO=10) A;

EMP_ID EMP_NAME DESG


--------- ---------- -----------------
7782 CLARK MANAGER
7839 KING PRESIDENT
4 ZIA CLERK
7934 MILLER CLERK

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:

SQL> SELECT ROWNUM SNO, ENAME, SAL, DEPTNO


2 FROM ( SELECT ENAME, SAL, DEPTNO
3 FROM EMP WHERE SAL IS NOT NULL
4 ORDER BY SAL DESC )
5 WHERE ROWNUM <= 3;

SNO ENAME SAL DEPTNO


--------- ---------- --------- ---------
1 KING 5000 10
2 SCOTT 3000 20
3 FORD 3000 20
NOTE: Use USER_VIEWS data dictionary to display created view information

_________________________________________________________________________
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.

Create a table to store student information.


Create table student (
std_id number(5),
Std_name varchar2 (10),
Std_f_name varchar2 (10),
Std_address varchar2 (30),
Std_gender varchar2 (8),
Std_fees number (10))

How to verify table creation?


By a data dictionary view USER_TABLES or (TABS)

SQL> SELECT TABLE_NAME FROM USER_TABLES;


TABLE_NAME
------------------------------
DEPT
EMP
BONUS
SALGRADE
STUDENT

The ALTER TABLE 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.

Alter table student


Add (roll no number (10));

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.

Alter table student


Modify roll_nonumber(10);

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.

Alter table student


Drop column Roll_no;

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;

Insert data in a Table 1

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.

Insert into student


(std_id, Std_name, Std_f_name, Std_address, Std_gender, Std_fees)
Values(1,’ABC’,’XYZ’,’House # ABC 123’,’Male’,’2000’);

Insert data in a Table 2

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.

Insert into student


Values(1,’ABC’,’XYZ’,’House # ABC 123’,’Male’,’2000’);

Insert data in a Table 3

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

Insert into student


(‘&std_id’, ‘&Std_name’, ‘&Std_f_name’, ‘&Std_address’, ‘&Std_gender’, ‘&Std_fees’)

_________________________________________________________________________
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’;

Delete data from a Table


You can remove existing rows by using the DELETE statement.
Specific rows are deleted if you specify the WHERE clause.
Delete student where std_id = 6

Delete from student where std_id = 6

All rows in the table are deleted if you omit the WHERE clause.
Delete student

Delete from student

The COMMIT statement


For applying explicit commit the COMMIT statement is used.
For save data
COMMIT;
Commit complete.

The ROLLBACK statement


You can undo or revert data which is changed by DML statements. To revert/undo you have to use
rollback, rollback may be applied either implicitly or explicitly.
For applying explicit rollback the ROLLBACK statement is used.
ROLLBACK;
Rollback complete.

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.

TRUNCATE TABLE STUDENT;


Table truncated.

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 82 of 89
Create Copy Table

Create a table EMP_COPY with the same structure of EMP table.


Create table emp_copy as select * from emp;

Create Synonyms

Simplify access to objects by creating a synonym


(another name for an object). With synonyms, you can:
• Ease referring to a table owned by another user
• Shorten lengthy object names

CREATE SYNONYM EMP_SYN FOR EMP;


Synonym created.

CREATE PUBLIC SYNONYM EMP_SYN FOR EMP;


Synonym created.

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.

Confirming system privileges granted to the user

SQL> SELECT * FROM USER_SYS_PRIVS;


USERNAME PRIVILEGE ADM
------------------------------ ---------------------------------------- ---
ATIF CREATE VIEW NO
ATIF CREATE TABLE NO
ATIF CREATE SESSION NO
ATIF CREATE SEQUENCE NO

_________________________________________________________________________
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)

SQL> COL USERNAME FORMAT A10


SQL> COL ACCOUNT_STATUS FORMAT A10
SQL> COL DEFAULT_TABLESPACE FORMAT A10
SQL> COL TEMPORARY_TABLESPACE FORMAT A10
SQL> SELECT USERNAME, ACCOUNT_STATUS, DEFAULT_TABLESPACE,
2 TEMPORARY_TABLESPACE, CREATED FROM USER_USERS;

USERNAME ACCOUNT_ST DEFAULT_TA TEMPORARY_ CREATED


---------- ---------- ---------- ---------- ------------------------------------------------------------
ATIF OPEN USERS TEMP 07-AUG-08
SQL> CREATE TABLE EMPLOYEE
2(
3 EMPNO NUMBER(4) PRIMARY KEY,
4 ENAME VARCHAR2(20)
5 );
CREATE TABLE EMPLOYEE
*
ERROR at line 1:
ORA-01950: no privileges on tablespace 'USERS'

SQL> DESC USER_TS_QUOTAS


Name Null? Type
----------------------------------------- -------- --------------------------
TABLESPACE_NAME NOT NULL VARCHAR2(30)
BYTES NUMBER
MAX_BYTES NUMBER
BLOCKS NUMBER
MAX_BLOCKS NUMBER
DROPPED VARCHAR2(3)

SQL> SELECT * FROM USER_TS_QUOTAS;


no rows selected
Assigning quota to ATIF on USERS tablespace

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> ALTER USER ATIF QUOTA 5M ON USERS;


User altered.

SQL> CONN ATIF/ASATTAR


Connected.

_________________________________________________________________________
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.

SQL> SELECT * FROM USER_TS_QUOTAS;


TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DR
------------------------------ ---------- ---------- ---------- ---------- --
USERS 131072 5242880 16 640 NO
SQL> CREATE TABLE STUDENT
2(
3 GRNO NUMBER(4) PRIMARY KEY,
4 NAME VARCHAR2(20) NOT NULL,
5 FNAME VARCHAR2(20)
6 );
Table created.

SQL> SELECT * FROM USER_TS_QUOTAS;


TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO
------------------------------ ---------- ---------- ---------- ---------- ---
USERS 262144 5242880 32 640 NO
SQL> SELECT * FROM USER_SYS_PRIVS;
USERNAME PRIVILEGE ADM
------------------------------ ---------------------------------------- ---
ATIF CREATE VIEW NO
ATIF CREATE TABLE NO
ATIF CREATE SESSION NO
ATIF CREATE SEQUENCE NO

The REVOKE statement

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.

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> REVOKE CREATE TABLE FROM ATIF;


Revoke succeeded.
SQL> CONN ATIF/ASATTAR
Connected.

SQL> SELECT * FROM USER_SYS_PRIVS;


USERNAME PRIVILEGE ADM
------------------------------ ---------------------------------------- ---
ATIF CREATE VIEW NO
ATIF CREATE SESSION NO
ATIF CREATE SEQUENCE NO

_________________________________________________________________________
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

Granting object privileges


You are trying to access EMP table, but you don’t have rights/privileges to access the EMP
table.

SQL> SHOW USER


USER is "ATIF"

SQL> SELECT COUNT(*) FROM SCOTT.EMP;


SELECT COUNT(*) FROM SCOTT.EMP
*
ERROR at line 1:
ORA-00942: table or view does not exist

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.

SQL> GRANT SELECT


2 ON EMP
3 TO ATIF;
Grant succeeded.

SQL> GRANT SELECT, INSERT, UPDATE, DELETE


2 ON EMP
3 TO ATIF;
Grant succeeded.

How to view granted object privileges

SQL> COL GRANTEE FORMAT A10


SQL> COL OWNER FORMAT A10
SQL> COL TABLE_NAME FORMAT A10
SQL> COL GRANTOR FORMAT A10
SQL> COL PRIVILEGE FORMAT A10

SQL> SELECT * FROM USER_TAB_PRIVS_MADE;


GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE GRA HIE
---------- ---------- ---------- ---------- ---------- --- ---
ATIF SCOTT EMP SCOTT INSERT NO NO
ATIF SCOTT EMP SCOTT UPDATE NO NO
ATIF SCOTT EMP SCOTT DELETE NO NO
ATIF SCOTT EMP SCOTT SELECT NO NO
SQL> CONN ATIF/ASATTAR
Connected.

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 88 of 89
SQL> SELECT COUNT(*) FROM SCOTT.EMP;
COUNT(*)
----------
18

SQL> CONN SYS/ORACLE AS SYSDBA


Connected.

SQL> CREATE USER MR IDENTIFIED BY ASATTAR;


User created.

SQL> GRANT CREATE SESSION, CREATE TABLE TO MR;


Grant succeeded.

SQL> ALTER USER MR QUOTA 5M ON USERS;


User altered.

SQL> CONN MR/ASATTAR


Connected.

SQL> SELECT * FROM SCOTT.EMP;


SELECT * FROM SCOTT.EMP
*
ERROR at line 1:
ORA-00942: table or view does not exist
ATIF is not authorized to grant privileges on SCOTT’s EMP table
SQL> CONN ATIF/ASATTAR
Connected.
SQL> GRANT SELECT ON SCOTT.EMP TO MR;
GRANT SELECT ON SCOTT.EMP TO MR
*
ERROR at line 1:
ORA-01031: insufficient privileges
Grant privilege with grant option
(ATIF is now authorized to grant privileges on SCOTT’s EMP table)
SQL> CONN SCOTT/TIGER
Connected.
SQL> GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO ATIF WITH GRANT OPTION;
Grant succeeded.
SQL> CONN ATIF/ASATTAR
Connected.
SQL> GRANT SELECT ON SCOTT.EMP TO MR;
Grant succeeded.

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

SQL> CONN SCOTT/TIGER


Connected.

SQL> REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM ATIF;


Revoke succeeded.

_________________________________________________________________________
Prepared by Abdul Sattar
abdulsattar100@hotmail.com
0300 – 8204124 Page 89 of 89

Potrebbero piacerti anche