Testing SQL

Updated · 13 min read
mediumPostgreSQL 18sqltestingpytestfixturestransactionsmigrationsciinterview

Testing SQL means running your queries, constraints and migrations against a real database with known data, and checking that the results are exactly what you expect. A query that returns the wrong students, a constraint someone forgot, or a migration that fails on an empty database are all bugs that only show up when SQL actually runs. Good SQL tests follow three rules: they run on a disposable test database, never a shared or production one; they start from known data, called fixtures; and they leave nothing behind, usually by rolling back after each test. In this lesson, we will write tests in SQL itself with ASSERT, use a transaction to undo every test's changes, test that bad data is refused, compare a query's result with the expected rows, test a migration, and then run the same ideas as a pytest suite in Python, with its real output.

In One Minute

  • Run tests on a disposable database, created fresh from your migrations and sample data.
  • Fixtures are known rows each test starts from: the Fee Tracker's three students, for example.
  • Wrap each test in a transaction and roll it back, so tests can't affect each other.
  • Test the happy path (right rows come back) and the refusals (bad rows raise the right error).
  • Compare result sets in both directions with EXCEPT, or compare lists in your test code.
  • Test migrations by applying them all to an empty database in CI.

A Disposable Test Database

Tests need a database you can fill, change and throw away. Never point tests at production or a shared development database: tests insert and delete rows, and a shared database changes under them, so results stop being repeatable.

ApproachHowGood for
A test database on your machine or CIcreatedb feetracker_test, run migrations, load fixturesMost projects
A container per test runDocker, or Testcontainers (Java, Node.js, Python), starts PostgreSQL, then removes itClean, identical runs in CI
A template copyCREATE DATABASE feetracker_test TEMPLATE feetracker_template;Fast fresh copies of a large fixture set
SQLite instead of PostgreSQLAn in-memory fileAvoid for PostgreSQL apps: types, functions and errors differ

Test against the same database engine and major version you run in production. A test that passes on SQLite can fail on PostgreSQL, and the other way round (Dialect Differences Cheat Sheet). Every Try it example in this course works the same way: a fresh copy of the Fee Tracker for each run, thrown away afterwards.

Assertions in SQL

PostgreSQL's procedural language has an ASSERT statement that raises an error when a condition is false. Inside a DO block, it turns a query into a test:

SQL▶ Try it
DO $$
BEGIN
  ASSERT (SELECT count(*) FROM students) = 3,
         'expected 3 students';
  ASSERT (SELECT count(*) FROM payments) = 8,
         'expected 8 payments';
END $$;
Output
ERROR:  expected 8 payments

Explanation: The first ASSERT passes, because the Fee Tracker has three students. The second is wrong on purpose: there are 7 payments, not 8, so PostgreSQL raises an error with our message. A test that fails loudly with a clear message is exactly what you want. ASSERT checks can be switched off with the setting plpgsql.check_asserts, which is on by default; use RAISE EXCEPTION with an IF when a check must never be skipped.

Each Test Leaves Nothing Behind

The simplest way to keep tests independent is to run each one inside a transaction and roll it back at the end. The test can insert, update and delete freely; afterwards, the data is exactly as it was:

SQL▶ Try it
BEGIN;
 
-- Test: when Advitha pays, she leaves the unpaid list
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 1, 450.00, '2026-01-05', '2026-01-05', 'card');
 
DO $$
BEGIN
  ASSERT NOT EXISTS (
    SELECT 1 FROM students s
    WHERE NOT EXISTS (SELECT 1 FROM payments p WHERE p.student_id = s.student_id)
  ), 'every student should have a payment now';
END $$;
 
ROLLBACK;
 
SELECT count(*) AS payments_after_test FROM payments;
Output
BEGIN
 
INSERT 0 1
 
DO
 
ROLLBACK
 
 payments_after_test
---------------------
                   7
(1 row)

Explanation: Inside the transaction, Advitha's payment exists and the assertion passes (DO with no error). ROLLBACK then throws the payment away, so the table has 7 payments again, and the next test starts from the same known data. This is much faster than rebuilding the database before every test. It has one limit: code that commits its own transactions, or that needs two connections to see each other's changes, can't be tested this way, and needs a freshly loaded database instead.

Each test runs in a transaction and rolls back, so every test starts from the same data

Testing That Bad Data Is Refused

Constraints are part of your design, so test them: a test should prove that bad rows are refused with the right error. In PL/pgSQL, catch the expected error by its name, and fail if no error happens:

SQL▶ Try it
DO $$
BEGIN
  INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
  VALUES (101, 1, -5.00, '2026-01-05', '2026-01-05', 'card');
  RAISE EXCEPTION 'test failed: a negative amount was accepted';
EXCEPTION
  WHEN check_violation THEN
    RAISE NOTICE 'ok: negative amount refused';
END $$;
 
DO $$
BEGIN
  INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
  VALUES (103, 1, 450.00, '2026-01-05', '2026-01-05', 'card');
  RAISE EXCEPTION 'test failed: a payment without an enrollment was accepted';
EXCEPTION
  WHEN foreign_key_violation THEN
    RAISE NOTICE 'ok: payment without an enrollment refused';
END $$;
Output
NOTICE:  ok: negative amount refused
DO
 
NOTICE:  ok: payment without an enrollment refused
DO

Explanation: If the INSERT succeeds, the next line raises our own error and the test fails. If it fails with check_violation (SQLSTATE 23514) or foreign_key_violation (23503), the handler prints a notice and the test passes. Catching only the expected error matters: a different error, such as a typo in a column name, still fails the test instead of being mistaken for success. Navika isn't enrolled in course 1, so the payment's foreign key to enrollments refuses it. A DO block's exception handler also undoes the block's changes, so nothing is left behind.

Comparing a Query's Result

To test a query, compare its rows with the rows you expect, in both directions. EXCEPT returns rows in the first set that aren't in the second (INTERSECT and EXCEPT), so two empty EXCEPTs mean the sets match:

SQL▶ Try it
WITH actual AS (
  SELECT s.first_name, sum(p.amount_usd) AS total_usd
  FROM students s JOIN payments p ON p.student_id = s.student_id
  GROUP BY s.first_name
),
expected (first_name, total_usd) AS (
  VALUES ('Srihitha', 1700.00), ('Navika', 450.00)
)
SELECT 'missing' AS problem, * FROM (SELECT * FROM expected EXCEPT SELECT * FROM actual) m
UNION ALL
SELECT 'unexpected', * FROM (SELECT * FROM actual EXCEPT SELECT * FROM expected) u;
Output
 problem | first_name | total_usd
---------+------------+-----------
(0 rows)

Explanation: Zero rows means the query returned exactly the expected totals: nothing missing and nothing extra. If someone changed the JOIN to a LEFT JOIN, Advitha would appear with a NULL total, and this test would report her as unexpected. Two notes: EXCEPT compares sets, so it ignores duplicate rows and row order; when order or duplicates matter (a ranked list, for example), compare the rows in order in your test code instead.

Expected EXCEPT actual and actual EXCEPT expected: both empty means the result is right

Testing Migrations

A migration test applies every migration to an empty database and then checks the result. Run it in CI on every change, so a broken migration is caught before it reaches production (Schema Migrations). After the migrations run, you can check the schema itself:

SQL▶ Try it
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'payments'
  AND column_name IN ('payment_id', 'amount_usd', 'method')
ORDER BY ordinal_position;
Output
 table_name | column_name |     data_type     | is_nullable
------------+-------------+-------------------+-------------
 payments   | payment_id  | integer           | NO
 payments   | amount_usd  | numeric           | NO
 payments   | method      | character varying | YES
(3 rows)

Explanation: information_schema.columns describes every column, so a test can check that amount_usd is numeric and required, and that method may be NULL. Good migration tests also check that the migrations run twice in a row without error where they should be repeatable, that a database with realistic data (not just an empty one) migrates cleanly, and that the app's own tests pass against the migrated schema.

Running SQL Tests in Python

In a real project, these tests live next to the application code and run with its test runner. Here is a pytest file for the Fee Tracker, using psycopg (SQL from Python). The conn fixture gives each test a connection inside a transaction that is always rolled back:

Python
import os
 
import psycopg
import pytest
from psycopg import errors
 
CONNINFO = "host=localhost port=5432 dbname=feetracker_test user=fee_app"
 
@pytest.fixture
def conn():
    """A connection whose changes are rolled back after each test."""
    with psycopg.connect(CONNINFO,
                         password=os.environ["FEE_DB_PASSWORD"]) as c:
        with c.transaction(force_rollback=True):
            yield c
 
def unpaid_students(conn):
    rows = conn.execute(
        "SELECT first_name FROM students s"
        " WHERE NOT EXISTS (SELECT 1 FROM payments p"
        "                   WHERE p.student_id = s.student_id)"
        " ORDER BY first_name").fetchall()
    return [name for (name,) in rows]
 
def add_payment(conn, student_id, course_id, amount):
    conn.execute(
        "INSERT INTO payments"
        " (student_id, course_id, amount_usd, due_on, paid_on, method)"
        " VALUES (%s, %s, %s, '2026-01-05', '2026-01-05', 'card')",
        (student_id, course_id, amount))
 
def test_unpaid_students_with_sample_data(conn):
    assert unpaid_students(conn) == ["Advitha"]
 
def test_paying_removes_student_from_unpaid_list(conn):
    add_payment(conn, 102, 1, "450.00")         # Advitha pays
    assert unpaid_students(conn) == []
 
def test_negative_amount_is_refused(conn):
    with pytest.raises(errors.CheckViolation):
        add_payment(conn, 101, 1, "-5.00")
 
def test_payment_needs_an_enrollment(conn):
    with pytest.raises(errors.ForeignKeyViolation):
        add_payment(conn, 103, 1, "450.00")     # Navika isn't enrolled
 
def test_previous_test_left_no_rows_behind(conn):
    count = conn.execute("SELECT count(*) FROM payments").fetchone()[0]
    assert count == 7

Run with pytest -v test_fees.py:

Output
============================= test session starts ==============================
collecting ... collected 5 items
 
test_fees.py::test_unpaid_students_with_sample_data PASSED               [ 20%]
test_fees.py::test_paying_removes_student_from_unpaid_list PASSED        [ 40%]
test_fees.py::test_negative_amount_is_refused PASSED                     [ 60%]
test_fees.py::test_payment_needs_an_enrollment PASSED                    [ 80%]
test_fees.py::test_previous_test_left_no_rows_behind PASSED              [100%]
 
============================== 5 passed in 0.08s ===============================

Explanation: transaction(force_rollback=True) opens a transaction and rolls it back when the test finishes, pass or fail, so each test sees the original 7 payments. The second test adds a payment for Advitha, and the last test proves it was undone. pytest.raises(errors.CheckViolation) passes only if that exact error happens, the same idea as the EXCEPTION WHEN handler above. The same pattern works in Java with JUnit (a @BeforeEach that turns off auto-commit and an @AfterEach that rolls back; Spring's @Transactional tests do this automatically) and in Node.js with Jest or Vitest and one client per test.

Five tests, each rolled back: all 5 passed

Common Mistakes

Testing against a shared or production database. Results change under you, and tests can damage real data. Use a disposable database.

Testing on a different engine. SQLite or an in-memory fake hides PostgreSQL-specific behavior. Test on the engine you run.

Tests that depend on each other's data. One failure causes a chain of failures, and running tests in a different order breaks them. Roll back after each test.

Catching any error as success. A test that expects a check violation should fail on a syntax error. Catch the specific error.

Comparing results without ORDER BY. Rows come back in any order unless you sort them; sort, or compare as sets.

Never testing migrations from scratch. A migration that only works on your laptop's database fails on a new server. Build the test database from migrations in CI.

Interview Corner

How do you keep database tests independent of each other?

Run each test in a transaction and roll it back at the end, or build a fresh database (or copy a template) for each test run, so every test starts from the same known data.

How would you test that a constraint works?

Try to insert a row that breaks it and assert that the specific error is raised, such as CheckViolation (SQLSTATE 23514). Also test that a valid row is accepted.

How do you check that a query returns exactly the right rows?

Compare it with expected rows from known fixtures: expected EXCEPT actual and actual EXCEPT expected should both be empty, or compare ordered lists in the test code when order matters.

Why not test a PostgreSQL app with SQLite?

They differ in types, functions, constraints and error codes, so tests can pass on SQLite and fail in production. Use the same engine and major version.

Practice

Challenge: Write a SQL test that checks the rule "every payment belongs to an enrollment": insert a valid payment for Navika's own course (course 5) inside a transaction, assert that she now has 3 payments, then roll back and show that she has 2 again.

Show solution
SQL▶ Try it
BEGIN;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 225.00, '2026-01-15', '2026-01-14', 'card');
 
DO $$
BEGIN
  ASSERT (SELECT count(*) FROM payments WHERE student_id = 103) = 3,
         'Navika should have 3 payments inside the test';
END $$;
 
ROLLBACK;
 
SELECT count(*) AS navika_payments FROM payments WHERE student_id = 103;
Output
BEGIN
 
INSERT 0 1
 
DO
 
ROLLBACK
 
 navika_payments
-----------------
               2
(1 row)

The valid payment is accepted because Navika is enrolled in course 5, the assertion passes inside the transaction, and ROLLBACK restores her 2 payments. Together with the refusal test earlier, this checks both sides of the rule: valid rows are accepted and invalid ones refused.

Quick check: Testing SQL

4 questions
1Why roll back after each test?
2A test expects a check violation but the INSERT has a typo in a column name. What should happen?
3expected EXCEPT actual returns one row. What does it mean?
4Which database should tests for a PostgreSQL app use?

Key Takeaways

You want toUse
Fail when a condition is falseDO $$ BEGIN ASSERT cond, 'message'; END $$;
Undo a test's changesBEGIN; ... ROLLBACK; or transaction(force_rollback=True)
Expect a specific error in SQLEXCEPTION WHEN check_violation THEN ...
Expect a specific error in pytestwith pytest.raises(errors.CheckViolation):
Compare result setsexpected EXCEPT actual and actual EXCEPT expected
Check the schemainformation_schema.columns

Was this tutorial helpful?

Lesson 106 of 115