Database Queries: A First Look at SQL · Lesson 26 of 112

Database SELECT and FROM

What you will learn

  • What SQL is and what a query is
  • How to run a query on the sample database you choose
  • How to read data with SELECT ... FROM
  • How to pick columns, rename them with AS, calculate values and use DISTINCT

1. What SQL is

SQL (Structured Query Language) is the standard language for talking to relational databases. A query is a question you send to the database; the database sends back a result, which is itself a table.

SQL has many commands, but this chapter needs only a few. It is a first look: the full language comes in the next course. Commands are written in capitals here (SELECT, FROM) so they stand out; SQL does not require it.

2. The sample databases

Every example in this chapter runs on a sample database: a small, made-up database with real-looking tables. Use the Example data picker at the top of the lesson to choose one. The examples change to match your choice, and your choice is remembered in the next lessons.

Shop: an online shop with customers, products, orders, order lines, payments and reviews. Press Tables at the top to see every table and column.

Bank: a small bank with customers, accounts, a ledger of transactions, transfers, cards and loans. Money is stored in whole cents (1250 means 12.50). Press Tables at the top to see every table and column.

School: a school with students, teachers, courses, sections, enrollments, assignments and attendance. Press Tables at the top to see every table and column.

Every name, address and amount in these databases is made up. Tables, keys and REFERENCES are explained in chapters 2 and 3; for now just read along. You can edit any query in a box and press Run (or Ctrl+Enter). Reset data puts the original rows back.

3. SELECT and FROM

The basic query has two parts: SELECT says which columns, FROM says which table. * means "all columns". These tables have many rows, so each query ends with LIMIT 5, which keeps only the first five rows (lesson 4.3 explains it).

SELECT * FROM customers LIMIT 5;
customer_id  first_name  last_name  email                      phone         city          country         joined_on   is_active
-----------  ----------  ---------  -------------------------  ------------  ------------  --------------  ----------  ---------
          1  Vik         Ahmed      vik.ahmed37@example.com    +35 49854883  Leeds         United Kingdom  2025-10-01          1
          2  Wanda       Ahmed      wanda.ahmed70@example.com  NULL          Leeds         United Kingdom  2024-01-17          1
          3  Dana        Costa      dana.costa5@example.com    +58 13864688  Cairo         Egypt           2025-10-17          1
          4  Noah        Nair       noah.nair50@example.com    +48 26805141  Porto Alegre  Brazil          2024-06-10          1
          5  Hugo        Rossi      hugo.rossi88@example.com   +49 13135594  Porto Alegre  Brazil          2023-07-04          1
(5 rows)
SELECT * FROM customers LIMIT 5;
customer_id  full_name    birth_date  city     joined_on   risk_level
-----------  -----------  ----------  -------  ----------  ----------
          1  Chen Park    1956-03-20  Lima     2025-05-07  normal
          2  Rafi Uddin   1990-10-10  Manila   2020-01-08  normal
          3  Grace Kamau  1961-11-15  Toronto  2025-03-04  normal
          4  Mei Bianchi  1977-11-18  Osaka    2022-10-08  normal
          5  Farid Lee    1974-09-09  Austin   2022-06-19  normal
(5 rows)
SELECT * FROM students LIMIT 5;
student_id  first_name  last_name  birth_date  enrolled_year  email                           guardian_name
----------  ----------  ---------  ----------  -------------  ------------------------------  -------------
         1  Vera        Khan       2012-04-28           2026  vera.khan38@student.example     Amir Khan
         2  Elena       Haque      2012-08-30           2024  elena.haque48@student.example   Nadia Haque
         3  Chloe       Garcia     2010-10-09           2025  chloe.garcia13@student.example  Mina Garcia
         4  Quinn       Meyer      2011-12-07           2023  quinn.meyer73@student.example   Femi Meyer
         5  Dana        Torres     2010-05-02           2025  dana.torres45@student.example   Ana Torres
(5 rows)

Some cells are empty (NULL, lesson 2.3): a value that is not known. Name the columns you want, in the order you want them:

SELECT first_name, last_name, city FROM customers LIMIT 5;
first_name  last_name  city
----------  ---------  ------------
Vik         Ahmed      Leeds
Wanda       Ahmed      Leeds
Dana        Costa      Cairo
Noah        Nair       Porto Alegre
Hugo        Rossi      Porto Alegre
(5 rows)
SELECT full_name, city FROM customers LIMIT 5;
full_name    city
-----------  -------
Chen Park    Lima
Rafi Uddin   Manila
Grace Kamau  Toronto
Mei Bianchi  Osaka
Farid Lee    Austin
(5 rows)
SELECT first_name, last_name, enrolled_year FROM students LIMIT 5;
first_name  last_name  enrolled_year
----------  ---------  -------------
Vera        Khan                2026
Elena       Haque               2024
Chloe       Garcia              2025
Quinn       Meyer               2023
Dana        Torres              2025
(5 rows)

Asking only for the columns you need is a good habit: less data moves, and your code does not break if columns are added later.

4. Calculated columns and AS

A column in SELECT can be a calculation. AS gives the result column a name:

SELECT name, price, ROUND(price * 1.1, 2) AS price_with_tax FROM products LIMIT 5;
name              price  price_with_tax
----------------  -----  --------------
Steel pan           6.6            7.26
Ceramic mug        44.1           48.51
Wooden spoon set   29.5           32.45
Glass jar           5.4            5.94
Chopping board     26.4           29.04
(5 rows)

The 1.1 is a made-up 10% tax; the stored prices do not change. ROUND(x, 2) rounds to two decimals. Without it, decimal arithmetic can show tiny errors such as 0.8800000000000001 (the same float effect as Python lesson 3.4).

SELECT account_id, balance_cents, balance_cents / 100.0 AS balance FROM accounts LIMIT 5;
account_id  balance_cents  balance
----------  -------------  -------
         1         192400   1924.0
         2          52078   520.78
         3          62780    627.8
         4          99900    999.0
         5         153100   1531.0
(5 rows)

The stored amount is in cents; dividing by 100.0 shows it in whole money units. The stored values do not change. (100.0 with a decimal point makes SQLite divide as decimals: balance_cents / 100 would drop the cents.)

SELECT code, title, credits, credits * 15 AS study_hours FROM courses LIMIT 5;
code     title                   credits  study_hours
-------  ----------------------  -------  -----------
MATH101  Foundations of Algebra        4           60
MATH201  Geometry                      3           45
MATH301  Statistics                    4           60
SCI101   General Science               4           60
SCI201   Chemistry                     4           60
(5 rows)

The 15 is a made-up number of study hours per credit; the stored credits do not change.

SELECT only reads. A query does not even need a table:

SELECT 2 + 3 AS total;
total
-----
    5
(1 row)
SELECT 2 + 3 AS total;
total
-----
    5
(1 row)
SELECT 2 + 3 AS total;
total
-----
    5
(1 row)

5. DISTINCT: removing repeats

Many rows repeat the same value. DISTINCT returns each different value once. (ORDER BY, lesson 4.3, only puts the result in a fixed order so everyone sees the same rows.)

Orders have a status; thousands of orders, but only a few different statuses:

SELECT DISTINCT status FROM orders ORDER BY status;
status
---------
cancelled
delivered
paid
pending
shipped
(5 rows)

Hundreds of accounts, but only a few account types:

SELECT DISTINCT account_type FROM accounts ORDER BY account_type;
account_type
------------
checking
savings
(2 rows)

Hundreds of students, but only a few different years of enrollment:

SELECT DISTINCT enrolled_year FROM students ORDER BY enrolled_year;
enrolled_year
-------------
         2023
         2024
         2025
         2026
(4 rows)

Worked example: a short list for a printed sheet

The owner wants a price list with the product name and price only, the price column called list_price:

SELECT name, price AS list_price FROM products LIMIT 6;
name              list_price
----------------  ----------
Steel pan                6.6
Ceramic mug             44.1
Wooden spoon set        29.5
Glass jar                5.4
Chopping board          26.4
Tea kettle              79.0
(6 rows)

Two columns (name, list_price) and six rows, one per product. The result is a new table made on the spot; the products table itself is unchanged.

A branch wants an overview with the account number, the type and the balance in whole money units, the balance column called balance:

SELECT account_id, account_type, balance_cents / 100.0 AS balance FROM accounts LIMIT 6;
account_id  account_type  balance
----------  ------------  -------
         1  checking       1924.0
         2  savings        520.78
         3  savings         627.8
         4  checking        999.0
         5  checking       1531.0
         6  checking       2184.0
(6 rows)

Three columns and six rows, one per account. The result is a new table made on the spot; the accounts table itself is unchanged.

The office wants a course catalogue with the code, the title (called course_title) and the credits:

SELECT code, title AS course_title, credits FROM courses LIMIT 6;
code     course_title            credits
-------  ----------------------  -------
MATH101  Foundations of Algebra        4
MATH201  Geometry                      3
MATH301  Statistics                    4
SCI101   General Science               4
SCI201   Chemistry                     4
SCI202   Physics                       4
(6 rows)

Three columns and six rows, one per course. The result is a new table made on the spot; the courses table itself is unchanged.

Common mistakes

  • Using SELECT * everywhere. It is fine for exploring, but real programs should name the columns they need.
  • Forgetting that SELECT does not change data. It only reads.
  • Misspelling a column name. The database stops with an error such as no such column.
  • Expecting the order of rows to be guaranteed. Without ORDER BY (lesson 4.3) the database may return rows in any order.

Key takeaways

  • SQL is the standard language for relational databases; a query returns a table.
  • SELECT columns FROM table reads data; * means all columns.
  • AS renames a result column; calculations can appear in SELECT.
  • DISTINCT removes repeated rows from the result.
  • SELECT never changes the stored data.

Practice

1. Write a query that returns only one column of a table: the names (or titles) of everything in it.

Show answer

SELECT name FROM products; returns only the product names.

Show answer

SELECT full_name FROM customers; returns only the customer names.

Show answer

SELECT title FROM courses; returns only the course titles.

2. What does DISTINCT do in a query such as the following?

SELECT DISTINCT city FROM customers;

Show answer

It returns each different city once, even though many customers live in the same city. A customer with no city would show up as one NULL row.

SELECT DISTINCT city FROM customers;

Show answer

It returns each different city once, even though many customers live in the same city.

SELECT DISTINCT enrolled_year FROM students;

Show answer

It returns each different enrollment year once, even though many students enrolled in the same year.

3. What does AS do in this query?

SELECT price * 2 AS double_price FROM products;

Show answer

It names the calculated result column double_price. The stored prices are unchanged.

SELECT balance_cents / 100.0 AS balance FROM accounts;

Show answer

It names the calculated result column balance. The stored balances (in cents) are unchanged.

SELECT credits * 15 AS study_hours FROM courses;

Show answer

It names the calculated result column study_hours. The stored credits are unchanged.

4. Does a SELECT query change the table it reads?

Show answer

No. SELECT only reads.

5. Write a query that returns each row's name (or code) and a calculated number rounded to a whole number.

Show answer

SELECT name, ROUND(price) FROM products; returns each product name and its price rounded to a whole number.

Show answer

SELECT account_id, ROUND(balance_cents / 100.0) FROM accounts; returns each account number and its balance rounded to a whole money unit.

Show answer

SELECT code, ROUND(credits * 7.5) FROM courses; returns each course code and its credits times 7.5, rounded to a whole number.

6. Why is naming columns usually better than SELECT * in a program?

Show answer

It moves only the data you need, and the program keeps working if someone later adds or reorders columns in the table.