3. SELECT: choosing columns
SELECT is how you pick what comes back. Everything in this module builds
on it.
Pick specific columns
List the columns you want, separated by commas:
SELECT first_name, last_name, email
FROM customer;
Get every column with *
* means "all columns." Handy for a quick look, but in real code prefer
naming the columns you need — it's clearer and doesn't break when someone
adds a column later.
SELECT *
FROM category;
Compute new columns
SELECT can do math and build values on the fly. This film table stores
a daily rental_rate; here's the price for a 3-day rental:
SELECT title, rental_rate, rental_rate * 3
FROM film;
That third column comes back with an ugly auto-generated name. Give it a
friendly one with AS — this is called an alias:
SELECT title, rental_rate * 3 AS three_day_price
FROM film;
AS is optional (rental_rate * 3 three_day_price works too), but
writing it makes your intent obvious. Use quotes if you want spaces:
AS "Three Day Price".
Remove duplicates with DISTINCT
DISTINCT collapses repeated rows into one. The film table has 1000
rows, but only a handful of ratings — DISTINCT shows each once:
SELECT DISTINCT rating
FROM film;
It applies to the whole row you selected, so SELECT DISTINCT rating,
rental_rate gives every unique combination of the two.
Try it
Show each film's title and its replacement cost as a column called
cost — but only the distinct replacement_cost values, aliased as
cost. (Hint: you only need the one column.)
SELECT replacement_cost
FROM film;
SELECT DISTINCT replacement_cost AS cost
FROM film;