SQL Tutorial · SQL Basics · Lesson 3 of 36

SQL SELECT

Choose columns, use * and remove duplicates with DISTINCT.

Selecting columns

List the columns you want after SELECT, and the table after FROM:

Example 1Try it yourself
SELECT name, price FROM products;

Output

name | price
SQL for Beginners | 29.99
Clean Code | 37.5
The Pragmatic Programmer | 42
Mechanical Keyboard | 89
Wireless Mouse | 24.99
4K Monitor | 329
USB-C Hub | 39.95
Coffee Mug | 12
Desk Lamp | 45
Standing Desk Mat | 59.9
Rubber Duck | 5.5
Robot Kit | 120

SELECT *

* returns every column. It's handy for exploring, but in application code list the columns explicitly — it's faster and doesn't break when columns are added.

Example 2Try it yourself
SELECT * FROM categories;

Output

category_id | name
1 | Books
2 | Electronics
3 | Home
4 | Toys

Calculated columns

A column can be an expression:

Example 3Try it yourself
SELECT name, price, stock, ROUND(price * stock, 2) AS stock_value FROM products WHERE stock > 0;

Output

name | price | stock | stock_value
SQL for Beginners | 29.99 | 40 | 1199.6
Clean Code | 37.5 | 15 | 562.5
Mechanical Keyboard | 89 | 25 | 2225
Wireless Mouse | 24.99 | 60 | 1499.4
4K Monitor | 329 | 8 | 2632
USB-C Hub | 39.95 | 30 | 1198.5
Coffee Mug | 12 | 100 | 1200
Desk Lamp | 45 | 12 | 540
Rubber Duck | 5.5 | 200 | 1100
Robot Kit | 120 | 5 | 600

DISTINCT

SELECT DISTINCT removes duplicate rows from the result:

Example 4Try it yourself
SELECT DISTINCT country FROM customers ORDER BY country;
SELECT COUNT(DISTINCT country) AS countries FROM customers;

Output

country
Japan
Netherlands
Switzerland
UK
USA

countries
5

Test yourself

Which keyword removes duplicate rows from a result?

  1. UNIQUE
  2. DISTINCT
  3. DIFFERENT
  4. SINGLE
Show answer

Answer: DISTINCT