Professional Documents
Culture Documents
• Example:
SELECT lastname, firstname FROM students
WHERE hostel_id NOT IN
(SELECT hostel_id FROM hostels)
Challenge:
• Convert the above query into one without a subquery.
Using COMPARISON OPERATORS
• SYNTAX:
• WHERE expression comparison_operator [SOME|ANY|ALL]
(subquery)
• Example:
• SELECT * FROM students WHERE cwa > ANY (SELECT cwa FROM
students)
ALL, ANY, SOME
• exp > ALL (1,2,3) • exp > ANY (1,2,3)
• Example:
SELECT cwa, lastname, firstname, department_name FROM
students JOIN departments d
USING (deparment_id) WHERE cwa >
(SELECT AVG(cwa) FROM students WHERE department_id =
d.department_id)
EXISTS and NOT EXISTS
• You can use the EXISTS operator with subqueries (typically
with correlated ones)
• Example:
SELECT lastname, firstname FROM students s
WHERE NOT EXISTS
(SELECT * FROM hostels WHERE hostel_id = s.hostel_id)
• Typically, these can be rewritten as joins which are faster and easier to read.
• Exercise:
• Rewrite the previous query to retrieve the
same results while eliminating the subquery.
Subqueries in the FROM clause
• An inline view is a subquery coded in the FROM clause
• An alias is compulsory
• Example:
SELECT name, hostel_name FROM (
SELECT CONCAT(lastname, firstname) AS name, location, hostel_name
FROM students JOIN hostels USING (hostel_id) JOIN locations USING
(location_id)
)
WHERE locaton = ‘Kotei’
A word on complex queries
• Queries can quickly get complicated for large applications and large
datasets
• Such queries may be referred to as complex (subjective)
• They are still simple if broken down into smaller logical units
• To write a complex query:
• Outline the query in your own words (pseudo code)
• Write and test the subqueries
• Combine subqueries into main query
Subqueries in the other clauses
• You can use subqueries in the WHERE clause for both UPDATES and
DELETES.
• Example:
• UPDATE hostels SET location_id = 3 WHERE location_id = (SELECT location_id
FROM locations WHERE location = ‘Ayeduase’)
• (trivial)
• Exercise:
• Change the location of every hostel in ‘Ayeduase’ to ‘Kofiduase’.
(Assume you do not know the ids of both locations beforehand)