You are on page 1of 45

SQL Intermediate

December 2018
Agenda
This Presentation will provide you an overview of the following:
 SQL Joins
 SQL Sub Queries
 NULL in SQL
 SQL Functions
 Grouping and Aggregation
 Number functions
 Text functions
 Analytic functions
 Conditional functions
 Date functions
SQL Joins

There are different types of joins available in SQL:


INNER JOIN: Returns rows when there is a match in both tables.
OUTER JOIN: The joined table retains each record—even if no other
matching record exists.
LEFT OUTER JOIN Returns all rows from the left table, even if there are
no matches in the right table.
RIGHT OUTER JOIN Returns all rows from the right table, even if there
are no matches in the left table.
FULL OUTER JOIN Returns rows when there is a match in one of the
tables. It combines the effect of applying both left and right outer joins.
CARTESIAN JOIN : Returns the Cartesian product of the sets of records
from the two or more joined tables.
SELF JOIN: It is used to join a table to itself as if the table were two tables,
temporarily renaming at least one table in the SQL statement.

3
3
SQL JOINS Continued…

4
4
Inner Join

Product Company

PName Price Category Manufacturer Cname StockPrice Country


Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan
SingleTouch $149.99 Photography Canon Hitachi 15 Japan
MultiTouch $203.99 Household Hitachi

SELECT PName, Price


FROM Product, Company
WHERE Manufacturer=Cname AND Country=‘Japan’
AND Price <= 200
PName Price
SingleTouch $149.99
Same as

SELECT PName, Price


FROM Product JOIN Company ON
(Manufacturer=Cname AND Country=‘Japan’
AND Price <= 200) 5
5
Left Outer Join

Product
Company
PName Price Category Manufacturer
Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks
GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks
Canon 65 Japan
SingleTouch $149.99 Photography Canon
Hitachi 15 Japan
MultiTouch $203.99 Household Samsung

SELECT PName, Price ,


Cname
FROM Product LEFT OUTER
JOIN COMPANY ON Pname Price Cname
(Manufacturer=Cname) Gizmo $19.99 GizmoWorks

Powergizmo $29.99 GizmoWorks

SingleTouch $149.99 Canon

MultiTouch $203.99 (null)

6
6
Right Outer Join

Product
Company
PName Price Category Manufacturer Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA

Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan


Hitachi 15 Japan
SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Samsung

SELECT PName, Price ,


Cname
FROM Product RIGHT
OUTER JOIN COMPANY ON Pname Price Cname
(Manufacturer=Cname) Gizmo $19.99 GizmoWorks

Powergizmo $29.99 GizmoWorks

SingleTouch $149.99 Canon

(null) (null) Hitachi

7
7
Full Outer Join

Product
Company
PName Price Category Manufacturer Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA

Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan


Hitachi 15 Japan
SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Samsung

SELECT PName, Price ,


Cname
FROM Product FULL OUTER
JOIN COMPANY ON Pname Price Cname
(Manufacturer=Cname) Gizmo $19.99 GizmoWorks

Powergizmo $29.99 GizmoWorks

SingleTouch $149.99 Canon

(null) (null) Hitachi

MultiTouch $203.99 (null)


8
8
Exercise
 Consider the below tables
Employees Departments
E_ID E_MGR E_SAL E_DNO D_NO D_NAME LOCATION_ID
100 102 10000 10
10 HR 1
101 105 20000 20
20 ACCOUNT 2
102 100 12000 30
40 FINANCE 4
103 104 11000 40
50 MARKETING 5
110 101 15000 70
60 DELIVERY 6
 For these tables write a query to display Employee id, Department name,
location id for the employees having salary lesser than 12000.
 For these tables write a query to display Employee id, Manager id, Department
name for all departments.
 For these tables write a query to display Employee id, Manager id, Location id
for all employees.
 For these tables write a query to display Employee id, Manager id, Location id
and department name for all employees and departments .
9
9
Subqueries Returning Relations

Company(name, city)
Product(pname, maker)
Purchase(id, product, buyer)

Return cities where one can find companies that manufacture


products bought by Joe Blow

SELECT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);

10
Correlated Queries

Movie (title, year, director, length)


Find movies whose title appears more than once.

correlation

SELECT DISTINCT title


FROM Movie AS x
WHERE year <> ANY
(SELECT year
FROM Movie
WHERE title = x.title);

11
NULLS in SQL
 Whenever we don’t have a value, we can put a NULL
 Can mean many things:
 Value does not exists
 Value exists but is unknown
 Value not applicable
 Etc.
 The schema specifies for each attribute if can be null (nullable
attribute) or not
 How does SQL cope with tables that have NULLs ?

12
Null Values
Can test for NULL explicitly:
 x IS NULL
 x IS NOT NULL

SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL

13
Example
Emp_Id EMP_Nam Salary Dept_Id Age
e
1 Mark 1000 10 34
2 John 2000 (null) 33
3 Charlie 2345 20 32
4 Kathy 2240 30 40
Find employees which are not linked to any
department?

SELECT * FROM EMPLOYEES WHERE DEPT_ID IS


NULL;

Emp_Id EMP_Nam Salary Dept_Id Age


e
2 John 2000 (null) 33
14
14
Two Types of SQL Functions

Functions

Single-row Multiple-row
functions functions

15
Single-Row Functions

Character

General Number
Single-row
functions

Conversion Date

16
Single-Row Functions
 Manipulate data items

 Accept arguments and return one value

 Act on each row returned

 Return one result per row

 May modify the datatype

 Can be nested

function_name (column|expression, [arg1, arg2,...])

17
SQL Functions

Aggregation

SELECT avg(price) SELECT count(*)


FROM Product FROM Product
WHERE maker=“Toyota” WHERE year > 1995

SQL supports several aggregation operations:

sum, count, min, max, avg

Except count, all aggregations apply to a single attribute

18
Aggregation: Count

COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)


FROM Product
WHERE year > 1995

We probably want:

SELECT Count(DISTINCT category)


FROM Product
WHERE year > 1995

19
Aggregation: Grouping

Product Date Price Quantity


TotalQuantit
Bagel 21/10/2013 1 20 Product
Bagel 03/10/2013 1.50 20
y
Banana 10/10/2013 0.5 10 Bagel 40
Banana 25/10/2013 1 10
Banana 20

SELECT product, price*quantity AS TotalQuantity


FROM Purchase
WHERE date > ‘01/10/2013’
GROUP BY product

20
20
Grouping and Aggregation

1. Compute the FROM and WHERE clauses.

2. Group by the attributes in the GROUPBY

3. Compute the SELECT clause: grouped attributes and aggregates.

21
Grouping and Aggregation

Purchase(product, date, price, quantity)


Find total sales after 10/1/2005 per product.
Product Date Price Quantity
Bagel 21/10/2013 1 20
Bagel 03/10/2013 1.50 20
Banana 10/10/2013 0.5 10
Banana 25/10/2013 1 10

SELECT product, Sum(price*quantity) AS TotalSales


FROM Purchase
WHERE date > ’10-JAN-2013’
GROUP BY product

Product TotalSales
Bagel 50
Banana 15
22
HAVING Clause

Same query, except that we consider only products that had


at least 100 buyers.

SELECT product, Sum(price * quantity)


FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
HAVING Sum(quantity) > 30

HAVING clause contains conditions on aggregates.

23
Exercise
EMPLOYEES EMPLOYEE_DETAILS
EMP_I DEPT_ EMP_ID SALARY Job_Stat
D ID us
1 10 1 10000 P
2 10 2 20000 T
3 10 3 15000 P
4 20 8 12500 T
5 20 4 30000 P
6 30 6 25000 T
 Find sum of salary for every department for which employees
exists and job status is permanent.
 Find sum of salary for every department which has sum of salary
greater than 30000 and job status is temporary.
 Find minimum and maximum salary for every department where
employee exists.
24
24
Ordering the Results
SELECT ename, job, sal, deptno FROM emp ORDER BY
sal, ename
ENAME JOB SAL DEPTNO
SMITH CLERK 800 20
JAMES CLERK 950 30
ADAMS CLERK 1100 20
MARTIN SALESMAN 1250 30
WARD SALESMAN 1250 30
MILLER CLERK 1300 10
TURNER SALESMAN 1500 30
ALLEN SALESMAN 1600 30

Ties are broken by the second attribute on the ORDER BY list, etc.

Ordering is ascending, unless you specify the DESC keyword.

25
The LIKE operator

SELECT * FROM emp


WHERE ename LIKE ‘%BLA%’
s LIKE p: pattern matching on strings

p may contain two special symbols:


 % = any sequence of characters

 _ = any single character

26
Eliminating Duplicates

JOB
SELECT DISTINCT JOB CLERK
FROM emp SALESMAN
MANAGER

Compared to:
JOB
CLERK
SELECT JOB
SALESMAN
FROM Emp
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER

27
Built-in Functions

 The ROUND function rounds the value you want to modify


 The TRUNC function truncates precision from a number
 The UPPER, LOWER & INITCAP functions change the case of the
text you give them
 The LENGTH function determine the lengths of the data stored in
a database column
 The SUBSTR function used to separate multiple bits of data into
discrete segments
 The INSTR function is useful when you have substrings vary in
length. This mean not only is the length of the first substring is
unknown, but starting position of the second substring can also
vary

28
28
Number Functions : ROUND
 The ROUND function rounds the value you want to modify.

 Example:
SELECT pname, pprice,
ROUND (pprice,0) AS ROUND0,
ROUND (pprice,1) AS ROUND1,
ROUND (pprice,2) AS ROUND2
FROM products

PNAME PPRICE ROUND0 ROUND1 ROUND2


Roco Pencil 3.663 4 3.7 3.66
FABER Pen 5.26 5 5.3 5.26
Roco Pad 2.28 2 2.3 2.28

29
29
Number Functions : TRUNC
 The TRUNC function truncates precision from a number.
 Example:

SELECT pname, pprice,


TRUNC(pprice,0) AS TRUNC0,
TRUNC(pprice,1) AS TRUNC1,
TRUNC(pPrice,2) AS TRUNC2
FROM product;

PNAME PPRICE TRUNC0 TRUNC1 TRUNC2


Roco Pencil 3.663 3 3.6 3.66
FABER Pen 5.26 5 5.2 5.26
Roco Pad 2.28 2 2.2 2.28

30
30
Number Functions : MOD, POWER
 MOD(m,n): Modulus function returns remainder when m is divided
by n.
 POWER(m,n): Power function returns the value of the specified
expression(m) to the specified power(n).
 Example : Employees (Emp_ID, Emp_Name, Salary)

 SELECT Emp_ID, Emp_Name, Salary,


 MOD(SALARY,2) Mod2,
 MOD(SALARY,3) Mod3,
 POWER(SALARY,2) Pow2
 FROM employees;
Emp_I Emp_Na Salary Mod2 Mod3 Pow2
D me
100 Casie 100 0 1 10000
101 John 105 1 0 11025
102 Mark 101 0 2 10201
31
31
Number Functions : SIGN & ABS
sign(n) : Returns a value indicating the sign of a number.
– if n=0 returns 0
– if n>0 returns 1
– if n<0 returns -1

Example:
Select sign(-17.36) col1,
sign(17.36) col2, Col1 Col2 Col3
sign(0) col3, From dual ; ----------------------------------
-----
-1 1 0
abs(): Returns the absolute value of a number passed as argument.
Example:

Select abs(-17.36) From dual ;

ABS(-17.36)
--------------------------------------
17.36
32
32
Text Functions : UPPER, LOWER & INITCAP
These three functions change the case of the text you give them.
 UPPER(Column_Name) : Changes parameter text font to uppercase.
 LOWER(Column_Name) : Changes parameter text font to lowercase.
 INITCAP(Column_Name) : Changes parameter text font to lowercase.
 Example : City (City_Name)

SELECT City_Name,
UPPER(City_Name) UPR,
LOWER(City_Name) LRW,
INITCAP(City_Name) INTCP
From city;
City_Name UPR LWR INTCP
Philedelphia PHILEDELPHIA philedelphia Philedelphia
New york NEW YORK new york New York
new Delhi NEW DELHI new delhi New Delhi
loNdon LONDON london London
33
33
Text Functions : LENGTH
To determine the lengths of the data stored in a database column.

Example: Products(product_code, product_name)

Select product_code, LENGTH(product_code) AS Len From Products;

Product_Cod Product_Nam Len


e e
1234QWRT Alloy Wheels 8
1234.MAGT Magnum 9
Board
$LAPZ23Q Leather Seats 8
TYR@786M// Chrome Paints 10
34
34
Text Functions : SUBSTR
To separate multiple bits of data into discrete segments.

 Syntax: SUBSTR (Column, position, [length]) :


where column is column parameter. Position and length are both integers.
Position specifies starting position and length specifies number of
character to be picked. Length parameter is optional. If not specified then
whole string starting from position integer will be picked.

Example: Item(Item_id, Item_desc)


Select item_id, SUBSTR(item_id,2) Location, SUBSTR(item_id,4,3) Number, Item_desc From
item;

ITEM_ID LOCATION NUMBER


ITEM_DESC
-----------------------------------------------------------------------------------------------------------
------------------
LA 101 A 101 101 Box, Small
NY 102 y 102 102 Bottle, Large

35
35
Text Functions : INSTR
Used to find starting location of a pattern in the string.
 Syntax: INSTR(Column, pattern, [starting position, [occurrence]])
Find starting location of pattern from starting position and for nth occurrence in
column.
Example: Items (Item_id, Item_desc)

SELECT Item_id, item_desc,


INSTR(Item_id, ’a’) col1,
INSTR(Item_id, ’a’,1,1) col2,
INSTR(Item_id, ’a’,1,2) col3,
INSTR(Item_id, ’a’,-1,1) col4 from ITEMS;

Item_i Item_Desc Col1 Col2 Col3 Col4


d
100 Leather 3 3 11 11
Seats
101 Side Mirror 0 0 0 0
102 Chrome 10 10 10 10
Board 36
36
Text Functions : REPLACE
Replace(char, str1, str2): Every occurrence of str1 in char is replaced by str2.

Example: employee(name)

Select Name,
Replace(name,‘ar',‘a') name_edit1
Replace(name,‘a',‘@') name_edit2
Replace(name,‘a',‘') name_edit2
from employee;

Name Name_edi Name_edi Name_edi


t1 t2 t3
John John John John Crter
Carter Cater C@rter
Larry Page Lary Page L@rry Lrry Pge 37
37
Text Functions : Concatenation operator “||”
To concatenate column names with other column names or with
literal characters.

Example: employees(emp_id,emp_name)

Select emp_id, emp_name, emp_id||’-’||emp_name concat_result From employee;

Emp_id Emp_name Concat_result


101 Priyanka 101-Priyanka
102 Peter 102-Peter
103 Pradeep 103-Pradeep
104 Kumar 104-Kumar
38
38
Date Functions

Function Description Syntax

Get current system date and INSERT INTO employee VALUES


Sysdate
time. (…………, trunc(sysdate),……….);

ADD_MONTHS(starting_date,
Add_months(d, n) Adds n months to date d.
number_of_months)

Difference in months
Months_between(f, s) MONTHS_BETWEEN(later_date, earlier_date)
between date f and date s.

39
39
Data Conversion Functions

Function Description

To_char(input_value, format_code) Converts any data type to character data type.

Converts a valid set of numeric character data to


To_number(input_value, format_code)
number data type.

Converts character data of the proper format to date


To_date(input_value, format_code)
data type.

40
40
Analytic Functions : LEAD,LAG
 LEAD function is used to return data from the next row
 LAG function is used to access data from a previous row

SELECT ename , Salary, SELECT ename , Salary,


LEAD(Salary, 1) OVER (ORDER BY Salary) LAG(Salary, 1,0) OVER (ORDER BY Salary)
AS LEAD AS LAG
FROM emp; FROM emp;

ENA Salar ENA Salar LEAD LAG


ME y ME y
Mike 100 Mike 100 200 0
Ross 200 Ross 200 300 100
Ben 300 Ben 300 400 200
Mark 400 Mark 400 0 300

41
41
Analytic Functions : RANK()
Rank() will assign ranks to the values in a given set

EMPN DEPT SAL EMPN DEPTN SAL Rank


O NO O O
123 10 1000 123 10 1000 1
456 10 2000 456 10 2000 2
789 20 500 789 20 500 1
120 20 500 120 20 500 1
500 20 1000 500 20 1000 3
300 20 1000 300 20 1000 3
250 20 2500 250 20 2500 5
SELECT empno, deptno, sal,
RANK() OVER (PARTITION BY deptno ORDER BY sal) AS rank
FROM emp;

Note: Rank() can cause non-consecutive rankings if the tested values are the same 42
42
Analytic Functions : DENSE RANK()
Dense Rank() acts like the RANK function except that it assigns consecutive ranks.

EMPN DEPTN SAL EMPN DEPTN SAL D_Ra


O O O O
nk
123 10 1000 123 10 1000 1
456 10 2000 456 10 2000 2
789 20 500 789 20 500 1
120 20 500 120 20 500 1
500 20 1000 500 20 1000 2
300 20 1000 300 20 1000 2
250 20 2500 250 20 2500 3
SELECT empno, deptno, sal,
DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal) AS D_rank
FROM emp;

43
43
Conditional Functions : CASE,DECODE
 SQL equivalence of IF..THEN..ELSE conditional procedural statement
 CASE and DECODE statement are very similar but CASE is an extended version of DECODE

SELECT ename , deptid, SELECT ename , deptid,


CASE WHEN deptid=10 THEN ‘SALES’ DECODE (deptid,
WHEN deptid=20 THEN ‘IT’ 10 ,‘SALES’,
WHEN deptid=30 THEN ‘HR’ 20 , ‘IT’,
ELSE ‘OTHERS’ END AS deptname 30, ‘HR’,
FROM emp; ‘OTHERS’) AS deptname
FROM emp;

ENAME DEPTID ENAME DEPTID DEPTNAME

Mike 10 Mike 10 SALES


Ross 20 IT
Ross 20
Ben 30 HR
Ben 30
Mark 40 OTHERS
Mark 40

Note: Decode cannot work with logical


operators other than

44
44
Thank You

45

You might also like