You are on page 1of 40

Data Query Language – Retrieving or fetching data from database.

 Select – Normal statement to retrieve the data from the table and displaying as result.
 Projection – The process of retrieving the data by selecting only columns from the table.
 Selection – Process of retrieving the data from both rows as well as columns.
 Join – Process of retrieving the data from multiple tables

Projection
SELECT clause:
SELECT(2) */COLUMN_NAME //* means all the columns, * cannot be clubbed with
FROM(1) TABLE_NAME; any other column

SELECT S_NAME //Will give all the names(only names)


FROM STUDENT;

SELECT S_NAME, SCORE


FROM STUDENT;

DISTINCT clause – Mainly used to remove duplicate values. Should be used before column name.
SELECT DISTINCT S_NAME
FROM STUDENT;

If we have multiple column names then if two rows have all the column values same then only one will
be printed, else even if any one column value is not matching, then both rows will be printed.

EXPRESSION – Combination of operands(Values) & operators(+,-,* etc)


Two kinds of operands-
 Column_Name
 Literal – Three types:
o Character Literal – Case sensitive. Must be enclosed in ‘ ‘(Single Quotes)
o Date Literal - Case sensitive. Must be enclosed in ‘ ‘(Single Quotes)
o Number Literal – No need to use Quotes

Eg: Display annual salary of all employees


SELECT SAL *12 //Here SALARY * 12 is the expression(12 is number literal, SAL Column
FROM EMPLOYEES; i.e monthly salary)

If we want to display all columns but want to add some expression as well then we can do like-

SELECT EMP.*, SAL * 12 //EMP is table name, SAL is column


FROM EMP; //This displays all the columns(including monthly salary column)
and then the salary *12 column

SELECT SAL + SAL * 10/100 //Column Name will be SAL+SAL*10/100


FROM EMP;
ALIAS – Alternative name given to an expression that should be displayed. There should not be any
space in the Alias name, If space should be there then we have to include the alias name in double
quotes(“ ”).

SELECT SAL*12 AS ANNUAL_SALARY //or we can use “ANNUAL SALARY”


FROM EMP;

AS is optional, but is recommended.


SELECT SAL*12 ANNUAL_SALARY //Same output as above
FROM EMP;

DESC – Used to display the description of the table. Description means all column names, constraints on
each column and data_type of each column.
DESC EMP; //Will give the description of the table and it will print like

COLUMN_NAMES CONSTRAINTS DATA_TYPE


S_ID UNIQUE NUMBER

Selection
Retrieving the data by selecting both columns as well as rows.
Syntax:
SELECT */COLUMN_NAME
FROM TABLE_NAME
WHERE FILTER_CONDITION; //WHERE is used to filter records based on a condition, checks
row by row
st
FROM will execute 1 , then WHERE then SELECT

SELECT E_NAME //Will fetch all E_NAME whose D_NO is 20


FROM EMP
WHERE D_NO = 20;

SELECT *
FROM EMP
WHERE ENAME = ‘SMITH’;

SELECT *
FROM EMP
WHERE HIREDATE > ’31-DEC-1981’; //Will fetch details of all employees who joined after
1981, i.e from 1982

SELECT *
FROM EMP
WHERE HIREDATE < ’01-JAN -1981’; //Will fetch details of all employees who joined before
1981, i.e till 31st DEC 1980
SELECT ENAME,SAL, SAL*12 AS ANNUAL_SAL
FROM EMP
WHERE SAL*12 > 12000;

> is used for an after condition


< is used for a before condition

AFTER > 31-DEC-YYYY //(Can be used like starting from year 1981 so >’31-DEC-1980’)
BEFORE < 01-JAN-YYYY //(Can be used like ending till year 1987 so <’01-JAN -1988’)

OPERATORS IN SQL – Seven types of operators:

i. Arithmetic - + , - , * , / , %
ii. Concatenation - || //Concatenates two strings
Syntax:
‘String1’|| ‘String2’ //COLUMN_NAME should not be included in ‘ ’
Eg: SELECT ‘MR ’ || E_NAME
FROM EMP
WHERE JOB = ‘MANAGER’; //Result will be like MR John, MR Smith etc for all Managers

iii. Comparison - =, < , > , !=


iv. Relational - <=, >=
v. Logical – AND, OR, NOT
Syntax:
SELECT *
FROM EMP
WHERE JOB = ‘MANAGER’ AND DEPT_NO = 20;

SELECT *
FROM EMP
WHERE JOB = ‘ANALYST’ OR SAL < 1000;

SELECT *
FROM EMP
WHERE NOT (JOB = ‘MANAGER’);
or we can write like:
SELECT *
FROM EMP
WHERE JOB != ‘MANAGER’;

SELECT *
FROM EMP
WHERE JOB = ‘MANAGER’ AND (DEPT = 20 || DEPT = 30);

SELECT *
FROM EMP
WHERE DEPT = 10 || DEPT = 20 || DEPT = 30;
SELECT *
FROM EMP
WHERE HIREDATE > ’31-DEC-1981’ AND HIREDATE < ’01-JAN-1987’;

SELECT EMP.*, SAL*12 AS ANNUAL_SAL


FROM EMP
WHERE NOT(JOB = ‘MANAGER’ || JOB = ‘ANALYST’);
//Will fetch details of all employees except who are manager or analyst

vi. Special Operators – These are of 8 types:


o IN
o NOT IN
o BETWEEN
o NOT BETWEEN
o IS
o IS NOT
o LIKE
o NOT LIKE

vii. Subquery – 4 types


o ALL
o ANY
o EXISTS
o NOT EXISTS

Special Operators-
IN – Multi valued operator that accepts one condition at LHS and multiple values at RHS.
Eg: SELECT *
FROM EMP
WHERE DEPT_NO IN (10,20,30); //Fetches details of employees who belong to either
dept 10 or 20 or 30

SELECT *
FROM EMP
WHERE DEPT_NO = 10 AND JOB IN (‘MANAGER’,’CLERK’);

NOT IN – Similar to IN except this rejects the values that satisfy the condition.
Eg: SELECT *
FROM EMP
WHERE DEPT_NO = 10 AND JOB NOT IN (‘MANAGER’,’PRESIDENT’);
//Fetches the details of all employees who belong to dept 10 excluding manager or
president

BETWEEN – Used for range of values. Considers the boundary values too. Can compare dates as
well.
Eg: SELECT *
FROM EMP
WHERE SAL BETWEEN 1000 AND 3000;
//Fetches details of employees whose salary >=1000 & <=3000
NOT BETWEEN – Similar to between except this rejects the values that satisfy the condition. This
also includes boundary values to be rejected.
Eg: SELECT *
FROM EMP
WHERE SAL NOT BETWEEN 1000 AND 3000;
//Fetches details of employees whose salary <1000 & salary>3000

IS – Used to compare the values present at LHS with NULL as NULL cannot be used with any
other operator. We must use IS to compare with NULL.
Eg: SELECT *
FROM EMP
WHERE COMM IS NULL;
//Fetches details of employees whose commission is null

SELECT *
FROM EMP
WHERE COMM IS NULL AND SAL IS NULL;

IS NOT – Used to compare the values at LHS with NOT NULL.


Eg: SELECT NAME, SAL
FROM EMP
WHERE SAL IS NOT NULL;
//Fetches name & sal of employees who earn some salary can be even 1 Rs but not null

LIKE – Used to perform pattern matching. We use these 2 special characters, (i) % (ii)
_(Underscore) % represents n(n>=0) number of characters and one _ represents only one
character.
Eg: SELECT *
FROM EMP
WHERE HIREDATE LIKE ‘%APR%’;
//Fetches details of employees who joined in april as date format could be DD-MMM-
YYYY or DD-MMM-YY

SELECT *
FROM EMP
WHERE SAL LIKE ‘___’ AND HIREDATE LIKE ‘%81’;
//Fetches details of employees who have a 3-digit salary and joined in year 1981. _ and
% should be included in single quotes.

SELECT ENAME
FROM EMP
WHERE ENAME LIKE ‘_A%’;
//Fetches name of employees who have A as 2nd character in their name
NOT LIKE – Rejects the values which satisfy the condition.
Eg: SELECT *
FROM EMP
WHERE ENAME NOT LIKE ‘_A%’;
//Fetches name of employees who don’t have 2nd character as ‘A’ in their name

SELECT *
FROM EMP
WHERE JOB = ‘CLERK’ AND DEPT IN (10,30) AND ENAME LIKE ‘%A%’;

SELECT *
FROM EMP
WHERE JOB = ‘SALES’ AND COMM IS NULL;

SELECT *
FROM EMP
WHERE ENAME LIKE ‘%L%L%’ AND JOB=’MANAGER’;

SELECT *
FROM EMP
WHERE ENAME LIKE ‘A%’ OR ENAME LIKE ‘S%’;

SELECT *
FROM EMP
WHERE ENAME NOT LIKE ‘A%’;

SELECT *
FROM EMP
WHERE JOB=’MANAGER’ AND HIREDATE>’31-DEC-1984’ AND ENAME LIKE ‘%S’;

Functions - Block of code or list of instructions that perform some task. Can be of two types-
 User defined functions
 Built-in functions – Again two types-
o Single row – Executes one row by one i.e checks each condition with each row.
Whatever we saw till now were single row functions.
o Multi row – Executes group by group. Cannot be used with WHERE clause. These ignore
NULL values. All built in functions except count accept only one column name upon
which function will be performed. Again 5 types-
 MAX()
 MIN()
 SUM()
 AVG()
 COUNT() – Only multi row function that accepts *, means all the columns.

Group By – Used to group the records. Can be used without WHERE clause too. Order of Execution
FROM -> WHERE -> GROUP BY -> SELECT
Eg: SELECT COUNT(*)
FROM EMP
GROUP BY DEPT_NO;
//Fetches no of employees in each department. each means use GROUP BY

SELECT DEPT_NO, COUNT(*)


FROM EMP
GROUP BY DEPT_NO;
//Whichever column name is used with GROUP BY clause, can be used with the SELECT clause along with
a multi-row function, else multi-row function doesn’t allow any column_name to be used along with it

SELECT DEPT_NO, COUNT(*)


FROM EMP
WHERE ENAME != ‘JAMES’
GROUP BY DEPT_NO;
//Fetches no of employees in each department except IT WON’T COUNT JAMES

SELECT JOB, MAX(SAL)


FROM EMP
GROUP BY JOB;
//Fetches maximum salary in each job

SELECT DEPT_NO, COUNT(*)


FROM EMP
WHERE SAL>1000
GROUP BY DEPT_NO;
//Fetches no of employees in each department having salary>1000

SELECT DEPT_NO, SUM(SAL)


FROM EMP
GROUP BY DEPT_NO;
//Fetches sum of salary of each department

HAVING clause – Must be written after GROUP BY clause and is also executed after GROUP BY. Used to
filter the groups grouped by GROUP BY clause. Cannot be used without GROUP BY clause. Order of
Execution – FROM -> WHERE -> GROUP BY -> HAVING -> SELECT

Eg: SELECT DEPT_NO, COUNT(*)


FROM EMP
GROUP BY DEPT_NO
HAVING COUNT(*) >= 3;
//Fetches count of department which has no of employees >= 3

Atmost 3 means <=3, atleast 3 means >=3


SELECT DEPT_NO, COUNT(*)
FROM EMP
WHERE JOB=’CLERK’
GROUP BY DEPT_NO
HAVING COUNT(*) >= 2;
//No of employees working in each dept if there atleast two clerks in that department

SELECT DEPT_NO, SUM(SAL)


FROM EMP
GROUP BY DEPT_NO
HAVING SUM(SAL) > 6000;
//Fetches total salary dept wise if the total salary of each dept exceeds 6000

SELECT SAL
FROM EMP
GROUP BY SAL
HAVING COUNT(SAL) > 1; //Fetches repeated salary

or can be written like

SELECT SAL, COUNT(SAL)


FROM EMP
GROUP BY SAL
HAVING COUNT(*) >1;

SELECT JOB, COUNT(*)


FROM EMP
WHERE ENAME LIKE ‘%A%’
GROUP BY JOB
HAVING COUNT(*) > =1;
//Fetches no of emp in each department if there is an employee having A in their name

Escape Character – Used to remove the behaviour of special character & behaves as a normal character.
Must be written before the special character which has to be treated as a normal character.
Most used: ! $ \ /
Eg: SELECT ENAME
FROM EMP
WHERE ENAME LIKE ‘!_%’ ESCAPE ‘!’;
//Displays name of employees if the name starts with _ Here, usually _ is used to denote 1 character
but since we have mentioned ! before _ and also telling that ! is escape so whichever character is used
after ! will be treated as a normal character instead of it’s functionality.

SELECT ENAME
FROM EMP
WHERE ENAME LIKE ‘!%__!_%’ ESCAPE ‘!’;
//Displays name of employees if the name’s 1st character is % and 4th character is _ So here the 1st %
after 1st ! is treated as a normal character and the _ after 2nd ! is treated as a normal character
SELECT ENAME
FROM EMP
WHERE ENAME LIKE ‘%!%’ ESCAPE ‘!’ OR ENAME LIKE ‘%!_’ ESCAPE ‘!’;
//Displays name of employees if the name of employee ends with % or _

ORDER BY – Used to sort the records. Has to be written as the last statement in the query. Order of
Execution – FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY. By default it sorts in the
ascending order. To sort in descending order use DESC with ORDER BY. Returns a table with the sorted
order.
Eg: SELECT *
FROM EMP
ORDER BY HIREDATE;
//Display records based on ascending order of DOJ

SELECT DEPT_NO, COUNT(*)


FROM EMP
GROUP BY DEPT_NO
ORDER BY COUNT(*);
//Display no of employees working in each dept in ascending order

SELECT ENAME, SAL


FROM EMP
WHERE SAL>3000
ORDER BY ENAME, SAL DESC;
//Display employees name and salary given to the employee if the employee earns > 3000. Arrange the
records in descending order
When we give two or more columns in ORDER BY clause then the records will be sorted based on first
column and if for any two rows, the value is same then the second column will be taken into
consideration & if for the same two rows if second column values are also same then it will sort based
on third column. Also, we have to add DESC with each column name whichever column needs to be
sorted as descending order.

Subquery – A query written inside a query is called subquery. The inner query will execute first & give
some output and this output will be taken as input for outer query then outer query will execute. So
outer query is dependent on inner query.
When to use:
Case 1: When we have unknowns present and we use subquery to find the unknowns
Eg: SELECT ENAME
FROM EMP
WHERE SAL > (SELECT SAL
FROM EMP
WHERE ENAME = ‘JOHN’);
//Display name of employees earning more than JOHN
Here JOHN’s salary is unknown so we will find JOHN’s salary in subquery. Now in outer query we
are comparing based on SAL so subquery’s output should have SAL column.
SELECT *
FROM EMP
WHERE DEPTNO = (SELECT DEPTNO
FROM EMP
WHERE ENAME = ‘SCOTT’);
//Display details of employee working in same dept as SCOTT.

SELECT ENAME, SAL


FROM EMP
WHERE SAL < (SELECT SAL
FROM EMP
WHERE ENAME = ‘KING’);
//Display name & salary of the employees who are earning less than KING

SELECT *
FROM EMP
WHERE HIREDATE > (SELECT HIREDATE
FROM EMP
WHERE ENAME = ‘JAMES’);
//Display details of employees who joined after JAMES

SELECT *
FROM EMP
WHERE JOB = ’MANAGER’ AND DEPTNO = (SELECT DEPTNO
FROM EMP
WHERE ENAME = ‘MILLER’);
//Display details of employees working as Manager in the same dept as MILLER

SELECT ENAME, SAL


FROM EMP
WHERE SAL >(SELECT SAL
FROM EMP
WHERE ENAME = ‘SMITH’)
AND SAL < (SELECT SAL
FROM EMP
WHERE ENAME = ‘KING’);
//Display name & sal given to employees earning more than SMITH but less than KING

Case 2: When the data to be selected & the condition to be executed, are in different tables
Eg: SELECT DNAME
FROM DEPT
WHERE DEPTNO = (SELECT DEPTNO
FROM EMP
WHERE ENAME = ‘SMITH’);
//Display department name of SMITH (department name is in DEPT table)

Table structure is as follows. For a foreign key to exist in a table, the column name should be
exact same
DEPT TABLE
DEPTNO DNAME LOC

EMP TABLE
EMPID EMPNAME SAL JOB HIREDATE DEPTNO

SELECT DNAME, LOC


FROM DEPT
WHERE DEPTNO = (SELECT DEPTNO
FROM EMP
WHERE ENAME = ‘MILLER’);
//Display dept name & location of MILLER

SELECT *
FROM EMP
WHERE HIREDATE > (SELECT HIREDATE
FROM EMP
WHERE ENAME = ‘JAMES’)
AND DEPTNO = (SELECT DEPTNO
FROM DEPT
WHERE DNAME = ‘Research’);
//Display details of employee hired after JAMES into Research department

Types of Subquery –
 Single Row Subquery – If a subquery returns exactly one value(one row one column).
Can use normal comparison operators = , < , >
 Multi Row Subquery – if the subquery returns more than one value. Should use special
operators for comparison. IN , NOT IN, LIKE etc

Eg:
SELECT DNAME
FROM DEPT
WHERE DEPTNO IN (SELECT DEPTNO
FROM EMP
WHERE ENAME = ‘SMITH’);
//Here the subquery will return only one value so we can use = as well but using IN is
more proper convention

SELECT *
FROM EMP
WHERE SAL > ALL (SELECT SAL
FROM EMP
WHERE DEPTNO = 30);
//Display details of employees earning more than employees of department 30
ALL will check the condition for each & every value one by one in the returned table
ALL – Returns true if all the conditions on the RHS are satisfied.

ANY – Returns true if any of the conditions on the RHS are satisfied

NOTE – Difficult to identify if a subquery is single row or multi row, then it’s recommended to
use special operators.

SELECT ENAME
FROM EMP
WHERE SAL = (SELECT MAX(SAL)
FROM EMP);
//Display name of employee getting the max salary

SELECT *
FROM EMP
WHERE JOB = ‘MANAGER’ AND SAL = (SELECT MIN(SAL)
FROM EMP
WHERE JOB = ‘MANAGER’);
//Details of an employee earning least salary as manager

SELECT *
FROM EMP
WHERE HIREDATE = (SELECT MAX(HIREDATE)
FROM EMP);
//Details of employee hired latest

If last or latest term is there in the question then use MAX, if first or earliest then use MIN

SELECT ENAME
FROM EMP
WHERE SAL = (SELECT MIN(SAL)
FROM EMP WHERE SAL > (SELECT MIN(SAL)
FROM EMP));
//Display name of employee getting second min salary

Nested Subquery – A subquery written inside a subquery is called nested subquery. We can have
a nest of 255 subqueries.
EMPLOYEE
EID ENAME SAL HIREDATE DNO JOB MANAGER

EMPLOYEE-MANAGER RELATIONSHIP(ABSTRACT TABLE)


EID ENAME MANAGER(EID OF MANAGER)
1 Rahul 4
2 Smith 4
3 John 1
4 Miller 5
5 King 6
6 Rohit 7
7 Anand null

DEPARTMENT
DNO DNAME LOC
Write a query to display John’s Manager(Manager is a JOB in Employee table).
SELECT ENAME
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE ENAME = ‘JOHN’);

Write a query to display department name of Smith’s Manager.


SELECT DNAME
FROM DEPARTMENT
WHERE DNO = (SELECT DNO
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE ENAME = ‘SMITH’));

Write a query to display King’s Manager’s Manager’s name.


SELECT ENAME
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE ENAME = ‘KING’));

Write a query to display all the department details of Smith’s Manager.


SELECT *
FROM DEPARTMENT
WHERE DNO = (SELECT DNO
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE ENAME = ‘SMITH’));
Write a query to display details of employees earning more than Rahul’s Manager.
SELECT *
FROM EMP
WHERE SAL > (SELECT SAL
FROM EMPLOYEE
WHERE EID = (SELECT MANAGER
FROM EMPLOYEE
WHERE ENAME = ‘RAHUL’));

Write a query to display details of employees reporting to James.


SELECT *
FROM EMPLOYEE
WHERE MANAGER = (SELECT EID
FROM EMPLOYEE
WHERE ENAME = ‘JAMES’);

Write a query to display number of employees reporting to Smith.


SELECT COUNT(*)
FROM EMPLOYEE
WHERE MANAGER = (SELECT EID
FROM EMPLOYEE
WHERE ENAME = ‘SMITH’);

Write a query to display the location where the employees of Miller are working.
SELECT LOC
FROM DEPARTMENT
WHERE DNO = ALL (SELECT DNO
FROM EMPLOYEE
WHERE MANAGER = (SELECT EID
FROM EMPLOYEE
WHERE ENAME = ‘MILLER’));

Joins – Process of retrieving the data from multiple tables simultaneously.


We use JOINS when we have to select attributes from more than one table.
Types of JOINS-
 Cartesian JOIN or Cross JOIN
 Inner JOIN or Equi JOIN
 Outer JOIN
o Left Outer JOIN
o Right Outer JOIN
o Full Outer JOIN
 Self JOIN
 Natural JOIN

Cartesian JOIN – Record from table1 will be merged with all the records of table2 and so on.
The number of columns in the resultant table will be sum of number of columns of both the
tables.
Number of records in the resultant table will be product of number of records present in both
the tables.
Syntax:
ANSI – SELECT COLUMN_NAME
FROM TABLE1 CROSS JOIN TABLE2;

ORACLE(Common) – SELECT COLUMN_NAME


FROM TABLE1, TABLE2;

EMPLOYEE
ENAME DNO
A 3
B 1
C 2

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3

Resultant table for the above two tables will be having 4 columns(DNO 2 times) and 9 rows.
ENAME DNO DNO DNAME
A 3 1 D1
A 3 2 D2
A 3 3 D3
B 1 1 D1
B 1 2 D2
B 1 3 D3
C 2 1 D1
C 2 2 D2
C 2 3 D3
Use of Cartesian JOIN is prohibited as it generated more number of unwanted records.
That’s why we have INNER JOIN.

INNER JOIN – Used to obtain only the matching records, for the matching we must write a JOIN
condition. A condition on which we merge the two given tables.
Syntax:
ANSI – SELECT COLUMN_NAME
FROM TABLE1 INNER JOIN TABLE2
ON JOIN_CONDITION;
Syntax of JOIN_CONDITION: TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME

ORACLE – SELECT COLUMN_NAME


FROM TABLE1, TABLE2
WHERE JOIN_CONDITION;
Syntax of JOIN_CONDITION: TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME
Taking above example, if we do INNER JOIN, we’ll get-
ENAME DNO DNO DNAME
A 3 3 D3
B 1 1 D1
C 2 2 D2

Write a query to display employee name & department name for all employees who are
working as Manager.
SELECT ENAME, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND JOB = ’MANAGER’;

Write a query to display employee name & employee salary & location of employee if the
employee salary > 2000 and working in New York.
SELECT ENAME, SAL, LOC
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND SAL > 2000 AND LOC = ‘NEW YORK’;

Write a query to display employee name, salary, department name of the employee who is
working as CLERK in department 20 with salary > 1800.
SELECT ENAME, SAL, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND JOB = ‘CLERK’ AND SAL > 1800 AND
EMPLOYEE.DNO = 20; //Since DNO exists in both the tables, we have to explicitly mention the
table name, should use the table name where this key is foreign key & not the one where it’s
primary key so using EMPLOYEE.DNO = 20

Write a query to display employee name, department no, location of an employee who earns
salary > 2000 in New York.
SELECT ENAME, EMPLOYEE.DNO, LOC
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND SAL > 2000 AND LOC = ’NEW YORK’;

Write a query to display Ename, Department name, department no, salary given to all
employees working as Analyst in Accounting department.
SELECT ENAME, DNAME, EMPLOYEE.DNO, SAL
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND JOB = ‘ANALYST’ AND DNAME =
‘ACCOUNTING’;

Write a query to display Ename, Department name along with Hiredate if the employees hired
before the President
SELECT ENAME, DNAME, HIREDATE
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND HIREDATE < (SELECT HIREDATE
FROM EMPLOYEE
WHERE JOB = ‘PRESIDENT’);
Write a query to display department name and salary given to the employee if employee name
starts with ‘A’ and department name ends with ‘S’.
SELECT ENAME, DNAME, SAL
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND ENAME LIKE ‘A%’ AND DNAME LIKE ‘%S’;

Write a query to display Ename, department name, Hiredate, salary of all the employees
working in department 10 and hired before James and earning salary more than King in Chicago.
SELECT ENAME, DNAME, SAL, HIREDATE
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO AND DNO = 10 AND HIREDATE < (SELECT
HIREDATE
FROM EMPLOYEE
WHERE ENAME = ‘JAMES’) AND SAL > (SELECT SAL
FROM EMPLOYEE
WHERE ENAME = ‘KING’) AND LOC = ’CHICAGO’;

Outer Join – Used to obtain unmatched records. Three kinds-


i. Left Outer Join – Used to obtain unmatched records to the left table along with matching
records.
EMPLOYEE
ENAME DNO
A 3
B 1
C null

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3

If we do EMPLOYEE LEFT |OUTER| JOIN DEPARTMENT, then the resultant will be-

ENAME DNO DNO DNAME


A 3 3 D3
B 1 1 D1
C null null null
Syntax:
ANSI –
SELECT COLUMN_NAME
FROM TABLE1 LEFT |OUTER| JOIN TABLE2 ON JOIN_CONDITION;

Oracle –
SELECT COLUMN_NAME
FROM TABLE1, TABLE2
WHERE TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME (+);
Eg: Write a query to display Ename, Department name of all the employees even if the
employees don’t work in any department.
SELECT ENAME, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO (+);

ii. Right Outer Join – Used to obtain the unmatched records of right table along with the matching
records.

EMPLOYEE
ENAME DNO
A 3
B 1
C null

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3

If we do EMPLOYEE RIGHT |OUTER| JOIN DEPARTMENT Resultant Table-


ENAME DNO DNO DNAME
A 3 3 D3
B 1 1 D1
null null 2 D2

Syntax:
ANSI –
SELECT COLUMN_NAME
FROM TABLE1 RIGHT |OUTER| JOIN TABLE2 ON JOIN_CONDITION;

Oracle –
SELECT COLUMN_NAME
FROM TABLE1, TABLE2
WHERE TABLE1.COLUMN_NAME (+) = TABLE2.COLUMN_NAME;

Write a query to display Ename, Dname of all the employees even if there are no
employees in the department.
SELECT ENAME, DNAME
FROM EMPLOYEE,DEPARTMENT
WHERE EMPLOYEE.DNO (+) = DEPARTMENT.DNO;
iii. Full Outer Join – Used to obtain unmatched records of both the tables along with the matching
records.
EMPLOYEE
ENAME DNO
A 3
B 1
C null

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3

If we do EMPLOYEE FULL |OUTER| JOIN DEPARTMENT Resultant Table-


ENAME DNO DNO DNAME
A 3 3 D3
B 1 1 D1
C null null null
null null 2 D2

Syntax:
ANSI –
SELECT COLUMN_NAME
FROM TABLE1 FULL |OUTER| JOIN TABLE2 ON JOIN_CONDITION;

Oracle –
No Syntax for Oracle for Full Outer Join

Write a query to display Ename, Dname of all employees even if the employees don’t
work in any department and the department doesn’t have any employee.
SELECT ENAME, DNAME
FROM EMPLOYEEE FULL JOIN DEPARTMENT ON EMPLOYEE.DNO = DEPARTMENT.DNO;
//|OUTER| won’t be there in the query but in the syntax we have written just to show
that it’s an OUTER join

Self Join – Joining a table by itself is called as Self Join. When the data to be merged is in the same table
but different records, we use Self Join.

E1.MANAGER = E2.EID

Syntax:
ANSI –
SELECT COLUMN_NAME
FROM TABLE1 JOIN TABLE2 ON JOIN_CONDITION;
Oracle –
SELECT COLUMN_NAME
FROM TABLE T1, TABLE T2
WHERE T1.COLUMN_NAME = T2.COLUMN_NAME;
//T1 AND T2 are the temporary variables we give for the table as both the tables are
same table

Write a query to display employee name, manager’s name for all the employees.
SELECT E1.ENAME = E2.ENAME
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID;

E1.EID E1.ENAME E1.MANAGER E2.EID E2.ENAME E2.MANAGER


1 Alan 3 3 Miller 2
2 Smith 1 1 Alan 3
3 Miller 2 2 Smith 1

Write a query to display employee name, salary along with manager’s name and
manager’s salary for all the employees.
SELECT E1.ENAME AS EMP_NAME, E1.SAL AS EMP_SAL, E2.ENAME AS
MANAGER_NAME, E2.SAL AS MANAGER_SAL
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2. EID;

Write a query to display Ename, Manager’s name along with their department no if the
employee is working as Clerk.
SELECT E1.ENAME, E1.DNO, E2.ENAME AS MANAGER_NAME, E2.DNO AS
MANAGER_DNO
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID AND E1.JOB = ‘CLERK’;

Write a query to display employee name, manager’s job if manager is Analyst.


SELECT E1.ENAME, E2.JOB AS MANAGER_JOB
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID AND E2.JOB = ‘ANALYST’;

Write a query to display employee name, manager’s name along with both their jobs if
employee and manager are working as same designation.
SELECT E1.ENAME, E2.ENAME, E1.JOB, E2.JOB
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID AND E1.JOB = E2.JOB;

Write a query to display employee name, employee salary, manager’s name, manager’s
salary if manager is earning more than employee.
SELECT E1.ENAME, E1.SAL, E2.ENAME, E2.SAL
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER=E2.EID AND E2.SAL > E1.SAL;
Write a query to display employee name, manager’s name along with manager’s
commission if manager earns commission.
SELECT E1.ENAME, E2.ENAME, E2.COMMISSION
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID AND E2.COMMISSION IS NOT NULL;

Note – To join n number of tables, we need to write (n-1) number of JOIN_CONDITIONS.

Natural Join – It behaves as Inner Join as well as Self Join. If there is any relation between two tables
then it behaves as Inner Join, else Cross(Cartesian) Join.
Syntax:
ANSI-
SELECT COLUMN_NAME
FROM TABLE1 NATURAL JOIN TABLE2;

EMPLOYEE
ENAME DNO
A 3
B 1
C null

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3

If we do EMPLOYEE NATURAL JOIN DEPARTMENT Resultant Table-


ENAME DNO DNO DNAME
A 3 3 D3
B 1 1 D1

EMPLOYEE
ENAME JOB
A Analyst
B Clerk
C Accounts

DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3
If we do EMPLOYEE NATURAL JOIN DEPARTMENT Resultant Table-
ENAME JOB DNO DNAME
A Analyst 1 D1
A Analyst 2 D2
A Analyst 3 D3
B Clerk 1 D1
B Clerk 2 D2
B Clerk 3 D3
C Accounts 1 D1
C Accounts 2 D2
C Accounts 3 D3

Write a query to display Ename and Department name for all employees.
SELECT ENAME, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DNO = DEPARTMENT.DNO;

Write a query to display Ename and Manager’s name for all employees.
SELECT E1.ENAME, E2.ENAME
FROM EMPLOYEE E1, EMPLOYEE E2
WHERE E1.MANAGER = E2.EID;

Write a query to display Ename, Department name and Manager’s name


SELECT E1.ENAME, D1.DNAME, E2.ENAME
FROM EMPLOYEE E1, EMPLOYEE E2, DEPARTMENT D1
WHERE E1.DNO = D1.DNO AND E1.MANAGER = E2.EID;

Write a query to display Ename, Manager’s name and Manager’s department name.
SELECT E1.ENAME, E2.ENAME, D2.DNAME
FROM EMPLOYEE E1, EMPLOYEE E2, DEPARTMENT D2
WHERE E2.DNO = D2.DNO AND E1.MANAGER = E2.EID;

Write a query to display Ename, Employee department name, Manager’s name and Manager’s
department name.
SELECT E1.ENAME, D1.DNAME, E2.ENAME, D2.DNAME
FROM EMPLOYEE E1, EMPLOYEE E2, Department D1, department D2
WHERE E1.MANAGER = E2.EID AND E1.DNO = D1.DNO AND E2.DNO = D2.DNO;

Write a query to display Ename, department name and manager’s name if employee and
manager are working in same job and earning same salary.
SELECT E1.ENAME, D1.DNAME, E2.ENAME
FROM EMPLOYEE E1, EMPLOYEE E2, Department D1
WHERE E1.MANAGER = E2.EID AND E1.DNO = D1.DNO AND E1.JOB = E2.JOB AND E1.SAL =
E2.SAL;
Single Row Functions – When we pass one input it will process and give output then will go for next
input. We can use other column names in the SELECT clause with these functions unlike Multi Row
Functions. We have 16 Single Row Functions-
i. LENGTH()
ii. CONCAT()
iii. UPPER()
iv. LOWER()
v. INITCAP()
vi. REVERSE()
vii. SUBSTR()
viii. INSTR()
ix. REPLACE()
x. MOD()
xi. TRUNC()
xii. ROUND()
xiii. MONTHS-BETWEEN()
xiv. LAST-DAY()
xv. TO-CHAR()
xvi. NVL()
LENGTH() – Used to count the number of characters in a given string.
Syntax: LENGTH(‘String’)

Write a query to display to count the number of characters in SMITH.


SELECT LENGTH(ENAME)
FROM EMPLOYEE
WHERE ENAME = ‘SMITH’;

Write a query to display to count the number of characters in MILLER.


SELECT LENGTH(‘MILLER’)
FROM DUAL;
//DUAL is a dummy table that we can use if we don’t know the table name, since we have to
mandatorily give a dummy table name so we can use DUAL

Write a query to display to count the number of characters in HELLOWORLD.


SELECT LENGTH(‘HELLOWORLD’)
FROM DUAL;

CONCAT() – Used to join the given two strings.


Syntax: CONCAT(‘String1’ , ’String2’)

Write a query to concat Mr and SMITH.


SELECT CONCAT(‘Mr’ , ‘SMITH’)
FROM DUAL;

UPPER() – Converts the given string to upper case.

LOWER() – Converts the given string to lower case.


INITCAP() – Converts the first letter of the String to capital and remaining will be in
lowercase.

REVERSE() – Reverses the String.

SELECT REVERSE(‘SMITH’)
FROM DUAL;
//Output – HTIMS

SUBSTR() – Extract a part of a string from the given string.


Syntax: SUBSTR(‘STRING’, position , [length])
length is optional so we can also just write SUBSTR(‘STRING’ , position) Here it will consider
till the end of the string if we don’t mention length

-7 -6 -5 -4 -3 -2 -1
Q S P I D E R
1 2 3 4 5 6 7

SUBSTR(‘QPSIDER’ , 3 , 3) // PID
SUBSTR(‘QSPIDER’ , 2) // SPIDER (When we don’t mention length it prints till the end)
SUBSTR(‘QSPIDER’ , 1 , 6) // QSPIDE
SUBSTR(‘QSPIDER’ , 0 , 3) // QSP
SUBSTR(‘QSPIDER’ , 6 , 6) // ER
SUBSTR(‘QSPIDER’ , -2 , 1) // E
SUBSTR(‘QSPIDER’ , -5 , 3) // PID
SUBSTR(‘QSPIDER’ , -1) // R
SUBSTR(‘QSPIDER’ , 8 , 2) //NULL
SUBSTR(‘QSPIDER’ ,- 8 , 2) //NULL

Display first three characters of employee name.


SELECT SUBSTR(ENAME , 1, 3)
FROM EMPLOYEE;

Display the last three characters of employee name.


SELECT SUBSTR(ENAME , -3)
FROM EMPLOYEE;
OR
SELECT SUBSTR(ENAME , -3, 3)
FROM EMPLOYEE;

Display the first half of the employee name.


SELECT SUBSTR(ENAME, 1 , LENGTH(ENAME)/2)
FROM EMPLOYEE;
//If the length is odd then LENGTH(ENAME)/2 will return only int
Display the second half of the name.
SELECT SUBSTR(ENAME , LENGTH(ENAME)/2 +1)
FROM EMPLOYEE;
//If string is SMITH then the cursor will start from I as length is 5 and length/2 + 1 will give 3

REPLACE() – Used to replace a given string with another string.


Syntax: REPLACE(‘ORIGINALSTRING’ , ‘STRING’ , [‘NEWSTRING’])
//In the ORIGINALSTRING, the STRING will be replaced by NEWSTRING. NEWSTRING is
optional, if not mentioned, will be replaced by null

REPLACE(‘BANANA’ , ‘A’ , ‘C’) // BCNCNC


REPLACE(‘BANANA’ , ‘N’ , ‘ABC’) // BAABCAABCA
REPLACE(‘OPPO’ , ‘O’ , ‘J’) // JPPJ
REPLACE(‘BANANA’ , ‘A’) // BNN
REPLACE(‘OPPO’ , ‘O’ , ‘$’) // $PP$

Write a query to display number of times character ‘A’ is present in BANANA.


SELECT LENGTH(‘BANANA’) – LENGTH(REPLACE(‘BANANA’ , ‘A’));
//6 – LENGTH(‘BNN’) = 6 – 3 = 3

INSTR() – Used to obtain position of a string in original string. If present then returns the
index, else returns 0
Syntax: INSTR(‘ORIGINAL_STRING’,’STRING’,POSITION,[OCCURENCE]);
OCCURENCE is optional, 1 by default
INSTR(‘BANANA’,’A’,1,1); // 2
INSTR(‘BANANA’,’A’,2,1); // 2
INSTR(‘BANANA’,’A’,1,2); // 4
INSTR(‘BANANA’,’A’,1,4); // 0
INSTR(‘BANANA’,’A’,4,2); // 6
INSTR(‘BANANA’,’A’,2); // 2
INSTR(‘BANANA’,’G’,1,1); // 0
INSTR(‘BANANA’,’NA’,2,2); // 5
INSTR(‘BANANA’,’ANA’,1,2); // 4

MOD() – Used to obtain the mod of two numbers.


Syntax: MOD(m,n)

SELECT MOD(5,2)
FROM DUAL;
// 1

Write a query to display Ename of the employee who can earn salary in multiples of 3.
SELECT ENAME
FROM EMPLOYEE
WHERE MOD(SAL,3) = 0;
Write a query to display details of employee who is having Odd Employee ID.
SELECT *
FROM EMPLOYEE
WHERE MOD(EID,2) = 1;

ROUND() – Used to round off the number to the nearest whole number.
Syntax: ROUND(NUMBER);

ROUND(5.6); // 6
ROUND(5.5); // 6
ROUND(5.4); // 5
ROUND(9.9); // 10
ROUND(9.4); // 9

TRUNC() – Similar to round but will always round off the given number to the lower value.
Syntax: TRUNC(NUMBER);

TRUNC(5.6); // 5
TRUNC(5.4); // 5
TRUNC(9.9); // 9

Date Commands –
SYSDATE – Returns today’s date.
SELECT SYSDATE
FROM DUAL;
// 31-MAR-2023

CURRENT_DATE – Returns today’s date, same as SYSDATE


SELECT CURRENT_DATE
FROM DUAL;
//31-MAR-2023

SYSTIMESTAMP – Returns today’s date, time & timezone


SELECT SYSTIMESTAMP
FROM DUAL;
// 31-MAR-2023 12:12:30 PM +05:30

Write a query to display two days ago date.


SELECT CURRENT_DATE – 2
FROM DUAL;
//29-MAR-2023

MONTHS_BETWEEN() – Used to obtain the number of months present between given two
dates.
Syntax: MONTHS_BETWEEN(‘DATE1’,’DATE2’); //DATE2-DATE1
SELECT MONTHS_BETWEEN(CURRENT_DATE,HIREDATE)
FROM EMPLOYEE
WHERE EMPID = 3; //Prints HIREDATE – CURRENT_DATE will print -10 if hired 10 months ago
SELECT MONTHS_BETWEEN(HIREDATE, CURRENT_DATE)
FROM EMPLOYEE
WHERE EMPID = 3;
Prints CURRENT_DATE – HIREDATE will print 10 if hired 10 months ago

LASTDAY() – Used to obtain the last date in the month of the particular date.
Syntax: LASTDAY(DATE);

SELECT LASTDAY(SYSDATE)
FROM DUAL;
// 31-MAR-2023

TO_CHAR() – Used to convert the given date into String format based on the given model.
Syntax: TO_CHAR(DATE,’FORMAT_MODELS’);

FORMAT_MODELS are-
YEAR – Will print the year in words like twenty twenty three
YYYY – Will print the year in numerical value like 2023
YY – 23
MONTH – Will print the month in words like MARCH
MON – MAR
MM – 03
DAY – FRIDAY
DY – FRI
DD – 05
D–5
HH24 – 14 //Only hours in 24 hour format
HH12 – 02 //Only hours in 12 hour format, kinda useless better to use HH24
MI – 29 //Only minutes
SS – 30 //Only seconds

HH12:MI:SS
// 12:31:53

DD-MM-YY
// 31-03-23

MM-DD-YYYY
//03-31-2023

Write a query to display details of employees who were hired on SUNDAY.


SELECT *
FROM EMPLOYEE
WHERE TO_CHAR(HIREDATE,’DAY’) = ‘SUNDAY’;
Write a query to display details of employees hired on MONDAY at 10 AM.
SELECT *
FROM EMPLOYEE
WHERE TO_CHAR(HIREDATE,’DAY’) = ‘MONDAY’ AND TO_CHAR(HIREDATE,’HH24’) = 10;

NVL() – NULL VALUE LOGIC . Used to eliminate the side effects of using NULL in
arithmetic operations.
Syntax: NVL(ARG1,ARG2);
ARG1 is any column or expression which can result NULL
ARG2 is any numeric value which will be substituted if the ARG1 result is NULL . If ARG1
is not NULL then ARG1 value will be considered.

EMPLOYEE
ENAME SAL COMMISSION
A 500 100
B 1000 NULL
C 2000 200
D 2500 NULL
Resultant table for total salary of employees(including commission)
SELECT ENAME, SAL+COMMISSION
FROM EMPLOYEE;
ENAME SAL+COMMISSION
A 600
B NULL
C 2200
D NULL
//As when we perform any operation with NULL, we get NULL

To avoid this issue, we use NVL-


SELECT ENAME, SAL+NVL(COMMISSION,0)
FROM EMPLOYEE;
Now the result will be-
ENAME SAL+COMMISSION
A 600
B 1000
C 2200
D 2500

Data Definition Language – DDL is used to construct an object in the database and deals with the
structure of object. It has five statements-
CREATE
RENAME
ALTER
TRUNCATE
DROP

CREATE – Used to build & construct an object, object is nothing but a table.
Syntax : CREATE TABLE TABLE_NAME(COLUMN1 DATA_TYPE CONSTRAINT_TYPE, COLUMN2
DATA_TYPE, CONSTRAINT_TYPE.......COLUMN_N, DATA_TYPE, CONSTRAINT_TYPE);
Constraints are not mandatory.

CREATE TABLE CUSTOMER(


CID NUMBER(2) PRIMARY KEY,
CNAME VARCHAR(10),
CONTACT_NO NUMBER(10) NOT NULL CHECK(LENGTH(CONTACT_NO) = 10),
ADDRESS VARCHAR(50)
);

To check the description of the table, we use DESC. Description means the columns, their data
type & constrains associated with each column.
Syntax: DESC TABLE_NAME;

To add a foreign key(which is a primary key in some other table) in our table, we mention like-
CREATE TABLE TABLE_NAME(COLUMN1 DATA_TYPE CONSTRAINT_TYPE, COLUMN2 DATA_TYPE,
CONSTRAINT_TYPE.......COLUMN_N, DATA_TYPE, FOREIGN KEY REFERENCES
PARENT_TABLE_NAME(COLUMN_NAME));

CREATE TABLE STUDENT(


SID NUMBER(2) PRIMARY KEY,
SNAME VARCHAR(10),
CID NUMBER(2) FOREIGN KEY REFERENCES CUSTOMER(CID)
);
//Here we are using the primary key CID of CUSTOMER as foreign key in STUDENT table.

We can write the above query also like-


CREATE TABLE STUDENT(
SID NUMBER(2) PRIMARY KEY,
SNAME VARCHAR(10),
CID NUMBER(2) FOREIGN KEY(CID) REFERENCES CUSTOMER(CID)
);
//This is the 2nd way of using FOREIGN KEY reference

RENAME – Used to change the name of the object/table name.


Syntax: RENAME TABLE_NAME TO NEW_TABLE_NAME;
Eg: RENAME CUSTOMER TO CUST;

ALTER – Used to modify the structure(ADD/DELETE COLUMNS, change column names, data
type, constraints) of the table.
Syntax: ALTER TABLE TABLE_NAME
ADD COLUMN_NAME DATA_TYPE CONSTRAINT_TYPE;
Eg: ALTER TABLE CUST
ADD EMAILID VARCHAR(15);

Syntax for dropping column: ALTER TABLE TABLE_NAME


DROP COLUMN COLUMN_NAME;
Eg: ALTER TABLE CUST
DROP COLUMN EMAILID;

Syntax for renaming the column: ALTER TABLE TABLE_NAME


RENAME COLUMN COLUMN_NAME TO NEW_COLUMN_NAME;
Eg: ALTER TABLE CUST
RENAME COLUMN CONTACTNO TO PHONENO;

Syntax for modifying the data type of any column: ALTER TABLE TABLE_NAME
MODIFY COLUMN_NAME NEW_DATA_TYPE;
Eg: ALTER TABLE CUST
MODIFY CNAME CHAR(10);

Syntax to modify the constraint: ALTER TABLE TABLE_NAME


MODIFY COLUMN_NAME EXISTING_DATA_TYPE
NEW_CONSTRAINT;
//Will add one more constraint, replaces the old if needed
Eg: ALTER TABLE CUST
MODIFY ADDRESS VARCHAR(50) NOT NULL;

Syntax to delete all the constraints of a column: ALTER TABLE Persons


DROP CONSTRAINT PNAME;

TRUNCATE – Used to remove all the records/rows from a table permanently.


Syntax: TRUNCATE TABLE TABLE_NAME;
Eg: TRUNCATE TABLE CUST;

DROP – Used to remove the table from the database.


Syntax: DROP TABLE TABLE_NAME;
Eg: DROP TABLE CUST;
//If the primary key of this table is being used a foreign key in some other table then we cannot
delete this table.

Syntax to recover a dropped table: FLASHBACK TABLE TABLE_NAME


TO BEFORE DROP;
Eg: FLASHBACK TABLE CUST
TO BEFORE DROP;

Syntax to delete a dropped table even from bin folder: PURGE TABLE TABLE_NAME;
Eg: PURGE TABLE CUST;
We can directly use this command to directly delete the table from the database, like
(Shift+Delete) in Windows.

Data Manipulation Language – Used to manipulate the object for insertion, delete and update.
Three statements-
INSERT
UPDATE
DELETE
INSERT – Used to create records in the table.
Syntax: INSERT INTO TABLE_NAME VALUES(VALUE1, VALUE2, VALUE3……….VALUE_N);
Eg: INSERT INTO CUSTOMER VALUES(1,’Bholu’,45……………..);

UPDATE – Used to modify records in a table.


Syntax: UPDATE TABLE_NAME
SET COLUMN_NAME = NEW_VALUE
WHERE STATEMENT;
Eg: UPDATE CUSTOMER
SET PHONENO = 9231929319
WHERE CNAME = ‘Bholu’;

DELETE – Used to delete the whole record from a table.


Syntax: DELETE FROM TABLE_NAME
WHERE STATEMENT;
Eg: DELETE FROM CUSTOMER
WHERE CNAME=’Bholu’;

Q. Differentiate between TRUNCATE & DELETE.


Ans:
TRUNCATE DELETE
Belongs to DDL Belongs to DML
Removes all the records from the table Removes a particular record from the table
Auto-commit No Auto-commit

Transaction Control Language(TCL) – This is used to control the transaction done on database.
Transaction means performing DML operations on DB. Three statements-
COMMIT
ROLLBACK
SAVEPOINT

COMMIT – Used to save the transaction into the database.


Syntax: COMMIT;
Eg: INSERT INTO T1 VALUES(‘ABC’,5000);
COMMIT;
//This will save the queries whatever we have typed in the database. Won’t reflect the
functionality of the queries into the database, just save the queries into the database to
avoid retyping of the queries. Works only on DML queries.

ROLLBACK – Used to obtain only the saved data from the database. Will bring back all the
queries till the last COMMIT.
Syntax: ROLLBACK;

SAVEPOINT – Used to mark the position or restoration points.


Syntax: SAVEPOINT S1;
Eg: INSERT INTO T1 VALUES(‘XYZ’,1000);
SAVEPOINT S1;
INSERT INTO T1 VALUES(‘PQR’,300);
INSERT INTO T1 VALUES(‘ABC’,500);
SAVEPOINT S2;
INSERT INTO T1 VALUES(‘JKL’,1000);
INSERT INTO T1 VALUES(‘BAR’,500);
SAVEPOINT S3;
INSERT INTO T1 VALUES(‘JUIP’800);

ROLLBACK TO S3;
//Will fetch the values between Savepoint S2 & Savepoint S3, so-
INSERT INTO T1 VALUES(‘JKL’,1000);
INSERT INTO T1 VALUES(‘BAR’,500);
will be fetched.

DATA CONTROL LANGUAGE – Used to control the flow of data between the users. Two statements-
GRANT
REVOKE

GRANT – Used to give permission to a user.


Syntax: GRANT SQL_STATEMENT
ON TABLE_NAME
TO USER_NAME;
//GRANT, ON, TO are keywords

REVOKE – Used to take back the permission from the user.


Syntax: REVOKE SQL_STATEMENT
ON TABLE_NAME
FROM USER_NAME;

Eg: USER1 and USER2 are two different databases.


USER1 = ‘SCOTT’ USER2 = ‘HR’

EMPLOYEE
ENAME SAL
A 1000
B 2000 SELECT * FROM
SCOTT.EMPLOYEE;
//Since EMPLOYEE doesn’t exist
in USER2 DB, we have to
mention the USER1 DB name to
access EMPLOYEE table
GRANT SELECT
ON EMPLOYEE
TO HR; //Granting permission to HR user to execute SELECT query on EMPLOYEE table

REVOKE SELECT
ON EMPLOYEE
FROM HR; //Revoke the permission from HR so now if HR tries to fetch data from
EMPLOYEE, it won’t work
Note – GRANT & REVOKE can only be used to grant permission for DQL queries i.e SELECT
queries.

Co-related subquery – A query written inside another query such that the outer query and the inner
query are dependent on each other is called co-related subquery. In a normal subquery inner query has
no dependency on outer query but here both are dependent on each other. Here the outer query
executes partially and generated some output, then this output will be send as input to the inner query
then inner query executes completely to generate some output which will then be sent as input to the
outer query which will be executed completely to generate the final output.

Note – JOIN condition is must and must be written in inner query.


Co-related subquery works on the principal of subquery and JOIN.

Subquery Co-related subquery


Inner query executes first Outer query executes first
Outer query is dependent on inner query Outer & inner both are dependent on each other
JOIN condition is not mandatory JOIN condition is mandatory
Outer query executes one Outer query executes twice

Eg: Write a query to display department name in which there are employees working.
SELECT D1.DNAME
FROM DEPARTMENT D1
WHERE D1.DNO IN (SELECT E1.DNO
FROM EMPLOYEE E1
WHERE D1.DNO = E1.DNO); //Output D1,D2,D3 (Outer query will be executed partially to
know that DNO has to be matched from DEPARTMENT table, then inner query will be executed
to give all the matching DNO between EMPLOYEE & DEPARTMENT table, then this output will be
used as input for the remaining execution of outer query).
Write a query to display DNAME in which there are no employees working.
SELECT D1.DNAME
FROM DEPARTMENT D1
WHERE D1.DNO NOT IN (SELECT E1.DNO
FROM EMPLOYEE E1
WHERE D1.DNO = E1.DNO); //Output D4

Definitions-

Attributes – Properties which define the entity/objects.

Key Attributes – Also called as Candidate key. An attribute which is used to uniquely identify a record is
called a Key attribute. Eg: Phone No, PAN No
Non-key Attributes – Attributes other than Key attributes. Eg: Name, Age, Gender

Prime Key Attributes – Among the key attributes, an attribute is chosen to uniquely identify a record is
called Prime key attribute. Eg: Phone No

Non-prime key attributes – Attributes other than prime key attributes.

Composite key attributes – Combination of two or more non-key attributes used to uniquely identify a
record. Eg: Name + Age + DOB When we don’t have any key attribute, we go with composite key

Super key attribute – Set of all key attributes like {phone no, emailed, PAN No.}

Foreign Key Attribute – Attribute used to behave as attribute for another entity to represent the
relationship. Eg: DepartmentNo will form the relationship between Employee table & Department table.

Functional Dependency – There exists a dependency such that an attribute in a relation determines
another attribute. Three types-

Total Functional Dependency


Partial FD
Transitive FD

Total FD – If an attribute in a relation determines all the other attributes, it is known as Total FD.
If all the attributes are dependent on a single attribute, it is called as Total FD.
Let’s consider an Employee table having EmpID, EName, Salary, DOB
Now if EmpID is a key attribute, by using EmpID, we can get EName, Salary, DOB. So, EName, Salary,
DOB all completely depend on EmpID, so EmpID is a prime key attribute. So this is Total FD.

Partial FD – There exists a dependency such that a part of a composite key attribute determines another
attribute uniquely. Let’s consider a Customer table having CName, address, PhoneNo, EmailID. We can
have two same PhoneNo or same EmailID if two people belong to same family. So these cannot be
considered as Key Attributes. So we will go with a combination of non-key attributes to form a
composite key attribute. So if we make PhoneNo & EmailID as composite attribute then CName, Address
will be dependent on this combination of PhoneNo & EmailID and not on only any one. They are partially
dependent on PhoneNo & Partially on EmailID.
Transitive FD – There exists a dependency such that an attribute is determined by a non-key attribute
which is in-turn determined by a key attribute. Let’s take Customer table example having CID, CName,
PIN-Code, City. Here, CID will be unique so it’s a key attribute. Now each city will have a unique PIN-
Code, so city is dependent on PIN-Code and each PIN-Code is dependent on CID. So City is dependent on
CID. So if -> A depends on B and B depends on C. Thus A depends on C

Redundancy – Repetition of unwanted data is called Redundancy.


Anomalies – Side effects caused during DML operations are called as Anomalies.

Major difference between Total, Partial & Transitive FD-


In Total FD, there will be no redundancy & no Anomalies. In partial FD, both redundancy & anomalies
exist. In Transitive FD, both redundancy & anomalies exist.
Normalization – It is the process of reducing a large table into a smaller table by removing the
redundancies and anomalies by identifying the FDs is known as Normalization. Nothing but reducing a
table to it’s normal form(A table without redundancies & anomalies)
Levels of Normal Form-
1NF
2NF
3NF
BCNF(Boyce-Codd Normal Form)

1NF – First Normal Form. No duplicate records, multi-value data should not be present. Let us consider
an example like if I have a table QSpiders having CandidateID, CName and courses

QSpiders
CandidateID CName Courses
1 A Java
2 B Java, SQL
3 C MT, SQL
1 A MT

To achieve 1NF, the above table will be broken down into-

CandidateID CName C1 C2 C3
1 A Java MT
2 B Java SQL
3 C MT SQL

2NF – Second Normal Form. The table should be in 1NF and should not have Partial FD. Only Total FD is
allowed. So, atleast one prime key attribute should exist.
Let’s consider an Employee table having EmpID, EName, Salary, DeptNo, DeptName, Location
Here, EName & Salary are dependent on EmpID and DeptName & Location are dependent on DeptNo.
So EmpID & DeptNo are combination of two key attributes on which other four attributes are
depending. So partial FD exists.
To achieve 2NF, the above table will be broken into-
Employee – EmpID, EName, Salary, DeptNo Department – DeptNo, DeptName, Location
DeptNo needs to be added in Employee table to connect both the tables.

3NF – Third Normal Form. Should exist in 2NF & should not have Transitive FD.
Let’s consider an Employee table having EmpID, EName, Salary, Commission, PIN-Code, State, Country
Here Transitive FD exists as State, Country depend on PIN-Code & PIN-Code depends on EmpID so State,
Country depend on EmpID.
To achieve 3NF, the above table will be broken down into-
Employee – EmpID, EName, Salary, Commission, PIN-Code Location - PIN-Code, State, Country

BCNF – Advanced version of 3NF. A table is in BCNF if it’s in 3NF and for every FD, X->Y(Y is dependent
on X) so X will be considered as super key.
Let’s consider an employee table-
Employee having attributes EmpID, EmpName, Commission, Pin-Code, State, Country, DeptNo,
DeptName, Location

To achieve 2NF we’ll do EmpID -> EmpName, Commission, Pin-Code, State, Country, DeptNo(Foreign
Key)
And DeptNo -> DeptName, Location

To achieve 3NF, we’ll do EmpID -> EmpName, Commission, Pin-code, DeptNo & Pin-code -> State,
Country
& DeptNo -> DeptName, Location

We found that EmpID should be considered as the super key and all other attributes functionally depend
on EmpID. So to achieve BCNF, for the above example, we’ll have 3 tables, Employee, Pin-code and
Department.

ER Diagram – Entity Relationship Diagram. Describes the structure of the database with the help of a
diagram. Three main components of an ER Diagram-
Entity
Attributes
Relationship

Notations –

Represents Entity means it represents any table


Eg:
Employee

Represents Attributes means the attributes of a table


Eg:
EID
Represents Relationship means relationship between two entities

Eg: Employee Works for Department

Links attributes to entity or entity set to relationship


set. Depicted above

Represents multi-valued attributes i.e any attribute having more than


one value. Eg: PhoneNo, EmailId

PhoneNo

Represents Derived Attributes means an attribute that can be derived


from other attributes. Eg: Age can be derived from DOB.

Age

Represents total participation of entity

Employee Works for Department

Represents weak entity means an entity that depends on another


entity. Weak entity doesn’t contain any key attributes. Eg: Installment
entity would depend on Loan entity

Installment Loan
Represents weak relationship means the relationship between weak &
strong entity. Eg: Loan depends on Customer

Loan Borrows Customer

Represents composite attributes means attributes composed of many


other attributes(Different from composite key attributes). Eg: Name
attribute is combination of first name, middle name & last name

First Name Last Name

Name

Represents key Attributes/ single valued attribute.

EName EID Sal

Employee

User Requirement: I have a company with multiple departments and an employee has to work in a
department but any department. A department can have any number of employees. I want a
department to be empty for a period of time.
Participation – There can be two participation, Minimum & Maximum. Minimum means min no of times
that entity takes part in a relation. Maximum means max no of times that entity takes part in a relation.

Cardinality Number – The maximum participation is known as Cardinality number. So for an employee
cardinality number will be 1. And for a department cardinality number will be N. Represented by Cn.

Cardinality Ratio/Relationship Ratio – Four types-


One:One (1:1)
One:Many (1:N)
Many:One (N:1)
Many:Many (N:N)

Total Participation – If all the entities are taking part in a relation then it is referred to as total
participation.

Partial Participation – If any of the entities is not taking part or partially participating in more than one
entity then it is referred to as partial participation.
ER Diagram for Employee-Department table – Let’s consider there is only one row in Employee table &
multiple rows in Department table.
Attributes of Employee – EID, EName, Sal, Commission
Attributes of Department – DNo, DName, Location
EName Sal Commission DNo DName Location

EID

Employee Works in Department

Cn = 1 Cn=N
Cardinality Ratio = 1:N

If an employee is allowed to work in multiple departments above, then it won’t be total participation
but partial participation.

Rules –
1. For the ratio 1:1, 1:N and N:1, we don’t need to create a new table to store the relationships.
The primary key of the table whose cardinality is N is chosen to be a foreign key in the table whose
cardinality is 1.
2. For the ratio N:N, we must create a new table to store the relationships. The primary key of both
the tables will be chosen to be the foreign key of new table.

View – View is a virtual table. Used so that the user cannot directly access the main table in the DB. The
user can work on the view table.
Syntax: CREATE VIEW VIEW_NAME AS
SELECT * FROM TABLE_NAME
WHERE CONDITION;

You might also like