new hires by department CREATE TABLE employees ( id serial primary key, name text, department_id int, join_date date); CREATE INDEX join_dept_idx ON employees (department_id, join_date DESC); @lornajane
using aliases and a left join SELECT e.id AS employee_id, e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON (e.manager_id = m.id); employee_id | employee | manager -------------+----------+--------- 1 | Anna | 2 | Beth | Anna 3 | Charlie | Anna @lornajane
subtotal boundaries How many films with "DINOSAUR" in the name are in each store? SELECT i.store_id, f.title, count(*) AS total FROM inventory i INNER JOIN film f ON i.film_id = f.film_id WHERE f.title LIKE '%DINOSAUR%' GROUP BY f.title, i.store_id; @lornajane
Films where there are more than 7 copies in the inventory? SELECT f.title, count(*) AS total FROM inventory i INNER JOIN film f ON i.film_id = f.film_id GROUP BY f.title HAVING count(*) > 7; @lornajane
a JOIN city ci USING (city_id) JOIN country co USING (country_id); Result: addres_id | address | city | country ----------+---------------------+-------------+------------ 1 | 47 MySakila Drive | Lethbridge | Canada 2 | 28 MySQL Boulevard | Woodridge | Australia 3 | 23 Workhaven Lane | Lethbridge | Canada 4 | 1913 Hanoi Way | Sasebo | Japan 5 | 692 Joliet Street | Athenai | Greece 6 | 53 Idfu Parkway | Nantou | Taiwan @lornajane
ci.city, co.country FROM address a JOIN city ci USING (city_id) JOIN country co USING (country_id) SELECT c.first_name, a.country FROM customer c JOIN addr a USING (address_id); Result: first_name | country -------------+--------------------------------------- MARY | Japan PATRICIA | United States LINDA | Greece ELIZABETH | Taiwan @lornajane
while still returning the individual rows. e.g. A list of films plus: • their running time • the average running time for this rating of film • the average for all films @lornajane
seen (type \h [something]) • Try adding NULLS FIRST|LAST to your ORDER BY • Fabulous support for geographic data http://postgis.net/ See also: https://github.com/dhamaniasad/awesome-postgres @lornajane