SQL Notes
SQL Notes
SQL Notes
+-------------+-------------+------------+
| branch_name | branch_city | assets |
+-------------+-------------+------------+
| Pownal | Bennington | 400000.00 |
| Brighton | Brooklyn | 7000000.00 |
| Downtown | Brooklyn | 900000.00 |
| Round Hill | Horseneck | 8000000.00 |
| Perryridge | Horseneck | 1700000.00 |
| Mianus | Horseneck | 400200.00 |
| Redwood | Palo Alto | 2100000.00 |
| ... | ... | ... |
Aggregate Functions in SQL
6
¨ Example:
“Find all customers with more than one loan.”
SELECT customer_name, COUNT(*) AS num_loans
FROM borrower GROUP BY customer_name
HAVING COUNT(*) > 1;
+---------------+-----------+
| customer_name | num_loans |
+---------------+-----------+
| Smith | 3 |
+---------------+-----------+
Nested Subqueries
18
¨ Widely used:
¤ Directcomparison with scalar-subquery results
¤ Set-membership tests: IN, NOT IN
¨ Example:
“Find branches with assets greater than all branches in
Brooklyn.”
SELECT branch_name FROM branch
WHERE assets > ALL (
SELECT assets FROM branch
WHERE branch_name='Brooklyn');
¤ Could also write this with a scalar subquery
SELECT branch_name FROM branch
WHERE assets >
(SELECT MAX(assets) FROM branch
WHERE branch_name='Brooklyn');
Uniqueness Tests
31
“Find all cities with more than two customers living in the city.”
SELECT customer_city, COUNT(*) AS num_customers
FROM customer GROUP BY customer_city
HAVING COUNT(*) > 2;
¨ Or, can write:
SELECT customer_city, num_customers
FROM (SELECT customer_city, COUNT(*)
FROM customer GROUP BY customer_city)
AS counts (customer_city, num_customers)
WHERE num_customers > 2;
¤ Grouping and aggregation is computed by inner query
¤ Outer query selects desired results generated by inner query
Derived Relation Syntax
34
¨ SQL views