Your First Queries · Lesson 1 of 64

SQL How to Read a Database

What you will learn

  • How to list the tables of a database and the columns of a table
  • What a column's type, primary key and foreign key tell you
  • How to count rows and peek at a few rows safely
  • A routine for exploring a database you have never seen

1. Look before you query

A good query starts before you type SELECT. You need to know which tables exist, what each column is called and holds, and how the tables link. The tables and columns are called the schema of the database. Guessing a column name gives an error; reading the schema first saves time.

This course runs every example on a sample database that you choose with the Example data picker at the top of the lesson: Shop, Bank or School. All three are made up. Your choice is remembered in the next lessons, and Reset data puts the original rows back. Edit any query and press Run (or Ctrl+Enter).

If you have done chapter 4 of Database Fundamentals you have met these databases already. Here we go slower and learn to explore them.

2. Which tables exist?

SQLite keeps a list of its tables in a built-in table called sqlite_master. You can query it like any other table:

SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-----------
categories
customers
employees
order_items
orders
payments
products
reviews
suppliers
(9 rows)
SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-------------
accounts
audit_log
branches
cards
customers
loan_payments
loans
transactions
transfers
(9 rows)
SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-----------
assignments
attendance
courses
departments
enrollments
sections
students
submissions
teachers
(9 rows)

(The Tables button at the top of the lesson shows the same list, with row counts.) Other databases have their own way to list tables, for example a special command in the tool you use; the idea is the same.

3. Which columns does a table have?

pragma_table_info('table_name') lists the columns of one table: its position (cid), name, type, whether it is NOT NULL, its default value and whether it is part of the primary key (pk).

SELECT cid, name, type, "notnull", pk FROM pragma_table_info('products');
cid  name         type     notnull  pk
---  -----------  -------  -------  --
  0  product_id   INTEGER        0   1
  1  sku          TEXT           1   0
  2  name         TEXT           1   0
  3  category_id  INTEGER        1   0
  4  supplier_id  INTEGER        1   0
  5  price        REAL           1   0
  6  cost         REAL           1   0
  7  stock        INTEGER        1   0
  8  is_active    INTEGER        1   0
  9  added_on     TEXT           1   0
(10 rows)
SELECT cid, name, type, "notnull", pk FROM pragma_table_info('accounts');
cid  name           type     notnull  pk
---  -------------  -------  -------  --
  0  account_id     INTEGER        0   1
  1  customer_id    INTEGER        1   0
  2  branch_id      INTEGER        1   0
  3  account_type   TEXT           1   0
  4  opened_on      TEXT           1   0
  5  status         TEXT           1   0
  6  balance_cents  INTEGER        1   0
(7 rows)
SELECT cid, name, type, "notnull", pk FROM pragma_table_info('courses');
cid  name           type     notnull  pk
---  -------------  -------  -------  --
  0  course_id      INTEGER        0   1
  1  code           TEXT           1   0
  2  title          TEXT           1   0
  3  department_id  INTEGER        1   0
  4  credits        INTEGER        1   0
(5 rows)

How to read it:

  • name is what you write in a query. Names are written exactly as shown (with underscores, no spaces).
  • type says what kind of value the column holds: INTEGER (whole numbers), REAL (decimal numbers), TEXT (words and dates written as text).
  • notnull is 1 when the column must always have a value. (An INTEGER PRIMARY KEY shows 0 here in SQLite, but it can never be empty.)
  • pk is not 0 for the column (or columns) that identify each row: the primary key.

A column that holds the key of another table is a foreign key. pragma_foreign_key_list shows where each one points:

SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('products');
column_name  points_to   in_column
-----------  ----------  -----------
supplier_id  suppliers   supplier_id
category_id  categories  category_id
(2 rows)
SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('accounts');
column_name  points_to  in_column
-----------  ---------  -----------
branch_id    branches   branch_id
customer_id  customers  customer_id
(2 rows)
SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('courses');
column_name    points_to    in_column
-------------  -----------  -------------
department_id  departments  department_id
(1 row)

Each row says: this column of the table holds keys of that other table. Later, in the chapter on joins, you will use these links to combine tables.

5. How many rows?

COUNT(*) counts rows. Knowing the size of a table tells you whether SELECT * would print a handful of rows or thousands:

SELECT 'customers' AS table_name, COUNT(*) AS rows FROM customers
UNION ALL SELECT 'products', COUNT(*) FROM products
UNION ALL SELECT 'orders', COUNT(*) FROM orders
UNION ALL SELECT 'order_items', COUNT(*) FROM order_items;
table_name   rows
-----------  ----
customers     420
products       45
orders       2600
order_items  5790
(4 rows)
SELECT 'customers' AS table_name, COUNT(*) AS rows FROM customers
UNION ALL SELECT 'accounts', COUNT(*) FROM accounts
UNION ALL SELECT 'transactions', COUNT(*) FROM transactions
UNION ALL SELECT 'loans', COUNT(*) FROM loans;
table_name    rows
------------  ----
customers      300
accounts       450
transactions  7415
loans           80
(4 rows)
SELECT 'students' AS table_name, COUNT(*) AS rows FROM students
UNION ALL SELECT 'courses', COUNT(*) FROM courses
UNION ALL SELECT 'enrollments', COUNT(*) FROM enrollments
UNION ALL SELECT 'attendance', COUNT(*) FROM attendance;
table_name   rows
-----------  ----
students      360
courses        19
enrollments  1002
attendance   6012
(4 rows)

(UNION ALL stacks several results into one; it is covered properly in the chapter on joins.) A few tables are tiny, and some have thousands of rows.

6. Peek at a few rows

Now look at real rows. SELECT * means "all columns", and LIMIT 5 stops after five rows, so even a big table prints a short result:

SELECT * FROM products LIMIT 5;
product_id  sku       name              category_id  supplier_id  price   cost  stock  is_active  added_on
----------  --------  ----------------  -----------  -----------  -----  -----  -----  ---------  ----------
         1  SKU-0001  Steel pan                   2            9    6.6   3.96      0          1  2024-01-15
         2  SKU-0002  Ceramic mug                 2            9   44.1  30.21    150          1  2025-01-21
         3  SKU-0003  Wooden spoon set            2            2   29.5   13.3      0          1  2024-03-21
         4  SKU-0004  Glass jar                   2            8    5.4   2.45     40          1  2024-01-02
         5  SKU-0005  Chopping board              2            6   26.4  14.63     80          1  2024-11-07
(5 rows)
SELECT * FROM accounts LIMIT 5;
account_id  customer_id  branch_id  account_type  opened_on   status  balance_cents
----------  -----------  ---------  ------------  ----------  ------  -------------
         1           77          1  checking      2025-05-27  open           192400
         2          128          2  savings       2021-11-26  open            52078
         3          279          5  savings       2024-09-03  open            62780
         4            7          1  checking      2023-05-04  closed          99900
         5           12          5  checking      2021-10-12  open           153100
(5 rows)
SELECT * FROM courses LIMIT 5;
course_id  code     title                   department_id  credits
---------  -------  ----------------------  -------------  -------
        1  MATH101  Foundations of Algebra              1        4
        2  MATH201  Geometry                            1        3
        3  MATH301  Statistics                          1        4
        4  SCI101   General Science                     2        4
        5  SCI201   Chemistry                           2        4
(5 rows)

Compare the columns in the result with the list you read in section 3. A column may show NULL, which means "no value" (it is not zero and not empty text). Chapter 2 explains how to filter on it.

Always peek with LIMIT. On a table with millions of rows, SELECT * without a limit can take a long time and return far more than you can read.

Worked example: explore a table you have never seen

You are asked a question about "payments" and know nothing about the database. A routine that works on any database:

Step What you do What it tells you
1 list the tables is there a table that sounds right?
2 read the columns of that table what is stored, and in what type?
3 look at the foreign keys which other tables does it link to?
4 count the rows is it small or big?
5 peek at five rows what do real values look like (dates, money, NULL)?

Only then write the real query. In the Shop the table is payments, in the Bank transactions, in the School enrollments; the routine is the same. The names, people and amounts are made up.

Common mistakes

  • Guessing column names. A wrong name gives an error such as no such column. Read the schema first.
  • SELECT * on a big table without LIMIT.
  • Mistaking NULL for zero or an empty text. NULL means no value.
  • Forgetting that a type is only a hint in SQLite. SQLite is relaxed about types (lesson 2.2 of Database Fundamentals); most other databases are strict.

Key takeaways

  • The schema (tables, columns, types, keys) is the map of a database; read it first.
  • sqlite_master lists the tables and pragma_table_info lists the columns of one table (SQLite's way; other databases have their own).
  • A foreign key column holds keys of another table; pragma_foreign_key_list shows where.
  • COUNT(*) gives the size of a table; SELECT * ... LIMIT 5 shows a safe peek.

Practice

1. Which query lists the columns of the table customers (if it exists in your database)?

Show answer

SELECT name, type FROM pragma_table_info('customers');

2. What does pk tell you in the result of pragma_table_info?

Show answer

Whether the column is part of the primary key. A value other than 0 means it is, and a 0 means it is not.

3. Why add LIMIT 5 when you only want to look at a table?

Show answer

So a big table does not print thousands of rows. You see enough rows to understand the data, and the query stays fast.

4. A column called status shows NULL for some rows. What does NULL mean?

Show answer

No value is stored: the status is unknown or does not apply. It is not the same as an empty text or the number 0.

5. You cannot remember whether a table is called order or orders. What do you run?

Show answer

SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name; and read the list.

6. Name the five steps of the routine for exploring an unknown table.

Show answer

List the tables, read the columns, look at the foreign keys, count the rows, peek at five rows.