Originally published at Shipped Code.
Most app developers meet the database through an ORM. JPA, SQLAlchemy, Room or Drift hides it well until a list screen gets slow, a duplicate account appears or a migration fails on release day. The database knowledge that prevents those 3 problems is a short list, and you can learn it in the order below.
TL;DR. The 20% you use every day:
- Model data with primary keys, foreign keys and constraints, so the database rejects bad rows.
- Write joins and aggregates by hand, and log the SQL your ORM sends.
- Read
EXPLAIN ANALYZEand add the index your query needs.- Know what a transaction guarantees and which isolation level your code runs at.
- Change the schema only through versioned migrations.
- Apply the same rules to SQLite on the phone (Room, Drift).
- Keep
psqland one GUI client at hand.Read replicas, sharding and a NoSQL primary store can wait until you measure a need for them.
What you'll learn:
- what each of the 7 skills prevents, with one small schema you can reproduce;
- a real before/after index on 1 million rows, and how to read the plan;
- which topics are safe to postpone, and what they cost when you adopt them.
Who this is for and which engine to use
This guide assumes you use an ORM daily and can write a basic SELECT. If WHERE and GROUP BY are new to you, a short SQL tutorial comes first.
The examples run on PostgreSQL 18 (select version() reports 18.7), which is my default for a new backend. It has strict constraints, JSONB columns when part of the data really is free-form, and good tooling. MySQL is a fine choice when the host or the team already runs it; one of my apps, Mockly, runs on MySQL.
On the device, the database is SQLite. The ideas in this post carry over to all three, with different syntax at the edges.
The diagram shows where data lives in a typical app product and where each skill applies.
You can start the same server with Docker and follow along:
docker run --rm -d --name pg -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:18-alpine docker exec -it pg psql -U postgres 1. Let keys and constraints reject bad data
Validation in your API is useful, but it runs in one code path. The database sees every write, whether it comes from the API, an admin script, a batch job or the next developer's quick fix. A primary key, a foreign key, NOT NULL, UNIQUE and CHECK cost a line each and stop whole classes of bugs. The rest of this post uses this schema:
CREATE TABLE app_user ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL UNIQUE, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, user_id bigint NOT NULL REFERENCES app_user(id), status text NOT NULL CHECK (status IN ('pending', 'paid', 'cancelled')), created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE order_item ( order_id bigint NOT NULL REFERENCES orders(id), line_no int NOT NULL, product text NOT NULL, quantity int NOT NULL CHECK (quantity > 0), price_cents int NOT NULL CHECK (price_cents >= 0), PRIMARY KEY (order_id, line_no) ); Here are 4 writes an app could plausibly send, and what PostgreSQL does with them:
INSERT INTO orders (user_id, status) VALUES (999999, 'paid'); INSERT INTO orders (user_id, status) VALUES (1, 'shipped'); INSERT INTO app_user (email) VALUES ('user1@example.com'); INSERT INTO order_item VALUES (1, 3, 'mug', 0, 500); ERROR: insert or update on table "orders" violates foreign key constraint "orders_user_id_fkey" DETAIL: Key (user_id)=(999999) is not present in table "app_user". ERROR: new row for relation "orders" violates check constraint "orders_status_check" DETAIL: Failing row contains (1000002, 1, shipped, 2026-11-24 03:45:35.32946+00). ERROR: duplicate key value violates unique constraint "app_user_email_key" DETAIL: Key (email)=(user1@example.com) already exists. ERROR: new row for relation "order_item" violates check constraint "order_item_quantity_check" DETAIL: Failing row contains (1, 3, mug, 0, 500). The id in the second error is 1000002, although the table held 1,000,000 orders. The rejected first insert had already taken 1000001 from the identity sequence. Gaps in ids are normal, so never use them to count rows or to number invoices.
The UNIQUE on email is the one I would add even if you skip the rest. Two taps on "Sign up" over a slow network can send 2 requests, and only the database can decide that exactly one of them wins. Your API then maps the unique violation to a clear error.
Constraints protect a schema you already have. Deciding what goes in which table in the first place, and when to denormalise on purpose, gets its own schema design post.
2. Write the SQL your ORM hides
An ORM writes good SQL for simple loads and saves. For screens that combine tables, you should be able to write the query yourself, if only to check what the ORM does. This one returns each order of a user with its item count and total:
SELECT o.id, o.status, count(*) AS items, sum(i.quantity * i.price_cents) / 100.0 AS total FROM orders o JOIN order_item i ON i.order_id = o.id WHERE o.user_id = 42 GROUP BY o.id, o.status ORDER BY o.id; id | status | items | total --------+-----------+-------+---------------------- 41 | cancelled | 2 | 243.7500000000000000 100041 | pending | 2 | 85.3000000000000000 200041 | paid | 2 | 136.7800000000000000 ... (10 rows) That is 1 query for the whole screen. The classic ORM version loads the 10 orders, then runs 1 more query per order for its items. That makes 11 round trips for the same data. This is the N+1 problem, and the cure starts with seeing the SQL. Turn on SQL logging in development.
- Spring Boot with Hibernate:
logging.level.org.hibernate.SQL=DEBUGinapplication.properties. - SQLAlchemy:
create_engine(url, echo=True). - Room:
RoomDatabase.Builder.setQueryCallback(...).
Then open the screen once and count the statements. If the count grows with the number of rows, you have N+1. The Java side is covered step by step in the Spring Data JPA N+1 post, and the Python side in FastAPI CRUD with SQLAlchemy 2 and Alembic.
3. Read EXPLAIN ANALYZE and add the right index
A common reason a query in an app backend is slow is a filter or join on a column that has no index. You find them with EXPLAIN ANALYZE, which runs the query and prints the plan PostgreSQL chose, with real row counts and timings.
To see a difference you need data. This script fills the schema with 100,000 users, 1,000,000 orders and 2,000,000 order items. Loading takes well under a minute on a laptop:
SELECT setseed(0.42); INSERT INTO app_user (email, created_at) SELECT 'user' || g || '@example.com', now() - g * interval '1 minute' FROM generate_series(1, 100000) AS g; INSERT INTO orders (user_id, status, created_at) SELECT 1 + (g % 100000), (ARRAY['pending', 'paid', 'cancelled'])[1 + g % 3], now() - g * interval '10 seconds' FROM generate_series(1, 1000000) AS g; INSERT INTO order_item (order_id, line_no, product, quantity, price_cents) SELECT o.id, l, 'product-' || (1 + floor(random() * 500)::int), 1 + floor(random() * 4)::int, 199 + floor(random() * 5000)::int FROM orders o, generate_series(1, 2) AS l; ANALYZE; Now ask for one user's orders, the query behind a "My orders" screen:
EXPLAIN ANALYZE SELECT id, status, created_at FROM orders WHERE user_id = 42; Gather (cost=1000.00..13902.33 rows=10 width=23) (actual time=0.158..12.994 rows=10.00 loops=1) Workers Planned: 2 Buffers: shared hit=7112 read=581 -> Parallel Seq Scan on orders (cost=0.00..12901.33 rows=4 width=23) (actual time=0.816..10.175 rows=3.33 loops=3) Filter: (user_id = 42) Rows Removed by Filter: 333330 Execution Time: 13.025 ms Read it from the inside out. Seq Scan means PostgreSQL read the whole table. 3 processes each threw away 333,330 rows to find 10, and touched 7,693 pages (8 kB each) on the way. 13 ms sounds harmless, but it grows with the table and runs on every visit to that screen.
user_id is a foreign key, so you might expect it to be indexed already. It is not. The PostgreSQL docs say that declaring a foreign key "does not automatically create an index on the referencing columns". Only the referenced side (the primary key) has one. Add it yourself:
CREATE INDEX orders_user_id_idx ON orders (user_id); Bitmap Heap Scan on orders (cost=4.50..43.55 rows=10 width=23) (actual time=0.028..0.053 rows=10.00 loops=1) Recheck Cond: (user_id = 42) Buffers: shared hit=13 read=3 -> Bitmap Index Scan on orders_user_id_idx (cost=0.00..4.50 rows=10 width=0) (actual time=0.022..0.022 rows=10.00 loops=1) Index Cond: (user_id = 42) Execution Time: 0.078 ms I expected a plain Index Scan here and got a Bitmap Index Scan instead. PostgreSQL picked it because the 10 orders sit on 10 different pages; it collects their locations first, then reads the pages in order.
Both use the index, and the number to compare is pages read, which went from 7,693 to 16. Timings move between runs (a second run took 0.161 ms), so judge an index by the scan type and the buffers rather than by one timing.
If you last used EXPLAIN on an older version, 3 things look new in PostgreSQL 18. EXPLAIN ANALYZE prints Buffers lines without the BUFFERS option (plain EXPLAIN still needs it), row counts have decimals (rows=3.33 is an average per process), and index scans add an Index Searches line, left out of the output above.
Warning: Every foreign key column you filter or join on needs its own index, unless it is already the first column of another index. In this schema,
order_item.order_idis covered by the primary key(order_id, line_no), and the join plan usedorder_item_pkey.orders.user_idhad nothing until we added it.
The cluster post PostgreSQL indexes explained with EXPLAIN ANALYZE covers composite indexes, column order and when an index is ignored.
4. Know what your transactions guarantee
A transaction groups statements so they all commit or all roll back. If your API creates an order and its items, both inserts go in one transaction, and a crash between them leaves nothing half written.
What a transaction does not do by default is freeze the data you read. PostgreSQL runs at Read Committed unless you ask for more (SHOW transaction_isolation returns read committed). Each statement sees the data committed before that statement started. A row you read at the start of a transaction can change before you write.
That is how the lost update happens. 2 requests reduce the same stock count, and each one reads the row, computes the new value in application code and writes it back. Both read "stock = 5", both write 4, and one sale disappears without any error. The bug lives in the read-in-code, write-back pattern, so moving it inside a transaction at Read Committed does not fix it.
The simplest fix is to let one UPDATE check the condition and change the row together. Here it stops 2 requests from both paying the same order:
UPDATE orders SET status = 'paid' WHERE id = 100041 AND status = 'pending'; I ran this from 2 sessions at once, with the first one holding its transaction open for 2 seconds. The second session waited, then PostgreSQL rechecked its WHERE against the committed row:
-- session 1 UPDATE 1 -- session 2, after waiting about 1.5 s UPDATE 0 Your code reads the row count. 1 means this request won, 0 means another request already paid the order. For a stock counter, SET stock = stock - 1 WHERE id = ? AND stock > 0 follows the same idea. Other options are SELECT ... FOR UPDATE, a version column for optimistic locking, or a stricter isolation level with retries; each has its place.
The isolation levels post reproduces each level and its anomalies. If you use Spring, @Transactional pitfalls explains why some annotated methods run without a transaction at all.
5. Change the schema only through migrations
A migration is a numbered script that changes the schema, stored in git next to the code. A tool applies the pending ones in order and records which ran in a table in the same database. Flyway or Liquibase on the JVM and Alembic with SQLAlchemy work this way.
Room and Drift on the phone keep only a schema version number in SQLite (user_version) and run your migration code to get from the old version to the new one. Every environment ends up with the same schema, built the same way.
For tables that are already in use, change them in 2 steps, known as expand and contract: first add the new column or table, and deploy code that writes to both the old and new structure. Drop the old one in a later release, once nothing reads it. This matters doubly for mobile backends, because old app versions keep calling your API for months. Zero-downtime schema migrations with Flyway walks through both steps on a real release.
Warning: Do not change a production schema by hand, even "just one column". The next migration was written against the schema in git, so it can fail halfway through on production, or worse, succeed and leave the environments different from each other.
6. Apply the same rules on the phone
On Android and in Flutter apps, the local database is SQLite, usually through Room (Android) or Drift (Flutter). The skills above apply unchanged. Use primary keys and constraints, index the columns your screens filter on, and write a migration for every schema version, since an app update meets whatever schema the old version left on the device.
One SQLite detail catches people coming from PostgreSQL. Foreign keys are declared but not enforced unless the connection runs PRAGMA foreign_keys = ON; the SQLite docs say enforcement is off by default for backwards compatibility. Check what your library does. Drift's documentation enables it in the beforeOpen callback.
Storing data on the phone is the easy half. Keeping it in sync with the server when 2 devices edit the same record is a design problem, covered in the post on offline sync and conflict resolution. For the libraries, see Room in depth: relations, migrations and tests and Offline-first Flutter with Drift (SQLite). If you are still choosing the mobile stack, Native or Flutter? covers that decision.
7. Keep psql and a GUI client at hand
You need a way to look at the data without going through your app. psql ships with PostgreSQL and works over SSH on any server. 4 commands cover most days. \d orders describes a table with its indexes and constraints, \dt lists tables, \timing prints how long each query took, and \x switches wide rows to a vertical layout.
A GUI client is better for browsing data, editing a row in development and reading plans. Which one is worth it is compared in DBeaver vs DataGrip vs TablePlus.
What can wait: replicas, sharding, NoSQL
These topics appear on every database roadmap, and each solves a real problem. For a typical app backend they pay off only after you measure the problem they solve.
| Topic | When it pays off | Main trade-off |
|---|---|---|
| Read replicas | Read load saturates the primary after indexes and query fixes | Replicas lag, so a user may not see the write they just made |
| Table partitioning | Very large tables where you drop old data by time range | Unique constraints must include the partition key, and queries without it scan every partition |
| Sharding | One server can no longer hold the data or the write load | Cross-shard joins and transactions become your problem |
| NoSQL as the primary store | Data really has no relations, or a managed service fits the access pattern exactly | You enforce constraints and joins in application code |
| Redis as a cache | Measured hot reads that are expensive to compute | Invalidation, and stale data when it goes wrong |
Redis deserves a sentence of its own. It is a good cache or job queue next to PostgreSQL, but keep it out of the primary-store role. The data you cannot lose belongs in the database with constraints and backups. How caching fits into a whole backend is covered in System design for app developers, and JPA and transactions on the Java side in the Java backend roadmap.
In this pillar
- PostgreSQL indexes explained with EXPLAIN ANALYZE
- DBeaver vs DataGrip vs TablePlus: database GUI tools from daily use
- Transaction isolation levels: reproduce each anomaly yourself
- Schema design for a mobile backend: normalise first, denormalise on purpose
- Zero-downtime schema migrations with Flyway
If you take only one skill from this list into next week, make it skill 3. Run EXPLAIN ANALYZE on the query behind your slowest screen, then continue with PostgreSQL indexes explained with EXPLAIN ANALYZE.