SQL Notes
SQL Notes
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
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.
If we want to display all columns but want to add some expression as well then we can do like-
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
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 *
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;
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’)
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
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’;
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;
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
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
SELECT SAL
FROM EMP
GROUP BY SAL
HAVING COUNT(SAL) > 1; //Fetches repeated salary
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
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 *
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
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 *
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
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 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’));
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;
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
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’;
DEPARTMENT
DNO DNAME
1 D1
2 D2
3 D3
If we do EMPLOYEE LEFT |OUTER| JOIN DEPARTMENT, then the resultant will be-
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
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
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;
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 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;
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
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, 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’)
SELECT REVERSE(‘SMITH’)
FROM DUAL;
//Output – HTIMS
-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
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
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
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
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
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.
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));
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 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 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……………..);
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
ROLLBACK – Used to obtain only the saved data from the database. Will bring back all the
queries till the last COMMIT.
Syntax: ROLLBACK;
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
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.
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-
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
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 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
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
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 –
PhoneNo
Age
Installment Loan
Represents weak relationship means the relationship between weak &
strong entity. Eg: Loan depends on Customer
Name
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.
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
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;