










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











More Complex SQL Retrieval Queries
For convenience, include renaming (like ) as well
Aliases or tuple variables
SELECT name, sale_date, product, quantity AS amount FROM Customer C, Sale AS S(id,sale_date,custid), LineItem WHERE C.custid = S.custid AND id = saleid;
Customer custid name address phone
Sale saleid date custid
LineItem saleid product quantity price
Renaming is mandatory if table used more than once in a query
Example Give the last names and salaries of employees and their managers whenever the employee earns more than the manager.
SELECT E.Lname, E.Salary, M.Lname, M.Salary FROM EMPLOYEE E, EMPLOYEE M WHERE E.Super_ssn = M.Ssn and E.Salary > M.Salary;
EMPLOYEE Fname Minit Lname Ssn Bdate Address Sex Salary Super_ssn Dno
M Fname Minit Lname Ssn Bdate Address Sex Salary Super_ssn Dno
E Fname Minit Lname Ssn Bdate Address Sex Salary Super_ssn Dno
How can we answer a query such as
“ How many films were directed by each director after 2001? ”
GROUP BY clause to specify grouping attributes SELECT director, COUNT(*) FROM Film WHERE year > 2001 GROUP BY director;
After partitioning into groups, whole partitions can be discarded.
Having clause cannot reference individual tuples within group
Contrast WHERE clause to HAVING clause
Note : As for aggregation, no GROUP BY clause means relation treated as one group
Any table can be used in FROM clause.
select-from-where produces a table.
Thus can nest one query within another.
Example:
Give the biographical information for directors of profitable movies.
SELECT name, birth, city FROM ( SELECT director FROM Film WHERE gross > budget) AS Profitable, Person WHERE director = name
Film title genre year director minutes budget gross
Person name birth city
Comparison operator IN
Use tuples of values in comparisons
Correlated nested query
Such queries are easiest to understand (and write correctly) if all column names are qualified by their relation names.
Note that the inner query can refer to E, but the outer query cannot refer to D.
[NOT] EXISTS function
SELECT name, phone FROM Customer C WHERE NOT EXISTS ( SELECT * FROM Sale S WHERE C.custid = S.custid);
SQL function UNIQUE(Q)
Customer custid name address phone
Sale saleid date custid