A Language for "Fetching" Data
If I collected data with Python, now it's time to pull out what's been stored. Using MySQL's sample database Sakila (a movie-rental shop), I learned SELECT by typing each pattern by hand.
show databases; -- list databases
use sakila; -- open a database
show tables; -- list tables
select * from film;Basics and Conditions
-- only the columns I need, with aliases
select title as movie_title, rental_rate as rate from film;
-- filtering with WHERE
select * from film where rating = 'PG';
select * from film where rental_rate > 3;
select * from film where rental_rate >= 2 and rating = 'PG-13'; -- and / or
select * from film where rating <> 'PG'; -- negation <>, !=I also practiced comparing columns (replacement_cost > rental_rate) and putting arithmetic results into conditions.
Handy Condition Operators
- BETWEEN, as in
rental_rate between 2 and 4, selects an inclusive range. - IN, as in
rating in ('PG', 'G', 'PG-13'), is the same as chaining ORs. - LIKE finds by pattern, as in
description like '%drama%'(contains),'A Epic%'(starts),'%India'(ends). - IS NULL and IS NOT NULL are required; I confirmed firsthand that
= nulldoes not work.
Sorting, Limiting, Deduplicating
select * from film order by rating asc, rental_rate desc; -- multi-key sort
select * from film order by rand() limit 10; -- 10 at random
select distinct rating from film; -- remove duplicatesAggregation and Grouping
select count(*) as film_count from film;
select avg(rental_rate) avg_rate, max(rental_rate) max_rate from film;
-- group by rating, then filter groups with HAVING
select rating, count(*) as film_count
from film
group by rating
having count(*) >= 200;WHERE filters before grouping and HAVING filters after. I nailed down that difference.
JOIN — Connecting Scattered Tables
This was the most important lesson. Using a shared column (usually PK–FK), several tables connect as if they were one.
-- rentals per customer (LEFT JOIN + GROUP BY + HAVING + ORDER BY)
select c.customer_id, count(r.rental_id) as rental_count
from customer c
left join rental r
on c.customer_id = r.customer_id
group by c.customer_id
having count(r.rental_id) >= 10
order by rental_count desc;- INNER keeps only rows present on both sides.
- LEFT and RIGHT keep one table as the base and attach the other.
- Table aliases (
c,r) keep queries short and readable.
Takeaway
Key point
I was surprised how much syntax is tangled into a single SELECT. The final "rentals per customer" query gathers JOIN, GROUP BY, HAVING and ORDER BY into one statement. That query gave me the knack of turning data into questions. It was the same thinking as pandas filtering in Python, this time repeated on top of a database.