0% found this document useful (0 votes)
21 views

Week 7.1

Uploaded by

faiez tariq
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Week 7.1

Uploaded by

faiez tariq
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Data base system

Ch. Usman Ghous


FAST-NU
Chiniot Faisalabad Campus
SQL Clause
► ORDER BY CLAUSE:
► The ORDER BY keyword is used to sort the result-set by one or more columns
► Keyword DESC to see result in a descending order of values
► Keyword ASC to specify ascending order explicitly
► SELECT * FROM EMPLOYEE
ORDER BY ADDRESS ASC, Fname DESC;
► SELECT CITY, REGION, (SALES - TARGET)
FROM OFFICES
ORDER BY REGION ASC;
GROUP BY CLAUSE

► The SQL GROUP BY clause is used in collaboration with the SELECT statement
to arrange identical data into groups.
► SYNTAX SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2

► EXAMPLE SELECT dept_id, SUM(salary) AS total_salaries


FROM employees
GROUP BY dept_id;
HAVING CLAUSE

► The SQL HAVING clause is used in combination with the GROUP BY clause to
restrict the groups of returned rows to only those whose the condition is
TRUE.
► Similar to WHERE, but WHERE filters individual rows whereas HAVING filters
groups.

► SELECT department, SUM(sales) AS "Total sales"


FROM order_details
GROUP BY dno HAVING SUM(sales) > 1000;

► SELECT DEPARTMENT, MIN(salary) AS "Lowest salary"


FROM EMPLOYEE GROUP BY Dnumber
HAVING MIN(salary) > 35000;

► SELECT DEPARTMENT, MAX(salary) AS "Highest salary"


FROM EMPLOYEE GROUP BY Dnumber
HAVING MAX(salary) < 50000;
Aggregation Function

► ISO standard defines five aggregate functions:

►COUNT returns number of values in a specified column.


►SUM returns sum of values in a specified column.
►AVG returns average of values in a specified column.
►MIN returns smallest value in a specified column.
►MAX returns largest value in a specified column.
Aggregation Function

► Each operates on a single column of a table and return single value.

► COUNT, MIN, and MAX apply to numeric and non-numeric fields

► SUM and AVG may be used on numeric fields only

► Can use DISTINCT before column name to eliminate duplicates.

► DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG.

► Aggregate functions can be used only in SELECT list and in HAVING clause.

SELECT city, COUNT(*)


FROM car_sales;
Aggregation Function

► How many rows are ■ How many cities are


there in the car_sales there in the car_sales
table? table?
City Year Cars_Sold

SELECT Dhahra 200 52


n 1 5
SELECT COUNT(*) as Rows COUNT(DISTINCT city)
Dhahra 200 45
FROM car_sales as city n 2 6
FROM car_sales Jedda 200 92
h 1 1
Jedda 200 75
h 2 2
Rows city Khoba 200
r 2
7 4 Riyad 200 70
h 1 0
Riyad 200 65
h 2 4
SUM Function

► Find the total number ■ Find the number of all the


of all the cars sold from cars_sold in Dhahran from
the car_sales table? the car_sales table?
City Year Cars_Sold
SELECT SELECT Dhahra 200 52
SUM(cars_sold) as cars_sold SUM(cars_sold) as Dah_cars n 1 5
FROM car_sales FROM car_sales Dhahra 200 45
WHERE city = ‘Dhahran’ n 2 6
Jedda 200 92
h 1 1
Jedda 200 75
Cars_sold Dah_cars h
Khoba
2 2
200
r 2
400 98 Riyad 200 70
8 1 h 1 0
Riyad 200 65
h 2 4
MIN,MAX and AVG function

► Find the minimum, maximum, and average cars_sold per year


and per city form the car_sales table

SELECT MIN(cars_sold) as Min_sold


, MAX(cars_sold) as
Max_sold
, AVG(cars_sold) as Avg_sold
FROM car_sales
WHERE car_sales IS NOT NULL;

Min_sold Max_sold Avg_sold

45 92 66
6 1 8
Aliasing Table Names

► A table alias is created by directly placing an alias after the table name in the
FROM clause.
► For example in the following example we will refer to departments table as d
or dept.

SELECT d.dname SELECT dept.dname


FROM departments FROM departments
d dept
WHERE d.dno = 1; WHERE dept.dno = 1;
Nested Queries

► Some SQL statements can have a SELECT embedded within them.


► A sub select can be used in WHERE and HAVING clauses of an outer SELECT,
where it is called a nested query or a subquery.
► Who has a salary greater than Abel’s?

Main
query: Which employees have salaries
greater than Abel’s salary?

What is Abel’s salary?


SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

► The subquery (inner query) executes once before the main query (outer
query).
► The result of the subquery is used by the main query.
► Example.

SELECT last_name
FROM employees
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');
Nested queries

► From the Lecturer table, select lecturers whose salary is above average
► Cannot write 'WHERE salary > avg(salary);
► Solution
► Select * from lecturer where salary>(
select AVG(salary
from lecturer);
► List the names of all Lecturers who are in the ICS department
select name from lecturer
where dno IN(
select dno from department
where dname=‘ICS’
);
Nested queries

► List products with order quantities greater than 100


Nested queries

► List products with order quantities greater than 100

select ProductName from PRODUCT


where id=( select id from ORDERITEM
where quantity>100);
Nested queries

► Find lecturers whose salary higher than the salary of at least 1 COE lecturer.
Nested queries

► Find lecturers whose salary higher than the salary of at least 1 COE lecturer.

Select * from lecturer


Where salary>( select min(salary
from lecturer where dno =(select DNO
from department
where dname=‘COE’)
);
Nested queries

► Find lecturers whose salary higher than the salary of every COE lecturer
Nested queries

► Find lecturers whose salary higher than the salary of every COE lecturer
Select * from lecturer
Where salary>( select max(salary
from lecturer where dno =(select DNO
from department
where dname=‘COE’);
);
Special Operators
► EXISTS
► Used to check if subquery returns any rows

Syntax SELECT COLUMN(S) FROM Table-name
WHERE EXISTS ( subquery );
► EXAMPLE SELCT * FROM EMPLOYEE
WHERE EXISTS( SELECT * FROM DEPARTMENT
WHERE
EMPLOYEE.Dno=DEPARTMENT.Dnumber);
► Find all ICS lecturer
SELCT * FROM LECTURER
WHERE EXISTS( SELECT * FROM DEPARTMENT
WHERE
LECTUREER.Dno=DEPARTMENT.Dnumber AND
DNAME=‘ICS’);
► find all of the records from the customers table where there is at least one
record in the orders table with the same customer_id.
► find all of the records from the customers table where there is at least one
record in the orders table with the same customer_id.

► SOLUTION
SELECT * FROM customers
WHERE EXISTS (
SELECT * FROM orders
WHERE
customers.customer_id = orders.customer_id);
NOT EXISTS Operators
► Query: List first and last name of employees who work on ALL projects NOT controlled
by Dno=5.

SELECT Fname, Lname


FROM Employee
WHERE NOT EXISTS ( (SELECT Pnumber
FROM PROJECT
WHERE Dno=5)) ;
Find all non ICS lecturers.

SELECT *
FROM lecturers a
WHERE NOT EXISTS
(
SELECT *
FROM department b
WHERE a.dno = b.dno
AND b.dname = ‘ICS‘
);
Not Exists

SELECT * FROM customers


WHERE NOT EXISTS (SELECT * FROM orders WHERE

customers.customer_id = orders.customer_id);
Not Exists

Find the record of all those customer who doesn’t place any
order
Correlated queries

► A correlated subquery is a subquery that uses the values of the outer query. In
other words, the correlated subquery depends on the outer query for its values.
► Because of this dependency, a correlated subquery cannot be executed
independently as a simple subquery.
► Moreover, a correlated subquery is executed repeatedly, once for each row
evaluated by the outer query. The correlated subquery is also known as a
repeating subquery
► The main difference between a SQL correlated subquery and a simple subquery is that
a SQL correlated subquery references columns from the table of the outer query.
Example 1

Select Product_name.list_price,category_id
From production,product p1
Where list_price IN(
select MAX(p2.list_price)
From production,product p2
where p2.category_id=p1.Category_id
Group by p2.category_id)
order by
Name_list, category_id
Correlated queries
► Used to affect row by row processing, each subquery is executed once for
every row of the outer query
“It is a sub query that uses the value of outer query
It is top down approach
GET
Candidate row

Execute
Inner query using candidate row values

Use
Value(s) from inner query to qualify candidate row
EXAMPLE 2

“Find the student taking atleast three courses


Nested sub query
Select * from STD where st_id In( Select st id from REGISTERATION
group by st_id

Having count(st-id)>=3)
By correlated queries
Select * from STD where 3>=(select count (st_id) from Registration
where st_id=STD.St_id)
EXAMPLE 2

SELECT po_num, ship_date FROM orders main WHERE 10 > (SELECT COUNT
(DISTINCT ship_date) FROM orders sub WHERE sub.ship_date < main.ship_date) AND
ship_date IS NOT NULL ORDER BY ship_date, po_num;
EXAMPLE 2

“Find the Faculty who advise atleast one student


By correlated queries
Select * from FACULTY where exist(select * from STD
where f_id=FACULTY.f_id)
EXAMPLE 2

“Obtain the names of employees who never


received an award”

SELECT last_name, first_name


FROM employee e1
WHERE NOT EXISTS (SELECT ph.last_name
FROM payment_history ph
WHERE ph.employee_id = e1.employee_id
AND ph.payment_type = 'award')
Corelated Queries

“It is a sub query that uses the value o outer query


It is top down approach

SELECT last_name, first_name


FROM employee e1
WHERE NOT EXISTS (SELECT ph.last_name
FROM payment_history ph
WHERE ph.employee_id = e1.employee_id
AND ph.payment_type = 'award')
The INSERT Command

► Syntax
INSERT INTO TABLE NAME(FIELD1,FIELD2,…..FIELDN)
VALUES(VALUE1,VALUE2,…….VALUEN);
► EXAMPLE
INSERT INTO
EMPLOYEE(Fname, Minit,Lname,SSN,Bdate,Address,Gender,MSSN,Dno)
VALUES(‘Richard’,’K’,’Marini’,’653298653’,’1962-12-30’,’98 Oak Forest,
Katy, Tx’,’M’,37000,’653298653,4);
► OR
The Delete Command

► Removes tuples from a relation


► Includes a WHERE-clause to select the tuples to be deleted
► Tuples are deleted from only one table at a time (unless CASCADE is specified
on a referential integrity constraint)
► The number of tuples deleted depends on the number of tuples in the relation
that satisfy the WHERE-clause
► Syntax
DELETE from table name
WHERE Condition;
The Delete Command

► DELETE FROM EMPLOYEE


WHERE Lname=‘Brown’;
► DELETE FROM EMPLOYEE
WHERE SSN=‘123456789’;
► DELETE FROM EMPLOYEE
WHERE Dno=5;
► DELETE FROM EMPLOYEE;

► A missing WHERE-clause specifies that all tuples in the relation are to be


deleted; the table then becomes an empty table
UPDATE COMMANDS

► Used to modify attribute values of one or more selected tuples


► A WHERE-clause selects the tuples to be modified
► SET-clause specifies the attributes to be modified and their new values
► Each command modifies tuples in the same relation
► SYNTAX
UPDATE TABLE-NAME
SET ATRRIBUTE(s)=NEW VALUE
WHERE CONDITION;
► EXAMPLE
UPDATE PROJECT
SET Plocation=‘Bellaire’ AND Dnum=5
WHERE Pnumber=10;

You might also like