SQL from Zero › Module 4: DQL: asking questions

SELECT and choosing columns

Ask the bookshop for exactly the columns you want to see.

Lesson 17 of 33 · about 12 minutes

Video: Asking your first questionsThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.

The lesson

You've built the bookshop and filled it. Now comes the part people use most: asking it questions. That's DQL, and almost all of it is one command, SELECT.

SELECT title, price
FROM books;

Reading it out loud: "Show me the title and price, from the books table." The database goes through every row and hands back just those two columns, in the order you named them.

  • SELECT * means "every column". It's handy for a quick look, but naming the columns you need keeps results short and clear.
  • Separate column names with commas. A missing comma is the most common mistake.

Calculate as you go. A column in the result can be a small sum, and AS gives it a friendly name:

SELECT title, price * 2 AS price_for_two
FROM books;

Nothing in the table changes. SELECT only reads, so you can experiment freely.

Remove repeats with DISTINCT. SELECT genre FROM books; lists a genre for every one of the 20 books, with lots of repeats. SELECT DISTINCT genre FROM books; lists each genre once.

Key ideas
  • SELECT columns FROM table reads data without changing it.
  • SELECT * shows every column; naming columns keeps results focused.
  • AS renames a result column, and DISTINCT removes repeated rows.

Practise

Loading practice…

Quick check

1. What does SELECT * FROM customers; show?

2. After running this, what happens to the prices stored in the books table?

SELECT title, price * 0.9 AS discounted FROM books;

3. How many rows does SELECT DISTINCT genre FROM books; return?