A query that scans a million rows to return ten is not slow because the database is slow. It is slow because nobody told the database where to look. Learning how to write faster SQL queries starts with indexing basics: an index is a separate lookup structure that lets the database jump straight to the rows it needs instead of reading the whole table. Used well, an index turns a seconds-long query into a milliseconds-long one. Used badly, it slows down writes and wastes disk.
How to write faster SQL queries
Start by measuring. Run the slow query with EXPLAIN in front of it and read the plan. If the plan says “Seq Scan” on a large table, the database is reading every row. If it says “Index Scan” or “Index Only Scan”, it is using an index. The plan also shows the estimated row counts, which tells you whether the database expects a handful of rows or half the table. Fix the queries that scan large tables first, because they give the biggest return. Guessing which query is slow wastes time; the plan tells you. If you want a repeatable way to measure, benchmarking your VPS shows how to separate a slow query from a slow disk before you start tuning.
How an index works
How an index works is easiest to see with a comparison. Without an index, finding a user by email means reading every row until the match appears, like searching a book by reading every page. With an index on the email column, the database keeps a sorted copy of the emails with pointers to the rows, like the index at the back of a book. It looks up the email, follows the pointer, and reads one row. The cost is storage for the sorted copy and extra work on every insert, update, and delete, because the index must be kept in sync. That trade is worth it for columns you search often, and wasteful for columns you never filter on.
CREATE INDEX idx_users_email ON users (email);
SELECT * FROM users WHERE email = '[email protected]';
When an index helps
When an index helps most is on columns in WHERE clauses, join conditions, and ORDER BY clauses that match the index order. A query that filters by status and orders by created date benefits from a composite index on both columns, in the same order the query uses them. A query that filters on a column with only two distinct values, like a boolean flag, gains little, because the index still points at half the table. Selectivity matters: an index on email, where almost every value is unique, is powerful. An index on a low-cardinality column is mostly overhead. Check your most frequent queries first and index the columns they actually filter on, not the columns that look important.
Check the query plan
Check the query plan after adding an index, not before. Add the index, run EXPLAIN ANALYZE, and confirm the plan changed and the time dropped. If the plan ignores your index, find out why before adding another one. Common reasons: the query wraps the column in a function, which hides it from the index; the table is small enough that a scan is genuinely faster; or the statistics are stale and the planner is guessing wrong. A function on a column, like WHERE LOWER(email) = ..., defeats a plain index on email. The fix is an index on the expression itself, or storing the value in the form you query it. Never assume an index is used. The plan is the only proof.
Indexes have a cost
Indexes have a cost, and it shows up on writes. Every insert must update every index on the table. Every update to an indexed column rewrites index entries. A table with ten indexes can take noticeably longer to write to than the same table with two, and the indexes themselves consume disk and memory that the database could use for caching data. This is why the right number of indexes is a balance, not a maximum. Remove indexes that no query uses. You can find them by checking index usage statistics in PostgreSQL with pg_stat_user_indexes, or the equivalent in MySQL. An unused index is pure cost with no benefit, and dropping one is a safe, reversible change.
Write queries the planner can use
Small habits make queries easier for the planner. Select only the columns you need instead of SELECT *, because a narrow index can answer the whole query without touching the table. Avoid leading wildcards in LIKE patterns, since LIKE '%ana%' cannot use a normal index while LIKE 'ana%' can. Avoid functions on filtered columns, as above. And keep statistics fresh: run ANALYZE after bulk loads so the planner knows the table grew. None of this replaces an index, but each habit makes the indexes you have work harder. The same discipline applies to the schema around the query: if you run MySQL or PostgreSQL on limited memory, MySQL vs PostgreSQL tuning for limited RAM explains how memory settings change what the planner can afford to do.
A short routine for slow queries
When a query is slow, follow the same routine every time. First, run EXPLAIN ANALYZE and find the scan. Second, check whether an index exists on the filtered and joined columns, and whether the plan uses it. Third, add the missing index or fix the query so the existing one applies. Fourth, re-run the plan and confirm the time dropped. Fifth, check that writes on the table did not get noticeably slower. Write the slow query and its fix in a short note for your team, because the same pattern will appear again in another query. And remember that user input in a WHERE clause needs care too: sanitizing user input to prevent SQL injection is part of writing queries that are fast and safe, since a parameterized query is both.
Indexing is not magic. It is a lookup structure with a cost, applied to the columns your real queries filter on, verified with the query plan. Measure first, index second, verify third, and the slow queries get fast one at a time.