Development Tips

How to Write Efficient SQL Queries for Web Apps (2026 Guide)

By Ken Key Apr 21, 2024 5 min read Updated Oct 16, 2026

How to Write Efficient SQL Queries for Web Apps (2026 Guide)
The short answer

Efficient SQL starts with measuring: use pgstatstatements or MySQL's performance schema to find queries with the highest total time, then EXPLAIN ANALYZE the worst ones. Add indexes for real filter and join columns, kill N+1 loops with joins or eager loading, and select only the columns you need.

Part of the complete web development guide.

On this page

Most slow web pages I get called about aren’t slow because of the frontend. They’re slow because someone is running 200 queries in a loop, or scanning a table with two million rows because the right index was never added. The fixes are usually boring, and they usually work.

Here’s what actually moves the needle in 2026, from someone who’s spent a lot of time staring at query logs.

How to Write Efficient SQL Queries for Web Apps (2026 Guide)

Start by measuring, not guessing

Before you touch anything, find out which queries are actually slow. In Postgres, pg_stat_statements is the tool you want:

-- Requires: CREATE EXTENSION pg_stat_statements;
SELECT
 calls,
 round(total_exec_time::numeric, 2) AS total_ms,
 round(mean_exec_time::numeric, 2) AS mean_ms,
 rows,
 query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

Sorting by total_exec_time rather than mean_exec_time matters. A query that takes 4ms but runs 50,000 times a day will hurt you more than a report that takes 900ms once an hour. MySQL has the same idea with the performance schema and sys.statement_analysis.

Once you’ve got a suspect, run EXPLAIN (ANALYZE, BUFFERS) on it. Not plain EXPLAIN. You want actual row counts and buffer reads, because the planner’s estimates lie constantly.

How to Write Efficient SQL Queries for Web Apps (2026 Guide): The N+1 problem is still the number one killer

The N+1 problem is still the number one killer

This is the classic. You load 50 orders, then loop through them and hit the database once per order to get the customer. That’s 51 round trips. On localhost it feels fine. Over a real network with 5ms of latency, you just added 250ms to the request for no reason.

// Bad: one query, then N queries
$orders = $db->query("SELECT id, customer_id, total FROM orders LIMIT 50");
foreach ($orders as $order) {
 $customer = $db->query(
 "SELECT name FROM customers WHERE id = ?",
 [$order['customer_id']]
 );
}

// Better: two queries total
$orders = $db->query("SELECT id, customer_id, total FROM orders LIMIT 50");
$ids = array_column($orders, 'customer_id');
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$customers = $db->query(
 "SELECT id, name FROM customers WHERE id IN ($placeholders)",
 $ids
);

Or just use a JOIN and let the database do what it’s built for. Every framework has some version of eager loading (with() in Laravel and Eloquent, selectinload in SQLAlchemy, include in Prisma) that solves this for you. Turn it on.

Indexes: fewer than you think, on the right columns

An index on a column makes reads faster and writes slower, because every insert and update has to maintain it. So don’t index everything. Index the columns you actually filter, join, and sort on.

Column order in a composite index is not arbitrary. For a query like this:

SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
 AND status = 'shipped'
ORDER BY created_at DESC;

You want the index built like this:

CREATE INDEX idx_orders_customer_status_created
 ON orders (customer_id, status, created_at DESC);

Equality columns first, then the range or sort column. Put created_at before status and the planner can’t use it for the sort, so you get a sort step on top of the index scan.

Two more things people miss. First, a function on an indexed column kills the index: WHERE DATE(created_at) = '2026-01-15' won’t use an index on created_at. Write it as a range instead: WHERE created_at >= '2026-01-15' AND created_at < '2026-01-16'. Second, a leading wildcard in LIKE '%term' can’t use a normal B-tree index. If you need that, look at a trigram index (pg_trgm in Postgres) or a proper search tool.

Only select the columns you need

SELECT * is convenient during development and expensive in production. You pull columns you never use, you break index-only scans, and you ship more bytes over the wire. On a table with a few wide text columns, this is a real cost.

-- Slower, and it breaks index-only scans
SELECT * FROM products WHERE category_id = 7;

-- Faster: the index can cover this entirely
SELECT id, name, price FROM products WHERE category_id = 7;

Pagination: stop using big OFFSETs

LIMIT 20 OFFSET 10000 makes the database read and throw away 10,000 rows before it returns your 20. The deeper you page, the slower it gets. Keyset pagination (also called cursor pagination) fixes this by remembering where you left off:

-- First page
SELECT id, title, created_at
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- Next page: pass the last row's created_at and id
SELECT id, title, created_at
FROM posts
WHERE (created_at, id) < ('2026-01-15 09:30:00', 4821)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The row comparison (created_at, id) < (...) is the part people forget. Without the id tiebreaker, rows with identical timestamps get skipped or duplicated across pages. That’s a bug that shows up in production and nowhere else.

Watch for connection overhead

Opening a new database connection per request is slow. The TCP handshake, TLS negotiation, and auth round trips add up fast. Use a persistent connection pool (PgBouncer, or whatever your host provides) and size it to your actual concurrency, not to some big number you picked because it looked safe. Too many connections is its own problem, and Postgres gets unhappy when you push past what the hardware can serve.

If you’re running this on shared hosting, you often can’t tune any of it, and that’s a real constraint. On a properly configured stack (or one where you control the server), most of these fixes take an afternoon. That’s the kind of thing I handle in custom web development work, and it’s usually less about clever code and more about not doing the expensive thing by accident.

A short checklist

  • Find the slow queries with real data before optimizing anything.
  • Kill N+1 loops with JOINs or eager loading.
  • Index equality columns first, then the sort column. Don’t wrap indexed columns in functions.
  • Select specific columns instead of *.
  • Use keyset pagination for anything that pages deep.
  • Pool your connections.

FAQ

How many indexes is too many?

There’s no magic number, but if a table has more indexes than columns, ask why. Every index slows down writes, so keep the ones that earn their keep and drop the rest.

Should I add caching instead of fixing the query?

Fix the query first. Caching a slow query just means you have a slow query and a cache that goes stale. Cache the results that are genuinely expensive and don’t change often.

Does any of this apply to small sites?

Yes, but the order changes. On a small site the N+1 loops and SELECT * calls still bite you the moment traffic shows up. Index tuning matters less until a table gets into the hundreds of thousands of rows.

Have a project like this?

I do custom web development for Long Island businesses. If you need this done right, let’s talk.