Suggested slug: a-bad-query-is-a-bad-query
Suggested categories: Oracle, PostgreSQL, SQL Server, Performance Tuning
Suggested tags: SQL tuning, optimizer, indexes, normalization, query performance
A bad query is a bad query.
No matter how much CPU and memory you allot to the database, extra capacity will not fix a query that is asking the database to do unnecessary work. More hardware may make a bad plan finish a little sooner, but it does not change the amount of data the query reads, sorts, joins, and discards.
Think of the optimizer in Oracle, PostgreSQL, or SQL Server as a GPS. It calculates what it believes is the best route to fetch the results, based on the available indexes, statistics, data distribution, and estimated cost of each path.
But a GPS cannot help if the address is wrong, the road does not exist, or you ask it to visit every house in the city before reaching your destination. In the same way, the optimizer cannot invent a good access path when the query design or the database design prevents one.
Where bad queries hide
1. Functions and case-insensitive searches on indexed columns
SELECT * FROM customers WHERE LOWER(email) = 'sandeep@example.com';
Wrapping email in LOWER() can prevent a normal index on email from being used efficiently. The database may have to scan the table and evaluate the function for every row.
Better options include storing the email in a consistent normalized form, using a case-insensitive collation or type where appropriate, or creating an index that matches the expression being searched.
The same problem appears with dates:-- Harder for the optimizer to use an index on created_at WHERE TRUNC(created_at) = DATE '2026-12-03' -- A range predicate gives the optimizer a clean access path WHERE created_at >= DATE '2026-12-03' AND created_at < DATE '2026-12-04'
This is called making the predicate sargable: write it so the database can search an index instead of inspecting every row.
2. LEFT JOINs that multiply work
A LEFT JOIN is not bad by itself. The problem starts when large tables are joined without suitable indexes or selective predicates, and the optimizer is left with a nested-loop plan that probes the inner table again and again.
Joining first and filtering later can also create a huge intermediate result, only to throw most of it away. Filter as early as the logic allows, join on properly indexed keys, and check whether the join is multiplying rows unexpectedly.
Also watch for a WHERE condition on the right-hand table that quietly turns your LEFT JOIN into an inner join. If unmatched rows must be preserved, that condition may belong in the ON clause.
3. UNION when UNION ALL is enough
SELECT customer_id FROM orders_2025 UNION SELECT customer_id FROM orders_2026;
UNION removes duplicates, so the database must sort or hash the combined result. If duplicates are impossible, or duplicates are acceptable for the requirement, use UNION ALL and avoid paying for deduplication you do not need.
4. NULL handling that changes the result
SELECT * FROM customers c WHERE c.customer_id NOT IN ( SELECT o.customer_id FROM orders o );
If the subquery returns even one NULL, NOT IN can return no rows at all. That is not just a performance issue; it is a correctness issue.
For an anti-join, NOT EXISTS usually expresses the intent more safely:SELECT * FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id );
5. Correlated subqueries executed row by row
A correlated subquery can turn one query into thousands or millions of small executions: once for every row returned by the outer query. Sometimes a join, EXISTS, a common table expression, or a window function lets the optimizer process the data in bulk instead.
The goal is not to avoid subqueries at all costs. The goal is to understand how many times the work is being repeated.
6. Deep pagination with OFFSET
SELECT * FROM orders ORDER BY created_at DESC, order_id DESC OFFSET 100000 ROWS FETCH NEXT 20 ROWS ONLY;
To return page 5,001, the database still has to find, sort, and skip the first 100,000 rows. The deeper the page, the more work is discarded.
For large result sets, keyset pagination is usually much faster: remember the last key from the previous page and ask for rows after it.SELECT * FROM orders WHERE (created_at, order_id) < (:last_created_at, :last_order_id) ORDER BY created_at DESC, order_id DESC FETCH FIRST 20 ROWS ONLY;
Exact syntax varies by database, but the principle is the same: seek to the starting point instead of counting past every earlier row.
Fix the design, not just the server
Many slow queries are symptoms of a poorly organized database:
- The same customer name, address, and status repeated on every order row
- Comma-separated lists stored in one column instead of child rows
- Numbers and dates stored as text
- No primary keys, foreign keys, or uniqueness constraints
- Indexes that do not match the predicates and joins the application actually runs
- Statistics that no longer describe the data
Normalizing the data — customers in one table, orders in another, order items in a third, each fact stored once and connected by keys — gives the optimizer a cleaner model to work with. Updates touch fewer rows, constraints protect integrity, and indexes can be built around real access paths.
Normalization is not magic, and reporting workloads sometimes need carefully designed summary tables. But deliberate denormalization for a measured reporting need is very different from accidental duplication everywhere.
Organizing the database also means:
- Using the correct data types
- Indexing foreign keys and common join/filter columns
- Keeping optimizer statistics current
- Archiving or partitioning old data where appropriate
- Returning only the columns and rows the application needs
The DBA checklist
Before asking for more CPU or memory, ask:
- How many rows does the query read to return its result?
- Is the predicate sargable, or is a function wrapped around the indexed column?
- Is a join multiplying rows?
- Is
UNIONdoing deduplication that nobody asked for? - Can a
NULLchange the meaning of the query? - Is a subquery repeating work row by row?
- Is pagination scanning and discarding thousands of rows?
- Are the statistics and indexes aligned with the real workload?
Adding capacity treats the symptom. Fixing the query and organizing the data treats the cause.
A bigger engine helps a good car go faster. It does not turn a wrong route into the right one.
Leave a Reply