Stands For Structured Query Language: - Accepted As Standard Language (ISO, ANSI) For Relational Database
Stands For Structured Query Language: - Accepted As Standard Language (ISO, ANSI) For Relational Database
Stands For Structured Query Language: - Accepted As Standard Language (ISO, ANSI) For Relational Database
CREATE
ALTER Data definition language (DDL)
DROP
RENAME
TRUNCATE
1.SQL * PLUS
SQL
STRING,DATE
DATATYPES CLAUSES ARE
SHOULD BE ENTERED IN
ENCLOSED IN DIFFERENT LINES
SINGLE QUOTES
SELECTING ALL COLUMNS
P
ALL COLUMNS
SELECT *
FROM P
VID PID VID PID
V1 P10 V1 P10
V1 P8 V1 P8
ALL
V2 P5 V2 P5 COLUMNS
V3 P8 V3 P8
SELECT-PROJECTION
P
PROJECTION
SELECT VID
VID PID FROM P
VID
V1 P10
V1
V1 P8
V2
V2 P5
V2
V3 P8
V3
SELECT-RESTRICTION
P
RESTRICTION
SELECT *
FROM P
VID PID WHERE
VID PID
V1 P10 VID=‘V1’
V1 P10
V1 P8
V2 P5
V3 P8
Limiting Rows Using a Selection
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 CLARKE 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 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 7682 23-JAN-82 1300 10
•COLUMN NAME
•COMPARISON CONDITION
OPERATOR OPERATOR
TYPE
COMPARISON =,<=,>=,<>
LOGICAL AND,OR,NOT
SPECIAL IN,NOT IN ,BETWEEN
PATTERN LIKE,NOT LIKE
MATCHING
NULL IS NULL,IS NOT
NULL
Pattern Matching(Like operator)
COMMAND DESCRIPTION
S% BEGIN WITH S
%S END WITH S
SECOND LETTER STARTING
_S%
WITH S
_____ EXACTLY 5 LETTERS
PRACTICE SESSIONS-1
JOB
---------
CLERK
SALESMAN
SALESMAN JOB
MANAGER ---------
SALESMAN ANALYST
MANAGER CLERK
MANAGER PRESIDENT
ANALYST MANAGER
PRESIDENT SALESMAN
SALESMAN
CLERK
CLERK
ANALYST
CLERK
CONCAT OPERATOR
select ‘RAM’||’LAKHAN’ “CONCAT” FROM DUAL
CONCATS STRINGS OR
COLUMNS CONCAT
-------------------------------
|| IS THE NOTATION RAMLAKHAN
DOMINO’s PIZZA
DEFINE/UNDEFINE
DEFINE- DEFINES A VARIABLE AND ASSIGNS A VALUE TO IT
DEFINE V_SAL=5000
ENAME SAL
---------- ----------
KING 5000 UNDEFINE- REMOVES VARIABLE
UNDEFINE V_SAL
Functions
Single-row Multiple-row
functions functions
Character
Accepts
Number
different types Single-row
functions
Conversion Date
Character Functions
Character
functions
Case-manipulation Character-manipulation
functions functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE
TRANSLATE
Case Manipulation Functions
TRIM('THISSTRINGHASLEADINGANDTR
AILINGSPACES
-------------------------------------------
this string has leading and trailing spaces
PRACTICE SESSIONS
1. Display the total content of dept table & salgrade
table.
2. List the employees whose names start with "S“
(not "s")
3. List the employee names ending with "S“.
4. List the names of employees whose names have
exactly 6 characters:
5. List the employee names having "I" as the second
character: (Write minimum 2 queries)
6. Display o/p ‘SMITH works as CLERK’ using concat()
7. Find number of ‘A’ occurrences in each row of
dname column
PRACTICE SESSIONS
8. Write a query to perform trim operation on ename column
of emp table.
9. Write a query to perform ‘replace’ function on ename for
replacing first 3 characters of ename by numbers.
10. Left justify sal column of emp table.(use #)
11. Right justify job column of emp table (use $)
12. Write a query to find 3rd character in ename.
13. Create a query to display all the data from the
EMPLOYEES table. Separate each column by a
comma. Name the column THE_OUTPUT.
14. Write a query to find last character in ename.
15. Display all enames with only 3rd character replaced by
numbers.
16. Display all enames with last character being different
case.
17. Display only those names where last character is getting
repeated.
PRACTICE SESSIONS
18. Display only those names where second character is getting
repeated In 3rd position.
19. Display all the employees names replacing with * as per the
length of their names.
20. Show those employees that have a name starting with ‘J’,
‘K’,’M’,’S’
21. Display the names of all employees who have both an A and
an E in their name.(use other than like operator)
23. Display all employee names in which the third letter of the
name is A.
PRACTICE SESSIONS
24. Find all the names where 3rd character is getting
repeated.
26. Display all the enames with last character being lower
case.
27. Display all the enames with first character being lower
case.
MOD(9,2)
----------------
1
ASCII('A')
----------
65
CHR
SQL> SELECT CHR(65) FROM DUAL;
CHR(65)
--------------------
A
ABS SQL> SELECT ABS(-75) FROM DUAL;
ABS(-75)
----------
75
Number Functions
ROUND
SQL> SELECT ROUND(99.526,2) FROM DUAL;
ROUND(99.526,2)
-----------------------
99.53
TRUNC
SQL> SELECT TRUNC(99.526,2) FROM DUAL;
TRUNC(99.526,2)
-----------------------
99.52
CEIL & FLOOR
SQL> SELECT CEIL(99.4) ,FLOOR(99.4) FROM DUAL;
CEIL(99.4) FLOOR(99.4)
---------------- -------------------
100 99
Date Functions
Function Description
MONTHS_BETWEEN Number of months
between two dates
ADD_MONTHS Add calendar months to
date
NEXT_DAY Next day of the date
specified
• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
19.6774194
• NEXT_DAY ('01-SEP-95','FRIDAY')
'08-SEP-95'
• LAST_DAY('01-FEB-95') '28-FEB-95'
• ROUND(TO_DATE('01-JUL-05'),’YYYY’)
‘01-JAN-06'
• TRUNC(TO_DATE('01-JUL-05'),’YYYY’)
‘01-JAN-05'
CONVERSION FUNCTIONS
•TO_CHAR
•TO_DATE
•TO_TIMESTAMP
•TO_YMINTERVAL
•TO_DSINTERVAL
•TO_NUMBER
Useful formats while Using To_char
Function
FORMAT DESCRIPTION EXAMPLE
MM Number of month 12
RM Roman Numerical month XII
MON Three letter abbreviation DEC
MONTH Month fully spelt out DECEMBER
DDD Number of days since Jan 1 347
DD Number of the day of month 13
D Number of days in week 2
DY Three-letter abbreviation of day WED
DAY Day fully spelt out WEDNESDAY
YYYY Full 4 digit year 1995
SYYYY Signed Year 1000,BC=1000
YYY Last three digits of year 995
YY Last 2 digits of year 95
Y Last digit of year 5
YEAR Year fully spelt out NINTEEN-NINTY-FIVE
GENERAL FUNCTIONS
SELECT ,ENAME,SAL,
DECODE(JOB,'CLERK',2.0*SAL,'ANALYST',2.25*SAL,'SALESMAN',2.5*SAL,SAL)
"BONUS“ FROM EMP
18. Employees will be given an additional incentive for completing one year
service. Who have joined on or before 15th will be paid on the last Friday of
the same month after a year of appointment and who have joined after 15th
will be paid on last Friday of next month after a year. Display their incentive
payment date.
19. List employees hired on Monday.
20. Calculate how many days old you are.
21. Write a query that produces the following for each employee:
<employee name> earns <sal> monthly but wants <3 times salary>.
Label the column Dream Salaries.
22. Create a query that displays the employees names and commission
amounts. If an employee does not earn commission, put “No Commission.”
Label the column COMM.
23. Write a query to find out first ‘Sunday’ of hiredate
24. Create an anniversary overview based on the hire date of the employees.
Sort the anniversaries in ascending order.
25. Display the name and hire date of every employee who was hired in 1981.
Aggregate Functions
MIN(SAL)
29025/14 AVG(SAL)
COUNT(*)
MAX(SAL)
SUM(SAL)
Aggregate Functions
COUNT(*) DATE
CHARACTER
MIN NUMERIC
MAX
AVG NUMERIC
SUM
HAVING TO RESTRICT
GROUPS
COUNT
SELECT COUNT(*) FROM EMP
• SQL groups the result after it retrieves the rows from a table
SELECT SUMSAL),JOB
FROM EMP
GROUP BY JOB
USING GROUP BY
SELECT COUNT(*),DEPTNO SELECT AVG(SAL),JOB
NOT A GROUP
BY EXPRESSION
NOT A SINGLE –
GROUP
GROUPFUNCTION
GROUP FUNCTION
NOT ALLOWED HERE
MAX(COUNT(*)
SELECT MAX(COUNT(*))
--------------------
6
FROM EMP
GROUP BY DEPTNO
PRACTICE SESSIONS
1. List the department numbers and number of employees in each
department:
2. List the department number and the total salary payable in each
department:
3. List the jobs and the number of employees in each job. The result
should be in descending order of the number of employees:
4. List the total salary, maximum and minimum salary and the average
salary of employees job wise:
5. List the average salary for each job excluding managers
6. List the average monthly salary for each job type within department.
7. List average salary for all departments employing more than five people.
8. List jobs of all the employees where maximum salary is greater than or
equal to 3000.
9. List the total salary, maximum and minimum salary and the average
salary of the employees job wise, for department number 20 and
display only those rows having average salary greater than 1000:
10. List the number of people along with enames having ‘S’ in their name.
11. Display number of people along with the job which contains only 1 person
in that job
12. Display job along with minimum salary which has minimum salary greater
than or equal to 3000
The SET Operators
UNION/UNION ALL
A B
INTERSECT
A B
MINUS
The SET Operators
RULES:
1. Number of columns in the select statements should be
same.
SELECT ENAME,SAL
WRONG
FROM EMP
WHERE DEPTNO=10
UNION
SELECT ENAME,SAL,JOB
FROM EMP
WHERE DEPTNO=20
The SET Operators
RULES:
2. Datatypes of the corresponding columns should be
same.
WRONG
SELECT ENAME, SAL
FROM EMP
WHERE DEPTNO=10
UNION
ANALYST
ANALYST
CLERK
ANALYST CLERK
CLERK MANAGER
MANAGER
PRESIDENT
The SET Operators
UNION ALL MANAGER
SELECT JOB FROM EMP WHERE DEPTNO=10 PRESIDENT
CLERK
UNION ALL
SELECT JOB FROM EMP WHERE DEPTNO=20
ANALYST
ANALYST
CLERK
CLERK CLERK
MANAGER MANAGER
PRESIDENT
ANALYST NO
ANALYST SORTING
CLERK
CLERK
MANAGER
The SET Operators
INTERSECT MANAGER
PRESIDENT
SELECT JOB FROM EMP WHERE DEPTNO=10 CLERK
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20
ANALYST
ANALYST
CLERK
CLERK CLERK
MANAGER MANAGER
The SET Operators
MINUS MANAGER
PRESIDENT
SELECT JOB FROM EMP WHERE DEPTNO=10 CLERK
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20
ANALYST
ANALYST
CLERK
PRESIDENT CLERK
MANAGER
PRACTICE SESSIONS
ON E.DEPTNO=D.DEPTNO
OUTER JOIN
* OUTER JOIN=EQUIJOIN+MISSING DATA
EMP ENAME JOB MGR HIREDATE SAL COMM DEPTNO DEPTNO DNAME LOC
NO
10 ACCOUNTIG NEWYORK
7369 SMITH CLERK 7902 17-DEC-80 800 20
40 OPERATIONS BOSTON
MISSING DATA
ON E.DEPTNO=D.DEPTNO
OUTER JOIN
EMP ENAME JOB MGR HIREDATE SAL COMM DEPTNO
NO
1111 RAMU
DEPTNO DNAME LOC
10 ACCOUNTIG NEWYORK
MISSING DATA
20 RESEARCH DALLAS
30 SALES CHICKAGO
40 OPERATIONS BOSTON
ON E.DEPTNO=D.DEPTNO
OUTER JOIN
EMP ENAME JOB MGR HIREDATE SAL COMM DEPTNO DEPTNO DNAME LOC
NO
10 ACCOUNTIG NEWYORK
7369 SMITH CLERK 7902 17-DEC-80 800 20
MISSING DATA
WHERE E.DEPTNO(+)=D.DEPTNO
Rules to place (+) operator
AND S.HISAL
SELF JOIN
* Table is joined to the table itself
EMP E EMP M
ON E.MGR=M.EMPNO
Cross Joins
(Cartesian product )
Cartesian
product:
20x8=160 rows
SQL 99 SYNTAX
SELECT ENAME ,DNAME
FROM EMP
SQL 99 SYNTAX
SELECT ENAME ,DNAME
FROM EMP
JOIN DEPT
USING (DEPTNO)
PRACTICE SESSIONS-1
1. List the employee numbers, names, department numbers
and the department name
2. List all employees who joined the company before their
manager.
3. Select employees name with reporting manager.
4. List all employees who are earning more than
manager’s.
5. Write a query to display employee name,managername
and manager’s department name.
6. Display all the employees who are in sales department
and not reporting to Blake.
7. Find the department name where maximum numbers of
employees are working.
8. Find employees who are working in ACCOUNTING,
RESEARCH department as CLERK with a salary more
than 800.
PRACTICE SESSIONS-2
1. List deptno, dname along with total salary in each department.
2. List details from emp, dept and salgrade table excluding clerks and
employees with grade 1. Order on their names.
3. List employee with grade 3 or 4
4. List employees located in dallas.
5. List ename, job, sal, grade, dname with annual remuneration greater
than 36000 or any clerks.
6. List employee and department details for department 30 and 40.
7. List all employees who earn less than their managers. List their
managers details also.
8. Find the job that was filled in first half of 1982 and the same job that
was filled during first half of 1983
9. Find all employees who draw salary more than their manager
10. Display all clerks and their reporting managers
What Is a Subquery?
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list
FROM table);
SELECT ename
OUTER
FROM emp
QUERY WHERE sal >
>
2975
(SELECT sal
SUB
FROM emp
QUERY WHERE ename=‘JONES’)
ENAME
----------
SCOTT
KING
FORD
Subquery
TYPES
•SINGLE ROW
•MULTIPLE ROW
•MULTIPLE COLUMN
•NESTED
•CORRELATED
Subquery
Multiple row subquery using IN
SELECT ename,sal
OUTER
FROM emp
QUERY WHERE sal IN
>
3000,1250
(SELECT sal
SUB
FROM emp
QUERY WHERE ename in(‘FORD’,’MARTIN’)
ENAME SAL
---------- -------
SCOTT 3000
WARD 1250
Subquery
Multiple row subquery using ANY
SELECT ename,sal
OUTER
FROM emp
QUERY WHERE sal > ANY
>
ENAME SAL
---------- ----------
KING 5000
FORD 3000
SCOTT 3000
JONES 2975
BLAKE 2850
CLARK 2450
ALLEN 1600
TURNER 1500
MILLER 1300
MARTIN 1250
WARD 1250
Subquery
Multiple row subquery using ALL
SELECT ename,sal
OUTER
FROM emp
QUERY WHERE sal > ALL
>
ENAME SAL
---------- ----------
KING 5000
FORD 3000
SCOTT 3000
JONES 2975
BLAKE 2850
CLARK 2450
Subquery
Multiple COLUMN subquery
SELECT ename,sal,deptno
OUTER
FROM emp
QUERY WHERE (deptno,sal) IN
>
SELECT ename,sal,deptno
FROM emp
OUTER WHERE sal >
QUERY
Ename Sal deptno
>
Smith 800 20
(SELECT avg(sal)
from emp
?)
SUB
QUERY where deptno=
Subquery
Correlated subquery
SELECT ename,sal,deptno
FROM emp E
OUTER
QUERY
WHERE sal >
Ename Sal deptno
>
Smith 800 20
(SELECT avg(sal)
from emp
SUB where deptno=E.deptno)
QUERY
Subquery
NESTED subquery
SELECT ename,job
FROM emp
OUTER
QUERY
WHERE job in
>
CLERK,SALESMAN
(SELECT job
FROM emp
GROUP BY job
SUB having
QUERY
count(*) in
ENAME JOB
(SELECT MAX(COUNT(*))
----------
SMITH
-------------------
CLERK
FROM emp
ADAMS CLERK GROUP by job))
JAMES CLERK
MILLER CLERK
ALLEN SALESMAN
WARD SALESMAN
MARTIN SALESMAN
TURNER SALESMAN
PRACTICE SESSIONS-1
1. List employee working under KING
2. List department with maximum average salary.
3. Find employees who earn highest salary in each job type.
4. Find employees who earn minimum salary for each job type excluding
clerks. Sort on their salary.
5. Find most recently hired employee in each department. Order by
hiredate.
6. List departments for which no employees exists.
7. In which year did most people join the company. Display the year and
no of employees
8. Display department with maximum average salary.
9. Write a query to list enames with job having maximum no., of
employees
10. Write a query to list enames having maximum number of characters
in their name
PRACTICE SESSIONS-2
1. Create a query to display the employee numbers and names of all
employees who earn more than the average salary. Sort the results in
descending order of salary.
2. Write a query to display the last name and hire date of any employee in
the same department as BLAKE.Exclude BLAKE.
3. Find the department name of Mr.SMITH.
4. Write a query to display all employees who have joined after Mr.JONES.
5. Show the department numbers, names, and locations of the
departments where no sales representatives work.
6. Display Name,Job,Salary ofemployees who are having salaries more
than salesman. Arrange the data from highest to lowest.
7. Find all employees who have been with the company longer than any
top-level manager.
8. List the employees of dept 20 who have same job as that of sales
department.
9. Find out names of the employees who have joined on the same date
PRACTICE SESSIONS-3
1. Find out the seniormost SALESMAN
2. Find out the Juniormost Manager
3. Find the highest paid SALESMAN
4. Fiind the lowest paid Manager
ROLLUP
The ROLLUP function allows the creation of sorted subtotals
at every level of an aggregation up to the sum total.
ROLLUP first calculates the aggregates specified in the
GROUP BY clause. Subtotals of the higher levels are then
created progressively, navigating from right to left through
the grouping attributes. Finally, the sum total is output
SELECT deptno, job, COUNT(*),
SUM(sal)
FROM emp
GROUP BY rollup(deptno, job);
CUBE
The CUBE function forms all possible combinations of
subtotals, including the sum total.
This allows very simple cross-classified table reports, such as
are necessary in drill-down functionalities of client tools. With
multi-dimensional analyses, the CUBE function generates all
the subtotals that can be formed for a cube with the specified
dimensions
SELECT deptno, job, COUNT(*),
SUM(sal)
FROM emp
GROUP BY cube(deptno, job )
GRANT & REVOKE
GRANT IS USED FOR GIVING PRIVILEGES TO USERS
A sequence:
• Automatically generates unique
numbers
• Is a sharable object
• Is typically used to create a primary
key value
• Replaces application code
• Speeds up the efficiency of accessing
sequence values when cached in
memory
The CREATE SEQUENCE Statement
Syntax
1.Create a sequence to be used with the primary key column of the DEPT table. The
sequence should start at 200 and have a maximum value of 1000. Have your
sequence increment by ten numbers. Name the sequence DEPT_ID_SEQ.
2.Write a query in a script to display the following information about your sequences:
sequence name, maximum value, increment size, and last number.
3 Write a script to insert two rows into the DEPT table. Be sure to use the sequence
that you created for the ID column. Add two departments named Education and
Administration. Confirm your additions.
VIEWS
developer
enduser
• Virtual table
VIEWS
CREATE OR REPLACE
VIEW V1
AS SELECT *
FROM EMP
VIEWS
GROUP
GROUP BY FUNCTIONS
NO DMLS
ON VIEW
UNION
OPERATOR DISTINCT
VIEW WITH CHECK OPTION
•Specifies the level of checking to be done when inserting or
updating data through a view.
CREATE VIEW V2
AS SELECT * FROM EMP
WHERE DEPTNO=10 WITH CHECK OPTION
122
INDEXES
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO