SQL Study Material-Other Stream
SQL Study Material-Other Stream
Oracle
SQL Study Material
For Non-Oracle Streams
Date: 27/04/2012.
Personal Oracle is one of the flavors of Oracle. In this Oracle server and client both
run on the same machine. This is unlike other flavors where Oracle Server runs on
Server and Front-end runs on Client.
It is possible to develop an application using Personal Oracle and deploy it in a
Client / Server environment. Personal Oracle can support up to 15 database
connections.
Oracle SQL Workbook - Page No : 6
Oracle 6.0
Oracle 7.0
Oracle 7.1
Oracle 7.2
Oracle 7.3
Oracle 8.0
Oracle 8i
Oracle9i
Oracle10g
Oracle 11g
Oracle 12i
1990
1995
1996
1997
1998
1999
2000
2001
2004
2009
2009 Aug
Object based
ORDBMS
Internet based Application
Application server
Grid Computing
482 new features
1500 new features
Clients of Oracle can use two different environments for executing SQL
statements. SQL*plus and iSQL*plus.
iSQL*plus is (Available only from Oracle 9i) a web based client tool.
An Environment
Oracle proprietary
Keywords can be abbreviated
Runs on a browser
Centrally loaded, does not have to be implemented on each machine
SELECT
INSERT
UPDATE
DELETE
MERGE
CREATE
ALTER
DROP
RENAME
TRUNCATE
COMMIT
ROLLBACK
SAVEPOINT
GRANT
REVOKE
Transaction control
Each column value and constant in a SQL statement has a data type, which is
associated with a specific storage format, constraints, and a valid range of values.
When you create a table, you must specify a data type for each of its columns.
Oracle provides the following built-in data types.
Character Data types
o CHAR Data type
o VARCHAR2 and VARCHAR Data types
o NCHAR and NVARCHAR2 Data types
LONG Data type
NUMBER Data type
DATE Data type
LOB Data types
o BLOB data type
o CLOB and NCLOB data types
o BFILE Data type
RAW and LONG RAW Data types
Character Datatypes
The character data types store character (alphanumeric) data in strings, with byte
values corresponding to the character.
CHAR datatype
Fixed length character data of length size in bytes. (Default size is 1 and maximum
size is 2000). Padded on right with blanks to full length of size.
VARCHAR2 (size)
Variable length characters strings having a maximum size of 4000 bytes (Default
size is 1). Truncates leftover blank spaces.
NVARCHAR2(size)
Variable length characters strings having a maximum size of 4000 bytes (Default
size is 1) Or characters, depending on the choice of national character set.
Truncates leftover blank spaces.
Oracle SQL Workbook - Page No : 13
It is a building block for data retrieval in SQL. This statement helps to retrieve data
from one or multiple tables and produce output in a well formatted manner.
Syntax : SELECT <COLUMNS> FROM <TABLE>;
Your First Query
INPUT:
SQL> SELECT * FROM emp;
OUTPUT:
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 09-DEC-82
3000
20
7839 KING
PRESIDENT
17-NOV-81
5000
10
7844 TURNER
SALESMAN
7698 08-SEP-81
1500
0
30
7876 ADAMS
CLERK
7788 12-JAN-83
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
ANALYSIS:
Notice that columns 6 and 8 in the output statement are right justified and that
columns 2 and 3 are left justified. This format follows the alignment convention in
which numeric data types are right justified and character data types are left
justified.
The asterisk (*) in select * tells the database to return all the columns associated
with the given table described in the FROM clause. The database determines the order
in which to return the columns.
A full table scan is used whenever there is no where clause on a query.
OUTPUT:
EMPNO
---------7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934
ENAME
SAL JOB
COMM
---------- ---------- --------- ---------SMITH
800 CLERK
ALLEN
1600 SALESMAN
300
WARD
1250 SALESMAN
500
JONES
2975 MANAGER
MARTIN
1250 SALESMAN
1400
BLAKE
2850 MANAGER
CLARK
2450 MANAGER
SCOTT
3000 ANALYST
KING
5000 PRESIDENT
TURNER
1500 SALESMAN
0
ADAMS
1100 CLERK
JAMES
950 CLERK
FORD
3000 ANALYST
MILLER
1300 CLERK
14 rows selected.
ANALYSIS:
Observe that the column sequence specified in the select command is not the original
sequence followed during table creation. Also as per sql a column may be selected
any number of times in the same select command.
OUTPUT:
EMPNO ENAME
JOB
MGR HIREDATE
SAL
COMM
DEPTNO
------ ---------- --------- ---------- --------- ---------- ---------- ---------7839 KING
PRESIDENT
17-NOV-81
5000
10
ANALYSIS:
This simple example shows how you can place a condition on the data that you want to
retrieve.
OUTPUT:
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 09-DEC-82
3000
20
7844 TURNER
SALESMAN
7698 08-SEP-81
1500
0
30
7876 ADAMS
CLERK
7788 12-JAN-83
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
ANALYSIS:
Displays all the employees other than KING.
To understand how you could get an Unknown, you need to know a little about
the concept of NULL. In database terms NULL is the absence of data in a field. It
does not mean a column has a zero or a blank in it. A zero or a blank is a value.
NULL means nothing is in that field. If you make a comparison like Field = 9
and the only value for Field is NULL, the comparison will come back
Unknown. Because Unknown is an uncomfortable condition, most flavors of
SQL change Unknown to FALSE and provide a special operator, IS NULL, to
test for a NULL condition.
Here's an example of NULL: Suppose an entry in the PRICE table does not
contain a value for WHOLESALE. The results of a query might look like this:
SELECT * FROM emp WHERE comm IS NULL;
SELECT * FROM emp WHERE comm IS NOT NULL;
ANALYSIS:
Displays all the employees whose names begins with letter A
INPUT:
SQL> SELECT * FROM emp WHERE ename NOT LIKE A%;
ANALYSIS:
Displays all the employees whose names not beginning with letter A
INPUT:
SQL> SELECT * FROM emp WHERE ename LIKE %A%;
ANALYSIS:
Displays all the employees whose names contains letter A (Any number of As)
INPUT:
SQL> SELECT * FROM emp WHERE ename LIKE %A%A%;
ANALYSIS:
Displays all the names whose name contains letter A more than one time
ANALYSIS:
Displays all the employees who joined in the month of December.
INPUT:
SQL> SELECT * FROM emp WHERE hiredate LIKE %81;
ANALYSIS:
Displays all the employees who joined in the year 81.
INPUT:
SQL> SELECT * FROM emp WHERE sal LIKE 4%;
ANALYSIS:
Displays all the employees
conversion takes place).
whose
salary
begins
with
number
4.
(Implicit
data
Underscore (_)
The underscore is the single-character wildcard with in the LIKE operator.
INPUT:
SQL> SELECT empno,ename FROM emp WHERE ename LIKE _A%;
OUTPUT:
EMPNO
---------7521
7654
7900
ENAME
---------WARD
MARTIN
JAMES
ANALYSIS:
Displays all the employees whose second letter is A
INPUT:
SQL> SELECT * FROM emp WHERE ename LIKE __A%;
OUTPUT:
ENAME
---------BLAKE
CLARK
ADAMS
ANALYSIS:
Displays all the employees whose third letter is A ( Two underscores followed by A)
OUTPUT:
ENAME
---------AVINASH_K
ANAND_VARDAN
ADAMS_P
ANALYSIS:
Displays all the employees with underscore (_). \ Escape character. Underscore is
used to identify a position in the string. To treat _ as a character we have to use
Escape (\) character,
OUTPUT:
ENAME||JOB
------------------SMITHCLERK
ALLENSALESMAN
WARDSALESMAN
JONESMANAGER
MARTINSALESMAN
BLAKEMANAGER
CLARKMANAGER
SCOTTANALYST
KINGPRESIDENT
TURNERSALESMAN
ADAMSCLERK
JAMESCLERK
FORDANALYST
MILLERCLERK
ANALYSIS:
Combines both name and designation as a single string.
INPUT:
SQL>SELECT ename || , || job FROM emp;
OUTPUT:
ENAME||','||JOB
---------------------SMITH , CLERK
ALLEN , SALESMAN
WARD , SALESMAN
JONES , MANAGER
MARTIN , SALESMAN
BLAKE , MANAGER
CLARK , MANAGER
SCOTT , ANALYST
KING , PRESIDENT
TURNER , SALESMAN
ADAMS , CLERK
JAMES , CLERK
FORD , ANALYST
MILLER , CLERK
ANALYSIS:
Combines both name and designation as a single string separated by,
OUTPUT:
ENAME
---------ALLEN
WARD
MARTIN
BLAKE
CLARK
JAMES
ANALYSIS:
Displays all the employees whose names contains letter A exactly one time.
SELECT * FROM emp WHERE sal >= 3000 AND sal <= 4000;
SELECT * FROM emp WHERE sal BETWEEN 3000 AND 4000;
SELECT * FROM emp WHERE sal NOT BETWEEN 3000 AND 4000;
job
FROM
emp
WHERE
job='CLERK'
OR
job=MANAGER
OR
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
TURNER
ADAMS
JAMES
MILLER
JOB
--------CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER
SALESMAN
CLERK
CLERK
CLERK
ANALYSIS:
Display employees with designations manager, clerk, and salesman,
The above statement takes more time to parse it, which reduces the efficiency.
Oracle SQL Workbook - Page No : 25
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
TURNER
ADAMS
JAMES
MILLER
JOB
--------CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER
SALESMAN
CLERK
CLERK
CLERK
ANALYSIS:
Display employees with designations manager, clerk, and salesman,
INPUT:
SQL> SELECT ename, job FROM emp WHERE job NOT IN('CLERK','SALESMAN','MANAGER');
OUTPUT:
ENAME
---------SCOTT
KING
FORD
JOB
--------ANALYST
PRESIDENT
ANALYST
ANALYSIS:
Display designations other than manager, clerk, and salesman
INPUT:
SQL> SELECT ename,hiredate FROM emp WHERE hiredate IN (01-MAY-1981,09-DEC-1982);
OUTPUT:
ENAME
---------BLAKE
SCOTT
HIREDATE
--------01-MAY-81
09-DEC-82
ANALYSIS:
Display employees who joined on two different dates.
OUTPUT:
JOB
--------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
ANALYSIS:
Distinct operator displays unique designations.
displays the information in ascending order.
Distinct
operator
by
default
ORDER BY CLAUSE
Display the information in a particular order (Ascending or descending order)
Syntax: SELECT <COLUMNS> FROM <TABLE> WHERE <CONDITION> ORDER BY
<COLUMN(S)>;
INPUT:
SQL> SELECT ename FROM emp ORDER BY ename;
OUTPUT:
ENAME
---------ADAMS
ALLEN
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN
MILLER
SCOTT
SMITH
TURNER
WARD
ANALYSIS:
Display employees in ascending order of names.
OUTPUT:
JOB
--------ANALYST
ANALYST
CLERK
CLERK
CLERK
CLERK
MANAGER
MANAGER
MANAGER
PRESIDENT
SALESMAN
SALESMAN
SALESMAN
SALESMAN
ENAME
SAL
---------- ---------FORD
3000
SCOTT
3000
ADAMS
1100
JAMES
950
MILLER
1300
SMITH
800
BLAKE
2850
CLARK
2450
JONES
2975
KING
5000
ALLEN
1600
MARTIN
1250
TURNER
1500
WARD
1250
ANALYSIS:
Display employees in ascending order
information in ascending order of names.
of
jobs.
With
each
job
it
places
the
With
each
job
it
places
the
each
job
it
places
the
INPUT:
SQL> SELECT * FROM emp ORDER BY job, ename desc;
ANALYSIS:
Display employees in ascending order by
information in descending order of names.
jobs.
INPUT:
SQL> SELECT * FROM emp ORDER BY job desc, ename DESC;
ANALYSIS:
Display employees in descending order by
information in descending order of names.
jobs.
With
OUTPUT:
Display employees in ascending order of jobs other than clerks.
ANALYSIS:
When we are executing the query, it is divided into two different parts.
1) SELECT * FROM emp WHERE job != CLERK
2) ORDER BY job;
First part is going to execute first, and selects all the employees
designation is other than clerk and places them in a temporary table.
whose
ANALYSIS:
It places the information in the order of third column in the table.
INPUT:
SQL> SELECT deptno, job, sal, empno FROM emp ORDER BY 3;
ANALYSIS:
The information is displayed in the order of the 3rd column of the selected and not
the 3rd column of the table
INPUT:
SQL> SELECT deptno, job, sal, empno, comm FROM emp ORDER BY comm;
ANALYSIS:
Since the comm column contain nulls, you observe that the rows containing null in
the comm column are displayed at the bottom of the output.
INPUT:
SQL> SELECT empno, ename, sal, sal*12 as ann_sal FROM emp ORDER BY ann_sal;
ANALYSIS:
Data can be ordered by using alias name.
The function COUNT returns the number of rows that satisfy the condition in the
WHERE clause.
Say you wanted to know how many employees are there.
INPUT:
SQL> SELECT COUNT(*) FROM emp;
OUTPUT:
COUNT(*)
-------14
ANALYSIS:
It counts the number of rows in that table.
OUTPUT:
NUM_OF_EMP
------------------14
INPUT:
SQL> SELECT COUNT(comm) FROM emp;
OUTPUT:
COUNT(comm)
-------4
ANALYSIS:
It counts only those when there is a value in comm Column
Note: Count (*) faster than count(comm) Count(*) count the row when a row present in
the table where as Count(comm) counts the row only when there is a value in the
column.
OUTPUT:
COUNT(*)
------4
ANALYSIS:
It counts only managers
INPUT:
SQL> SELECT COUNT(DISTINCT job) FROM emp;
OUTPUT:
COUNT (*)
------4
ANALYSIS:
It counts only distinct jobs
SUM does just that. It returns the sum of all values in a column.
INPUT:
SQL> SELECT SUM(sal) TOTAL_SALARY FROM emp;
OUTPUT:
TOTAL_SALARY
------------29025
ANALYSIS:
Find the total salary drawn by all the employees
INPUT:
SQL> SELECT SUM(sal) TOTAL_SALARY, SUM(comm) TOTAL_COMM FROM emp;
OUTPUT:
TOTAL_SALARY
------------29025
TOTAL_COMM
---------2200
ANALYSIS:
The totals of sal column and the comm column are calculated and displayed
INPUT:
SQL> SELECT SUM(sal) TOTAL_SALARY,SUM(comm) TOTAL_COMM FROM emp WHERE
job=SALESMAN;
OUTPUT:
TOTAL_SALARY
------------5600
TOTAL_COMM
---------2200
OUTPUT:
AVERAGE_SALARY
--------------2073.21429
ANALYSIS:
Find the average salary of all the employees
INPUT:
SQL> SELECT AVG(comm) AVERAGE_COMM FROM emp;
OUTPUT:
AVERAGE_COMM
-----------550
ANALYSIS:
Functions ignores null rows
OUTPUT:
MAX(SAL)
-------5000
ANALYSIS:
Takes the value from one different rows from one particular column
INPUT:
SQL> SELECT MAX(ename) FROM emp;
OUTPUT:
MAX(ENAME)
-------WARD
ANALYSIS:
Max of name is identified based on ASCII value when a char column is given
INPUT:
SQL> SELECT MAX (hiredate) FROM emp;
OUTPUT:
MAX(HIREDATE)
------------12-JAN-83
ANALYSIS:
Can find the maximum date in the given column
Finds the minimum value in the given column of values. This example shows the
use of min function with a numeric column.
INPUT:
SQL> SELECT MIN(sal) FROM emp;
OUTPUT:
MIN(SAL)
-------800
OUTPUT:
MIN (ENAME)
-------ADAMS
The following example shows the use of all aggregate functions together.
INPUT:
SQL> SELECT SUM(sal),AVG(sal),MIN(sal),MAX(sal),COUNT(*) FROM emp;
OUTPUT:
SUM(SAL)
AVG(SAL)
--------- --------29025 2073.21429
MIN(SAL)
-------800
MAX(SAL)
-------5000
COUNT(*)
-------14
ANALYSIS:
All the aggregate functions can be used together in a single SQL statement
Arithmetic Functions
Character Functions
Date functions
Miscellaneous Functions
The ABS function returns the absolute value of the number you point to. For
example:
INPUT:
SQL> SELECT ABS(-10) ABSOLUTE_VALUE FROM dual;
OUTPUT:
ABSOLUTE_VALUE
--------------10
ANALYSIS:
ABS changes all the negative numbers to positive and leaves positive numbers alone.
Dual is a system table or dummy table from where we can display system information
(i.e. system date and username etc) or we can make our own calculations.
CEIL returns the smallest integer greater than or equal to its argument. FLOOR
does just the reverse, returning the largest integer equal to or less than its
argument.
INPUT:
SQL> SELECT CEIL(12.145) FROM dual;
OUTPUT:
CEIL(12.145)
-----------13
INPUT:
SQL> SELECT CEIL(12.000) FROM dual;
OUTPUT:
CEIL(12.000)
----------12
ANALYSIS:
Minimum we require one decimal place, to get the next higher integer number
INPUT:
SQL> SELECT FLOOR(12.678) FROM dual;
OUTPUT:
FLOOR(12.678)
----------------12
INPUT:
SQL> SELECT FLOOR(12.000) FROM dual;
OUTPUT:
FLOOR(12.000)
----------------12
OUTPUT:
MOD(5,2)
---------1
INPUT:
SQL> SELECT MOD(2,5) FROM dual;
OUTPUT:
MOD(2,5)
---------2
ANALYSIS:
When numerator value less than denominator, it returns numerator value as remainder.
To raise one number to the power of another, use POWER. In this function the
first argument is raised to the power of the second:
INPUT:
SQL> SELECT POWER(5,3) FROM dual;
OUTPUT:
POWER(5,3)
---------125
CHR returns the character equivalent of the number it uses as an argument. The
character it returns depends on the character set of the database. For this
example the database is set to ASCII.
INPUT:
SQL> SELECT CHR(65) FROM dual;
OUTPUT:
CHR(65)
------A
As you might expect, LOWER changes all the characters to lowercase; UPPER
does just the changes all the characters to uppercase.
INPUT:
SQL>SELECT ename,UPPER(ename) UPPER_CASE,LOWER(ename) LOWER_CASE FROM emp;
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
UPPER_CASE
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
LOWER_CASE
---------smith
allen
ward
jones
martin
blake
clark
scott
king
turner
adams
james
ford
miller
LPAD and RPAD take a minimum of two and a maximum of three arguments.
The first argument is the character string to be operated on. The second is the
number of characters to pad it with, and the optional third argument is the
character to pad it with. The third argument defaults to a blank, or it can be a
single character or a character string.
The following statement adds five pad characters, assuming that the field
LASTNAME is defined as a 15-character field:
INPUT:
SQL> SELECT LPAD(ename,15,*) FROM emp;
OUTPUT:
LPAD(ENAME,15,'
--------------**********SMITH
**********ALLEN
***********WARD
**********JONES
*********MARTIN
**********BLAKE
**********CLARK
**********SCOTT
***********KING
*********TURNER
**********ADAMS
**********JAMES
***********FORD
*********MILLER
ANALYSIS:
15 locations allocated to display ename, out of that, name is occupying some space
and in the remaining space to the left side of the name pads with *.
INPUT:
SQL> SELECT RPAD(5000,10,*) FROM dual;
OUTPUT:
RPAD(5000,10,*)
-------------------5000******
REPLACE does just that. Of its three arguments, the first is the string to be
searched. The second is the search key. The last is the optional replacement
string. If the third argument is left out or NULL, each occurrence of the search key
on the string to be searched is removed and is not replaced with anything.
Syntax: REPLACE(STRING,SEARCH_STRING,REPLACE_STRING)
INPUT:
SQL> SELECT REPLACE (RAMANA,MA, VI) FROM dual;
OUTPUT:
REPLACE (RAMANA,MA, VI)
---------------------------RAVINA
INPUT:
SQL> SELECT REPLACE(RAMANA,MA) FROM dual;
OUTPUT:
REPLACE(RAMANA,MA)
---------------------RANA
ANALYSIS:
When the replace string is missing, search string removed from the given string
INPUT:
SQL> SELECT REPLACE (RAMANA,MA, NULL) FROM dual;
OUTPUT:
REPLACE (RAMANA,MA, NULL)
-----------------------------RANA
The function TRANSLATE takes three arguments: the target string, the FROM
string, and the TO string. Elements of the target string that occur in the FROM
string are translated to the corresponding element in the TO string.
INPUT:
SQL> SELECT TRANSLATE(RAMANA,MA,CD) FROM dual;
OUTPUT:
TRANSLATE(RAMANA,MA,CD)
----------------------------RDCDND
ANALYSIS:
Notice that the function is case sensitive. When search string matches, it replaces
with corresponding replace string and if any one character is matching in the search
string, it replaces with corresponding replace character.
This three-argument function enables you to take a piece out of a target string.
The first argument is the target string. The second argument is the position of the
first character to be output. The third argument is the number of characters to
show.
Syntax: SUBSTR(STRING,STARTING_POSITION[,NO_OF_CHARACTERS])
INPUT:
SQL> SELECT SUBSTR(RAMANA,1,3) FROM dual;
OUTPUT:
SUBSTR(RAMANA,1,3)
-------------------RAM
ANALYSIS:
It takes first 3 characters from first character
INPUT:
SQL> SELECT SUBSTR(RAMANA,3,3) FROM DUAL;
OUTPUT:
SUBSTR(RAMANA,3,3)
-------------------MAN
ANALYSIS:
It takes 3 characters from third position
INPUT:
SQL> SELECT SUBSTR(RAMANA,-2,2) FROM dual;
OUTPUT:
SUBSTR(RAMANA,-2,2)
--------------------NA
ANALYSIS:
You use a negative number as the second argument, the starting point is determined
by counting backwards from the right end.
OUTPUT:
SUBSTR(RAMANA
-------------RANA
ANALYSIS:
First two characters and last two characters are combined together as a single
string
INPUT:
SQL> SELECT SUBSTR(RAMANA,3) FROM dual;
OUTPUT:
SUBSTR(RAMANA,3)
-----------------MANA
ANALYSIS:
When third argument is missing, it takes all the character from starting position
INPUT:
SQL> SELECT * FROM emp WHERE SUBSTR(hiredate,4,3) = SUBSTR(SYSDATE,4,3);
ANALYSIS:
Displays all the employees who joined in the current month SYSDATE is a single row
function, which gives the current date.
INPUT:
SQL> SELECT SUBSTR(RAMANA,1,2) || SUBSTR(RAMANA,-2,2) FROM DUAL;
OUTPUT:
SUBSTR(RAMANA,1,2)
-------------------RANA
ANALYSIS:
First two characters and Last two characters are combined together as a single
string
To find out where in a string a particular pattern occurs, use INSTR. Its first
argument is the target string. The second argument is the pattern to match. The
third and forth are numbers representing where to start looking and which match
to report. This example returns a number representing the first occurrence of O
starting with the second
INPUT:
SQL> SELECT INSTR(RAMANA,A) FROM DUAL;
OUTPUT:
INSTR(RAMANA,A)
------------------2
ANALYSIS:
Find the position of the first occurrence of letter A
INPUT:
SQL> SELECT INSTR(RAMANA,A,1,2) FROM dual;
OUTPUT:
INSTR(RAMANA,A,1,2)
----------------------4
ANALYSIS:
Find the position of the second occurrence of letter A from the beginning of the
string. Third argument represents from which position, Fourth argument represents,
which occurrence.
INPUT:
SQL> SELECT INSTR(RAMANA,a) FROM dual;
OUTPUT:
INSTR(RAMANA,a)
------------------0
ANALYSIS:
Function is case sensitive; it returns 0 (zero) when the given character is not
found.
INPUT:
SQL> SELECT INSTR(RAMANA,A,3,2) FROM dual;
OUTPUT:
INSTR(RAMANA,A,3,2)
---------------------6
ANALYSIS:
Find the position of the second occurrence of letter A from 3rd position of the
string
OUTPUT:
SAL
---------800
1600
1250
2975
1250
2850
2450
3000
5000
1500
1100
950
3000
1300
TO_CHAR(SAL)
---------------------------------------800
1600
1250
2975
1250
2850
2450
3000
5000
1500
1100
950
3000
1300
ANALYSIS:
After conversion, Converted information is left aligned. So we can say that it is a
string.
The main usage of this function is, to change the date formats and number
formats
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DD/MM/YYYY) FROM dual;
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,'DD/MM/YYYY')
-----------------------------24/03/2007
ANALYSIS:
Convert the default date format to DD/MM/YYYY format
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,'DD-MON-YY')
-----------------------------24-MAR-07
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DY-MON-YY) FROM dual;
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,'DY-MON-YY')
-----------------------------SAT-MAR-07
ANALYSIS:
DY displays the first 3 letters from the day name
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DAY MONTH YEAR) FROM dual;
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,'DAYMONTHYEAR')
-----------------------------SATURDAY MARCH TWO THOUSAND SEVEN
ANALYSIS:
DAY
MONTH
YEAR
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DDSPTH MONTH YEAR) FROM dual;
OUTPUT:
SYSDATE
TO_CHAR(SYSDATE,'DDSPTHMONTHYEAR')
--------- ------------------------------------------------------------------24-MAR-07 TWENTY-FOURTH MARCH
TWO THOUSAND SEVEN
ANALYSIS:
DD
DDSP
TH
format
OUTPUT:
HIREDATE
--------17-DEC-80
20-FEB-81
22-FEB-81
02-APR-81
28-SEP-81
01-MAY-81
09-JUN-81
09-DEC-82
17-NOV-81
08-SEP-81
12-JAN-83
03-DEC-81
03-DEC-81
23-JAN-82
TO_CHAR(HIREDATE,'DDSPTHMONTHYEAR')
------------------------------------------------------------------SEVENTEENTH DECEMBER NINETEEN EIGHTY
TWENTIETH FEBRUARY NINETEEN EIGHTY-ONE
TWENTY-SECOND FEBRUARY NINETEEN EIGHTY-ONE
SECOND APRIL
NINETEEN EIGHTY-ONE
TWENTY-EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE
FIRST MAY NINETEEN EIGHTY-ONE
NINTH JUNE NINETEEN EIGHTY-ONE
NINTH DECEMBER NINETEEN EIGHTY-TWO
SEVENTEENTH NOVEMBER NINETEEN EIGHTY-ONE
EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE
TWELFTH JANUARY
NINETEEN EIGHTY-THREE
THIRD DECEMBER NINETEEN EIGHTY-ONE
THIRD DECEMBER NINETEEN EIGHTY-ONE
TWENTY-THIRD JANUARY
NINETEEN EIGHTY-TWO
ANALYSIS:
Converts all hire dates in EMP table into Words
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,Q) FROM dual;
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,Q)
-----------------------------1
ANALYSIS:
Gives in the quarter the given date falls
INPUT:
SQL> SELECT TO_CHAR(TO_DATE(10-SEP-2005),Q) FROM dual;
OUTPUT:
TO_CHAR(TO_DATE('10-SEP-2005'),'Q')
---------------------------------------3
ANALYSIS:
To_date is data conversion function, which converts given string into date type
INPUT:
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,W) FROM dual;
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE,W)
-----------------------------4
ANALYSIS:
Gives the week number in the current month ( In which week given date falls in the
current month)
OUTPUT:
SYSDATE
--------24-MAR-07
TO_CHAR(SYSDATE)
---------------------------12
ANALYSIS:
Returns no. of weeks worked during the year.
INPUT:
SQL> SELECT TO_CHAR(SYSDATE,HH:MI:SS AM) FROM dual;
OUTPUT:
TO_CHAR(SYS
----------08:40:17 PM
ANALYSIS:
HH
MI
SS
AM
returns
returns
returns
returns
Hours
}
Minutes
} Returns time from current date
Seconds
}
AM / PM depends on Time
INPUT:
SQL> SELECT TO_CHAR(SYSDATE,HH24:MI:SS) FROM dual;
OUTPUT:
TO_CHAR(
-------20:43:12
ANALYSIS:
HH24
MI
SS
}
} Returns time from current date
}
INPUT:
SQL> SELECT TO_CHAR(12567,99,999.99) FROM dual;
OUTPUT:
TO_CHAR(12567,'99,999.99')
----------------------------12,567.00
ANALYSIS:
Converts the given number into comma format with two decimal places
OUTPUT:
TO_CHAR(12567,'L99,999.99')
----------------------------$12,567.00
ANALYSIS:
Display the local currency symbol
INPUT:
SQL> SELECT TO_CHAR(-12567,L99,999.99PR) FROM dual;
OUTPUT:
TO_CHAR(-12567,'L99,999.99PR')
----------------------------------<$12,567.00>
ANALYSIS:
PR
OUTPUT:
MATURITY_DATE
-------------------24-SEP-07
ANALYSIS:
It adds 6 months to the system date
INPUT:
SQL> SELECT hiredate, TO_CHAR(ADD_MONTHS(hiredate,33*12),DD/MM/YYYY) RETIRE_DATE
FROM emp;
OUTPUT:
HIREDATE
--------17-DEC-80
20-FEB-81
22-FEB-81
02-APR-81
28-SEP-81
01-MAY-81
09-JUN-81
09-DEC-82
17-NOV-81
08-SEP-81
12-JAN-83
03-DEC-81
03-DEC-81
23-JAN-82
RETIRE_DATE
--------------17/12/2013
20/02/2014
22/02/2014
02/04/2014
28/09/2014
01/05/2014
09/06/2014
09/12/2015
17/11/2014
08/09/2014
12/01/2016
03/12/2014
03/12/2014
23/01/2015
ANALYSIS:
Displaying the retirement date with century.
OUTPUT:
HIREDATE
--------17-DEC-80
20-FEB-81
22-FEB-81
02-APR-81
28-SEP-81
01-MAY-81
09-JUN-81
09-DEC-82
17-NOV-81
08-SEP-81
12-JAN-83
03-DEC-81
03-DEC-81
23-JAN-82
RETIRE_DATE
--------------17-DEC-13
20-FEB-14
22-FEB-14
02-APR-14
28-SEP-14
01-MAY-14
09-JUN-14
09-DEC-15
17-NOV-14
08-SEP-14
12-JAN-16
03-DEC-14
03-DEC-14
23-JAN-15
ANALYSIS:
Find the retirement date of an employee Assume, 33 years of service from date of
join is retirement date
LAST_DAY(expr1)
OUTPUT:
LAST_DAY(SYSDATE)
----------------31-JAN-11
ANALYSIS:
The last_date function automatically calculates the last of the current month on
which the function is applied and return that date.
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
EXPERIENCE
---------26.2713494
26.0966182
26.0912419
25.9783387
25.4917795
25.8976935
25.7928548
24.2928548
25.3546827
25.545543
24.2014569
25.3089838
25.3089838
25.171887
ANALYSIS:
Finds number of months between sysdate and hiredate. Result is divided with 12 to
get the experience
OUTPUT:
GREATEST
--------83
ANALYSIS:
Displays the greatest of the given set of values
NAME
RAVI
KRIS
BABU
ANU
SUB1
SUB2 SUB3 SUB4
55
22
86
45
78
55
65
12
55
22
44
77
44
55
66
88
To find the greatest and Least Mark we can use the GREATEST and LEAST
functions as follows.
INPUT:
SQL> SELECT name,sub1,sub2,sub3,sub4, GREATEST(sub1,sub2,sub3,sub4) GREATEST_MARK,
LEAST(sub1,sub2,sub3,sub4) LEAST_MARK FROM student;
OUTPUT:
ROLLNO
-----1
2
3
4
NAME
-----RAVI
KRIS
BABU
ANU
SUB1
---55
78
55
44
SUB2
---22
55
22
55
SUB3
---86
65
44
66
SUB4
---45
12
77
88
GREATEST_MARK
------------86
78
77
88
LEAST_MARK
---------22
12
22
44
USER returns the character name of the current user of the database.
INPUT:
SQL> SELECT USER FROM dual;
OUTPUT:
USER
-------SCOTT
ANALYSIS:
Displays the current
environment command
sessions
user
name
We
can
also
display
username
using
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
JOB
--------CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN
CLERK
CLERK
ANALYST
CLERK
PROMOTION
--------EXEC
S.OFFICER
S.OFFICER
VP
S.OFFICER
VP
VP
PM
PRESIDENT
S.OFFICER
EXEC
EXEC
PM
EXEC
ANALYSIS:
When JOB has a value CLERK , then display EXEC instead
When JOB has a value SALESMAN , then display S.OFFICER
When JOB has a value ANALYST , then display PM instead
When JOB has a value MANAGER , then display VP instead
OTHERWISE DISPLAY SAME JOB
of CLERK
instead of SALESMAN
of ANALYST
of MANAGER
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
JOB
SAL
NEW_SAL
--------- ---------- ---------CLERK
800
880
SALESMAN
1600
1920
SALESMAN
1250
1500
MANAGER
2975
3867.5
SALESMAN
1250
1500
MANAGER
2850
3705
MANAGER
2450
3185
ANALYST
3000
3750
PRESIDENT
5000
5000
SALESMAN
1500
1800
CLERK
1100
1210
CLERK
950
1045
ANALYST
3000
3750
CLERK
1300
1430
ANALYSIS:
When JOB has
When JOB has
When JOB has
When JOB has
OTHERWISE no
ANALYSIS:
Adding Mr. or Ms. before the name based on their Gender
As of Oracle 9i, you can use the CASE function in place of DECODE. The CASE
function uses the keywords when, then, else, and end to indicate the logic path
followed, which may make the resulting code easier to follow than an equivalent
DECODE.
INPUT:
SQL> SELECT job,
CASE job
WHEN 'MANAGER' then 'VP'
WHEN 'CLERK'
THEN 'EXEC'
WHEN 'SALESMAN' THEN 'S.OFFICER'
ELSE
job
END
FROM emp;
OUTPUT:
JOB
--------CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN
CLERK
CLERK
ANALYST
CLERK
CASEJOBWH
--------EXEC
S.OFFICER
S.OFFICER
VP
S.OFFICER
VP
VP
ANALYST
PRESIDENT
S.OFFICER
EXEC
EXEC
ANALYST
EXEC
ANALYSIS:
Works similar to that of DECODE
If the value is NULL, this function is equal to substitute. If the value is not NULL,
this function is equal to value. Substitute can be a literal number, another column,
or a computation.
NVL is not restricted to numbers, it can be used with CHAR, VARCHAR2, DATE, and
other data types, but the value and substitute must be the same data type.
INPUT:
SQL> SELECT
OUTPUT:
EMPNO
SAL
COMM
TOTAL
---------- ---------- ---------- ---------7369
800
7499
1600
300
1900
7521
1250
500
1750
7566
2975
7654
1250
1400
2650
7698
2850
7782
2450
7788
3000
7839
5000
7844
1500
0
1500
7876
1100
7900
950
7902
3000
7934
1300
ANALYSIS:
Arithmetic operation is possible only when value is there in both columns
INPUT:
SQL> SELECT empno, sal, comm, sal + NVL(comm,0) TOTAL FROM emp;
OUTPUT:
EMPNO
SAL
COMM
TOTAL
---------- ---------- ---------- ---------7369
800
800
7499
1600
300
1900
7521
1250
500
1750
7566
2975
2975
7654
1250
1400
2650
7698
2850
2850
7782
2450
2450
7788
3000
3000
7839
5000
5000
7844
1500
0
1500
7876
1100
1100
7900
950
950
7902
3000
3000
7934
1300
1300
ANALYSIS:
Using NVL, we are substituting 0 if COMM is NULL.
ASCII
CAST
OUTPUT:
JOB
COUNT(*)
--------- ---------ANALYST
2
CLERK
4
MANAGER
3
PRESIDENT
1
SALESMAN
4
ANALYSIS:
Counts number of employees under each and every job. When we are grouping on job,
initially jobs are placed in ascending order in a temporary segment. On the
temporary segment, group by clause is applied, so that on each similar job count
function applied.
INPUT:
SQL> SELECT job, SUM(sal) FROM emp GROUP BY job;
OUTPUT:
JOB
SUM(SAL)
--------- ---------ANALYST
6000
CLERK
4150
MANAGER
8275
PRESIDENT
5000
SALESMAN
5600
ANALYSIS:
With each job, it finds the total salary
OUTPUT:
SELECT job, COUNT (*) FROM emp
*
ERROR at line 1:
ORA-00937: not a single-group group function
ANALYSIS:
This result occurs because the group functions, such as SUM and COUNT, are
designated to tell you something about a group or rows, not the individual rows of
the table. This error is avoided by using JOB in the group by clause, which forces
the COUNT to count all the rows grouped within each job.
INPUT:
SQL> SELECT job,ename,COUNT(*) FROM emp GROUP BY job;
OUTPUT:
SELECT JOB,ENAME,COUNT(*) FROM EMP GROUP BY JOB
*
ERROR at line 1:
ORA-00979: not a GROUP BY expression
ANALYSIS:
In the above query, JOB is only the grouped column where as ENAME column is not a
grouped column. Whatever the columns we are grouping, the same column is allowed to
display.
INPUT:
SQL> SELECT job, MIN(sal),MAX(sal) FROM emp GROUP BY job;
OUTPUT:
JOB
MIN(SAL)
MAX(SAL)
--------- ---------- ---------ANALYST
3000
3000
CLERK
800
1300
MANAGER
2450
2975
PRESIDENT
5000
5000
SALESMAN
1250
1600
ANALYSIS:
With each job, it finds the MINIMUM AND MAXIMUM SALARY
OUTPUT:
JOB
SUM(SAL)
AVG(SAL)
MIN(SAL)
MAX(SAL)
COUNT(*)
--------- ---------- ---------- ---------- ---------- ---------ANALYST
6000
3000
3000
3000
2
CLERK
4150
1037.5
800
1300
4
MANAGER
8275 2758.33333
2450
2975
3
PRESIDENT
5000
5000
5000
5000
1
SALESMAN
5600
1400
1250
1600
4
ANALYSIS:
To display the output Designation wise, Department wise total salaries With a
matrix style report.
INPUT:
SQL>
SELECT
job,SUM(DECODE(deptno,10,sal))
DEPT10,
SUM(DECODE(deptno,20,sal))
DEPT20,
SUM(DECODE(deptno,30,sal)) DEPT30, SUM(sal) TOTAL FROM emp GROUP BY job;
OUTPUT:
JOB
DEPT10
DEPT20
DEPT30
TOTAL
--------- ---------- ---------- ---------- ---------ANALYST
6000
6000
CLERK
1300
1900
950
4150
MANAGER
2450
2975
2850
8275
PRESIDENT
5000
5000
SALESMAN
5600
5600
ANALYSIS:
When we apply group by, initially all the designations are placed in ascending order
of designations. Then group by clause groups similar designations, then DECODE
function (Single row function) applies on each and every row of that group and
checks the DEPTNO. If DEPTNO=10, it passes corresponding salary as an argument to
SUM() .
INPUT:
SQL> SELECT deptno,job,COUNT(*) FROM emp GROUP BY deptno,job;
OUTPUT:
DEPTNO
---------10
10
10
20
20
20
30
30
30
JOB
COUNT(*)
--------- ---------CLERK
1
MANAGER
1
PRESIDENT
1
CLERK
2
ANALYST
2
MANAGER
1
CLERK
1
MANAGER
1
SALESMAN
4
ANALYSIS:
Department wise, Designation wise , counts the number of employees
OUTPUT:
DEPTNO JOB
COUNT(*)
---------- --------- ---------10 CLERK
1
MANAGER
1
PRESIDENT
1
20 CLERK
ANALYST
MANAGER
2
2
1
30 CLERK
MANAGER
SALESMAN
1
1
4
ANALYSIS:
Break is Environment command , which breaks the information on repetitive column and
displays them only once.
SKIP 1 used with BREAK to leave one blank line after completion of each
Deptno.
We can use CUBE function to generate subtotals for all combinations of the values
in the group by clause.( CUBE and ROLLUP are available only from 9i)
INPUT:
SQL> SELECT deptno,job,COUNT(*) FROM emp GROUP BY CUBE(deptno,job);
OUTPUT:
DEPTNO JOB
COUNT(*)
---------- --------- ---------14
CLERK
4
ANALYST
2
MANAGER
3
SALESMAN
4
PRESIDENT
1
10
3
10 CLERK
1
10 MANAGER
1
10 PRESIDENT
1
20
5
20 CLERK
2
20 ANALYST
2
20 MANAGER
1
30
6
30 CLERK
1
30 MANAGER
1
30 SALESMAN
4
ANALYSIS:
Cube displays the out with all the permutation and combination of all the columns
given a CUBE function.
OUTPUT:
DEPTNO
---------10
10
10
10
20
20
20
20
30
30
30
30
JOB
COUNT(*)
--------- ---------CLERK
1
MANAGER
1
PRESIDENT
1
3
CLERK
2
ANALYST
2
MANAGER
1
5
CLERK
1
MANAGER
1
SALESMAN
4
6
14
ANALYSIS:
Observe the output. The count(*) column total is automatically displayed with every
change in the deptno.
OUTPUT:
JOB
SUM(SAL)
--------- ---------ANALYST
6000
CLERK
4150
MANAGER
8275
PRESIDENT
5000
SALESMAN
5600
To Display only those designations, whose total salary is more than 5000
INPUT:
SQL> SELECT job,SUM(sal) FROM emp WHERE SUM(sal) > 5000 GROUP BY job;
OUTPUT:
SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB
*
ERROR at line 1:
ORA-00934: group function is not allowed here
ANALYSIS:
Where clause doesnt allow using group function in the condition.
When we are using group function in the condition, we have to use having clause.
INPUT:
SQL> SELECT job,SUM(sal) FROM emp GROUP BY job HAVING SUM(sal) > 5000;
OUTPUT:
JOB
SUM(SAL)
--------- ---------ANALYST
6000
MANAGER
8275
SALESMAN
5600
ANALYSIS:
Displays all the designations whose total salary is more than 5000.
OUTPUT:
JOB
COUNT(*)
--------- ---------CLERK
4
MANAGER
3
SALESMAN
4
ANALYSIS:
Displays all the designations whose number where employees between 3 and 5
INPUT:
SQL> SELECT sal FROM emp GROUP BY sal HAVING COUNT(sal) > 1;
OUTPUT:
SAL
---------1250
3000
ANALYSIS:
Displays all the salaries, which are appearing more than one time in the table.
POINTS TO REMEMBER
WHERE clause can be used to check for conditions based on values of
columns and expressions but not the result of GROUP functions.
HAVING clause is specially designed to evaluate the conditions that are
based on group functions such as SUM, COUNT etc.
HAVING clause can be used only when GROUP BY clause is used.
ORDER OF EXECUTION
Here are the rules ORCALE uses to execute different clauses given in SELECT
command
INPUT:
SQL> SELECT job,SUM(sal) FROM emp WHERE job != CLERK
GROUP BY job HAVING SUM(sal) > 5000 ORDER BY job DESC;
OUTPUT:
ENAME
-----------KING
SAL
---------5000
ANALYSIS:
Right side query is called as child query and left side query is called parent
query. In nested queries, child query executes first before executing parent query.
OUTPUT:
ENAME
HIREDATE
---------- --------ADAMS
12-JAN-83
ANALYSIS:
Display the least experienced employee
INPUT:
SQL> SELECT ename,sal FROM emp WHERE sal < (SELECT MAX(sal) FROM emp);
OUTPUT:
ENAME
SAL
---------- ---------SMITH
800
ALLEN
1600
WARD
1250
JONES
2975
MARTIN
1250
BLAKE
2850
CLARK
2450
SCOTT
3000
TURNER
1500
ADAMS
1100
JAMES
950
FORD
3000
MILLER
1300
ANALYSIS:
Display all the employees whose salary is less than the maximum salary of all the
employees.
Display all the employees who are getting maximum commission in the
organization
Answer:
SQL> SELECT * FROM emp WHERE comm = (SELECT MAX(comm) FROM emp);
Display all the employees from department 30 whose salary is less than maximum
salary of department 20.
Answer:
SQL> SELECT empno, ename, sal FROM emp WHERE deptno=30
AND sal < (SELECT MAX(sal) FROM emp WHERE deptno = 20);
OUTPUT:
ENAME
---------WARD
MARTIN
SCOTT
FORD
SAL
--------1250
1250
3000
3000
ANALYSIS:
Displays all the employees who are drawing similar salaries
When child query returns more than one value, we have to use IN operator for
comparison.
OUTPUT:
EMPNO
---------7839
7788
7902
7698
ENAME
DEPTNO
SAL
---------- ---------- ---------KING
10
5000
SCOTT
20
3000
FORD
20
3000
BLAKE
30
2850
ANALYSIS:
Display all the employees who are drawing maximum salaries in each department
OUTPUT:
EMPNO
---------7369
7499
7521
7566
7654
7782
7844
7876
7900
7934
ENAME
DEPTNO
SAL
---------- ---------- ---------SMITH
20
800
ALLEN
30
1600
WARD
30
1250
JONES
20
2975
MARTIN
30
1250
CLARK
10
2450
TURNER
30
1500
ADAMS
20
1100
JAMES
30
950
MILLER
10
1300
ANALYSIS:
Find department wise maximum salaries and display the employees whose salary is less
than that value for each department
OUTPUT:
EMPNO
---------7788
7902
ENAME
SAL
---------- ---------SCOTT
3000
FORD
3000
ANALYSIS:
It selects each row from emp table from parent query and finds the distinct count
for each salary whose salary >= the salary returned by main query.
ANALYSIS:
Identify the employee who is drawing minimum salary and update with the maximum
salary of all the employees.
ANALYSIS:
Assuming that EMP1 is an existing table.
table.
Constraints are used to implement standard rules such as uniqueness in the key
filed and business rule such as AGE column should contain a value between 15
and 60 etc.
Oracle server makes sure that the constraints are not violated whenever a row is
inserted, deleted or updated. If constraint is not satisfied the operation will fail.
Constraints are normally defined at the time of creating table. But it is also
possible to define constraints after the table is created.
Constraint Guidelines
Name a constraint or the Oracle server generates a name by using the
SYS_Cn format
Create a constraint either:
o At the same time as the table is created, or
o After the table has been created.
Define a constraint at the column or table level.
View a constraint in the Data dictionary for verification
TYPES OF CONSTRAINTS
Constraints are classified into two types
Table Constraints
Column Constraints
Table Constraint
A constraint given at the table level is called as Table Constraint. It may refer to
more than one column of the table.
A typical example is PRIMARY KEY constraint that is used to define composite
primary key.
PRIMARY KEY
UNIQUE
NOT NULL
CHECK
PRIMARY KEY
It is used to uniquely identify rows in a table. There can be only one primary key in
a table. It may consist of more than one column, if so, it is called as composite
primary key. ( It maintains uniqueness in the data and null values are not
acceptable).
i.e. UNIQUE + NOT NULL = PRIMARY KEY
Automatically creates unique index to enforce uniqueness.
UNIQUE
Maintains unique and NULL values are acceptable.
Oracle automatically creates a unique index for the column.
Example : EmailID
A UNIQUE key integrity constraint requires that every value in a column or set of
columns (key) be unique- that is, no two rows of table can have duplicate values in
a specified column or set of columns. The column (or set of columns) included in
the definition of the UNIQUE key constraint is called the unique key. If the
CREATE, ALTER, DROP commands used in SQL are called the DDL commands.
DDL STATEMENTS COMMITS AUTOMATICALLY. There is no need to save explicitly.
Oracle SQL Workbook - Page No : 86
Note:
Constraint name is useful for manipulating the given constraint
When the constraint name is not given at the time of defining constraints,
system creates a constraint with the name SYS_Cn.
Constraints defined on a particular table are store in a data dictionary table
USER_CONSTRAINTS, USER_CONS_COLUMNS.
Tables defined by a user are stored in a data dictionary table USER_TABLES
USER_CONSTRAINTS
OUTPUT:
CONSTRAINT_NAME
--------------SYS_C003018
CHK_EMPL47473_GENDER
SYS_C003020
PK_EMPL47473_EMPNO
SYS_C003022
CONSTRAINTTYPE
--------------C
C
C
P
U
SEARCH_CONDITION
--------------------------------"ENAME" IS NOT NULL
UPPER (GENDER) IN ('M','F')
SALARY BETWEEN 10000 AND 70000
ANALYSIS:
Describe displays structure of the data dictionary table.
Select statement is used to view the constraints defined on the table
INPUT:
SQL> DESCRIBE USER_CONS_COLUMNS
SQL> SELECT CONSTRAINT_NAME,COLUMN_NAME
FROM USER_CONS_COLUMNS
WHERE TABLE_NAME = 'EMPL47473';
OUTPUT:
CONSTRAINT_NAME
-----------------------------CHK_EMPL47473_GENDER
PK_EMPL47473_EMPNO
SYS_C003018
SYS_C003020
SYS_C003022
COLUMN_NAME
-------------------------------GENDER
EMPNO
ENAME
SALARY
EMAIL_ID
ANALYSIS:
Describe displays structure of the data dictionary table.
Select statement is used to view the constraints defined on the column
ANALYSIS:
To remove the primary key
referring constraint name.
from
table.
Other
constraints
are
removed
only
by
INPUT:
SQL>ALTER TABLE empl47473 ADD PRIMARY KEY(empno);
ANALYSIS:
To add primary key to the table without constraint name. It creates constraint name
with SYS_Cn.
INPUT:
SQL>ALTER TABLE empl47473 ADD CONSTRAINT pk_empl47473_empno PRIMARY KEY(empno);
ANALYSIS:
To add primary key in the table with constraint name
Data manipulation means performing operations on the data in the tables of the
dataase. We perform mainly 3 types of data manipulation operations. They are
Insertion
Updation
Deletion
To insert data into specific columns of the table instead of all columns
SQL> INSERT INTO empl47473(empno,empname,salary) VALUES(101,RAVI, 5000);
OR
SQL> INSERT INTO empl47473(empno,empname,salary) VALUES(&empno,&empname,&salary);
ANALYSIS:
We cant skip primary key and NOT NULL columns
Note: Changes made on the database are recorded only in the shadow page. For
saving the information we have to use a command COMMIT,
ROLLBACK.SAVEPOINT (Called as Transactional processing statements)
SQL>COMMIT;
ANALYSIS:
Information from shadow
destroyed automatically.
page
flushed
back
to
the
table
and
shadow
page
gets
SQL> ROLLBACK;
ANALYSIS:
Shadow page destroys automatically without transferring the information back to the
table.
EMPNAME
---------KIRAN
LATHA
RADHA
G
M
F
F
EMAIL_ID
SALARY DOJ
------------------ ---------- [email protected]
5000 10-JAN-01
[email protected]
5000 15-JAN-02
[email protected]
15000 15-JAN-02
The output shows the three new records weve added . Now roll back just the last
insert:
SQL> ROLLBACK TO B;
IMPLICIT COMMIT
The actions that will force a commit to occur, even without your instructing it to,
or quit, exit (the equivalent to exit), any DDL command forces a commit.
AUTO ROLLBACK
If youve completed a series of inserts, updates or deletes, but not yet explicitly or
implicitly committed them, and you experience serious difficulties, such as a
computer failure, Oracle automatically roll back any uncommitted work. If the
machine or database goes down, it does this as cleanup work the next time the
database is brought back up.
emp;
COMMIT / ROLLBACK;
ANALYSIS
To give uniform increments to all the employees
ANALYSIS:
ADD Mr. or Ms. Before the existing name as per the SEX value
TRUNCATING A TABLE
Syntax: TRUNCATE TABLE <TABLENAME>
Note : Removes all the rows from table. Deleting specified rows is not possible.
Once the table is truncated, it automatically commits. It is a DDL statement.
DROPPING A TABLE OR REMOVING A TABLE
Syntax: DROP TABLE <TABLENAME>
Note : Table is dropped permanently. It is a DDL statement. It removes the data
along with table definitions and the table.
ADDING COMMENTS TO A TABLE.
You can add comments up to 2000 bytes about a column, table, view by using the
COMMENT statement. The comment is stored in the data dictionary and can be
viewed in one of the following data dictionary views in the COMMENTS column:
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Syntax: COMMENT ON TABLE table | COLUMN table.column IS text ;
Foreign Key
References
On delete cascade
On Delete Set NULL
Foreign Key
Defines the column in the child table at the table constraint level
References
Identifies the table and column in the parent table. Reference key accepts
NULL and duplicate values.
On delete cascade
Deletes the dependent rows in the child table when a row in the parent table is
deleted.
On Delete Set NULL
Converts dependent foreign key values to null.
For example we want following table structures and constraints imposed on those
tables as shown below. Give the commands to create those tables with the
specified constraints on those tables.
Department47473 (Deptno , dname)
Employee47473 (Empno, ename, salary, dno)
Deptno of Department47473 is a primary key
Empno of Employee47473 is a primary key
Dno of Employee47473 is a reference key
Solution
Oracle SQL Workbook - Page No : 97
Assume the case where supermarket selling various items and customers order
the items. Items may be returned by people who purchased it.
SQL> CREATE TABLE itemmaster (
itemno
NUMBER (3) PRIMARY KEY,
itemname
VARCHAR2 (10),
stock
NUMBER (3) CHECK (stock > 0)
);
SQL> CREATE TABLE itemtran (
trnno
NUMBER (3),
itemno
NUMBER (3) REFERENCES itemmaster (itemno),
trndate
DATE,
trntype
CHAR (1) CHECK (UPPER (trntype) IN (R,I)),
quantity
NUMBER (3) CHECK (quantity > 0),
PRIMARY KEY (trnno, itemno)
);
SQL> CREATE TABLE itemrefund(
trnno
NUMBER (3),
itemno
NUMBER (3),
quantity
NUMBER (3),
FOREIGN KEY (trnno,itemno) REFERENCES itemtran
);
ANALYSIS:
Removing the primary key along with Reference key
ANALYSIS:
Dropping the table along with constraints
Objectives
After completing this lesion, you should be able to do the following.
Write SELECT statements to access data from more than one table using
equality and non-equality join.
View Data that generally does not meet a join condition by using outer joins
Join a table itself by using self join
Join will enable you to gather and manipulate data across several tables. By
One of the most powerful features of SQL is its capability to gather and
manipulate data from across several tables. Without this feature you would have
to store all the data elements necessary for each application in one table. Without
common tables you would need to store the same data in several tables.
TYPES OF JOINS
Oracle supports different types of joins as defined in the following table.
Oracle Proprietary Joins(8i and SQL: 1999 Complaint Joins
prior)
Equi join
Cross join
Non-Equi join
Natural Join
Outer join
Using clause
Self Join
The Oracle 9i database offers join syntax that is SQL: 1999 compliant. Prior to 9i
release, the join syntax was different from the ANSI standards. The new SQL: 1999
compliant join syntax does not offer any performance benefits over the Oracle
proprietary join syntax that existed in prior releases.
empno,
ename,
job,
sal,
dname
FROM
emp,dept
WHERE
emp.deptno
OUTPUT:
EMPNO
---------7782
7839
7934
7369
7876
7902
7788
7566
7499
7698
7654
7900
7844
7521
ENAME
---------CLARK
KING
MILLER
SMITH
ADAMS
FORD
SCOTT
JONES
ALLEN
BLAKE
MARTIN
JAMES
TURNER
WARD
JOB
SAL DNAME
--------- ---------- -------------MANAGER
2450 ACCOUNTING
PRESIDENT
5000 ACCOUNTING
CLERK
1300 ACCOUNTING
CLERK
800 RESEARCH
CLERK
1100 RESEARCH
ANALYST
3000 RESEARCH
ANALYST
3000 RESEARCH
MANAGER
2975 RESEARCH
SALESMAN
1600 SALES
MANAGER
2850 SALES
SALESMAN
1250 SALES
CLERK
950 SALES
SALESMAN
1500 SALES
SALESMAN
1250 SALES
ANALYSIS:
Efficiency is more when we compare the information from lower data table(master
table) to Higher data table( child table).
When Oracle processes multiple tables, it uses an internal sort/merge procedure to
join those tables. First, it scans & sorts the first table (the one specified last
in FROM clause). Next, it scans the second table (the one prior to the last in the
FROM clause) and merges all of the retrieved from the second table with those
retrieved from the first table. It takes around 0.96 seconds
INPUT:
SQL> SELECT empno,ename,job,sal,dname FROM emp,dept WHERE emp.deptno = dept.deptno;
ANALYSIS:
Here driving table is EMP. It takes around 26.09 seconds
So, Efficiency is less.
ANALYSIS:
Displays all the employees whose salary lies between any pair of low and high salary
ranges.
INPUT:
SQL> SELECT * FROM dept WHERE deptno NOT IN (SELECT DISTINCT deptno FROM emp);
OUTPUT:
DEPTNO
DNAME
LOC
---------- -------------- ------------40 OPERATIONS
BOSTON
ANALYSIS:
Displays the details of the department where there are no employees
empno,ename,job,sal,dname
FROM
dept,emp
WHERE
dept.deptno
OUTPUT:
EMPNO
---------7782
7839
7934
7369
7876
7902
7788
7566
7499
7698
7654
7900
7844
7521
ENAME
---------CLARK
KING
MILLER
SMITH
ADAMS
FORD
SCOTT
JONES
ALLEN
BLAKE
MARTIN
JAMES
TURNER
WARD
JOB
SAL DNAME
--------- ---------- -------------MANAGER
2450 ACCOUNTING
PRESIDENT
5000 ACCOUNTING
CLERK
1300 ACCOUNTING
CLERK
800 RESEARCH
CLERK
1100 RESEARCH
ANALYST
3000 RESEARCH
ANALYST
3000 RESEARCH
MANAGER
2975 RESEARCH
SALESMAN
1600 SALES
MANAGER
2850 SALES
SALESMAN
1250 SALES
CLERK
950 SALES
SALESMAN
1500 SALES
SALESMAN
1250 SALES
OPERATIONS
SELF JOIN
Joining the table from itself is called as self join.
INPUT:
SQL> SELECT worker.ename || ' IS WORKING UNDER ' || manager.ename
FROM emp worker, emp manager WHERE worker.mgr = manager.empno;
OUTPUT:
WORKER.ENAME||'ISWORKINGUNDER'||MANAGE
-------------------------------------SCOTT IS WORKING UNDER JONES
FORD IS WORKING UNDER JONES
ALLEN IS WORKING UNDER BLAKE
WARD IS WORKING UNDER BLAKE
JAMES IS WORKING UNDER BLAKE
TURNER IS WORKING UNDER BLAKE
MARTIN IS WORKING UNDER BLAKE
MILLER IS WORKING UNDER CLARK
ADAMS IS WORKING UNDER SCOTT
JONES IS WORKING UNDER KING
CLARK IS WORKING UNDER KING
BLAKE IS WORKING UNDER KING
SMITH IS WORKING UNDER FORD
ANALYSIS:
It displays who is working under whom MGR number appearing against employee is the
employee number of manager
SEQUENCE OBJECT
Used to generate sequence(Unique) Integers for use of primary keys.
Syntax: CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Sequence
INCREMENT BY n
START WITH n
MAXVALUE n
NOMAXVALUE
MINVALUE n
NOMINVALUE
CYCLE | NOCYCLE
Example
CREATE SEQUENCE sqno47473
START WITH 1
INCREMENT BY 1
MAXVALUE 10;
It doesnt allow you to update the condition column as well as it doesnt allow you
to insert the details of employees with DEPTNO other than 20.
We can also create a view using group functions. Such views are called as INLINE
views. They are by default read only.
SQL> CREATE OR REPLACE VIEW simpleview47473 AS SELECT
SUBSTR(hiredate,-2) YEAR, COUNT(*) NUMB FROM empl47473
GROUP BY job;
To remove a view
SQL> DROP VIEW <VIEWNAME>;
A pseudo-column is a column that yields a value when selected but which is not
an actual column of the table.
ROWID
ROWNUM
SYADATE
NEXTVAL
CURRVAL
NULL
LEVEL
Are called as Pseudo-columns.
SELECT ROWNUM, empno, ename FROM emp;