If you work with databases, you know that a poorly optimized SQL query can slow down your application, frustrate users, and overload your server. Optimizing your queries is not just a technical chore—it is a way to improve user experience and ensure your system scales smoothly. In this article, I share practical tips with clear examples inspired by real-world scenarios such as online stores, CRM systems, social networks, and financial analytics. Each tip includes code snippets, impact metrics, and troubleshooting tools so you can easily apply them to your projects. Let’s get started!
1. Select Only the Columns You Truly Need
Using SELECT * is tempting because it is fast to write, but it can be a costly mistake. Fetching unnecessary columns wastes bandwidth, memory, and CPU cycles, especially if your table stores heavy data types like images (BLOB) or long text fields (TEXT). The solution is straightforward: select only the columns you are actually going to use.
Practical Example: Product Listing in an Online Store
Context: Imagine an e-commerce website displaying a list of products with their name, price, and category. The products table contains 1 million rows, but it also includes heavy columns like image (BLOB type, ~500 KB per image) and description (TEXT type, ~2 KB).
Suboptimal Query (Loads Unnecessary Data):
SELECT * FROM products WHERE category = 'Electronics';
The Problem: This query fetches every column, including image and description. For 1 million rows, that transfers roughly 500 GB of data (500 KB per row). Under moderate load in PostgreSQL, this takes around 10 seconds to execute.
Optimized Query (Targeted Projection):
SELECT name, price, category
FROM products
WHERE category = 'Electronics';
The Solution: By selecting only the required columns, you reduce data transfer to around 10 MB (10 KB per row). Execution time drops to 0.5 seconds.
How to Spot the Issue:
In PostgreSQL, you can inspect column sizes:
SELECT pg_column_size(image) AS image_size, pg_column_size(description) AS desc_size
FROM products LIMIT 1;
-- Resultado: image_size ~ 500 KB, desc_size ~ 2 KB
In MySQL, inspect the column data types:
SELECT column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'products';
Benefits:
- Significantly less data transferred: Down from 500 GB to 10 MB.
- Faster response times: Down from 10 seconds to 0.5 seconds.
- Built for traffic spikes: Essential for high-demand events like Black Friday.
Bonus Tip: If you rarely access heavy columns such as image, consider moving them to a dedicated table with a 1:1 relationship. This keeps your primary table lightweight and cache-friendly.
2. Leverage Indexes to Speed Up Searches
Indexes act like a book index: they allow the engine to locate data quickly without scanning every single page. They are essential for speeding up WHERE filters, JOIN conditions, and ORDER BY clauses. However, be cautious: indexes add overhead to inserts and updates, so use them strategically.
Practical Example: Logistics Order Reports
Context: A logistics application generates daily order reports filtered by region and status. The orders table contains 10 million rows.
Query Without an Index (Slow):
SELECT id, total
FROM orders
WHERE region = 'EU' AND status = 'Pending';
The Problem: Without an index, the database performs a full table scan across all 10 million rows, taking roughly 8 seconds.
Query with a Composite Index:
CREATE INDEX idx_orders_region_status ON orders (region, status);
SELECT id, total
FROM orders
WHERE region = 'EU' AND status = 'Pending';
The Solution: The composite index enables an Index Scan, slashing execution time down to 0.1 seconds.
Verifying Index Usage:
EXPLAIN SELECT id, total FROM orders WHERE region = 'EU' AND status = 'Pending';
-- Resultado: Index Scan using idx_orders_region_status
Benefits:
- Faster execution: From 8 seconds to 0.1 seconds.
- Ideal for real-time reporting: Perfect for logistics dashboards.
- Watch out for write-heavy workloads: If your table handles high write throughput (e.g., 1,000 orders per minute), measure the write overhead introduced by new indexes.
Bonus Tip: In MySQL, use EXPLAIN FORMAT=JSON for an in-depth breakdown of the execution plan.
3. Simplify JOINs with EXISTS or Subqueries
While JOINs are powerful, they can become expensive when processing more rows than necessary. When you only need to verify whether a record exists (such as checking whether a customer meets certain criteria), using EXISTS or targeted subqueries is often much more efficient than a full JOIN.
Practical Example: VIP Customers in a CRM
Context: A CRM application needs to identify VIP customers who placed orders over $10,000 in 2024. The customers table has 500,000 rows, and orders has 50 million rows.
Expensive JOIN:
SELECT DISTINCT c.id, c.name
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.order_date >= '2024-01-01' AND o.total > 10000;
The Problem: It processes 50 million rows and generates duplicate customer rows that must then be filtered out, taking 15 seconds.
Optimized Solution Using EXISTS:
SELECT c.id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
AND o.order_date >= '2024-01-01'
AND o.total > 10000
);
The Solution: The database engine short-circuits as soon as it finds a matching row, dropping query execution time to 0.8 seconds.
Benefits:
- Substantially faster: From 15 seconds to 0.8 seconds.
- Better scalability: Performs well even against massive tables.
Bonus Tip: In MySQL, if EXISTS is not fast enough, benchmark against IN with indexed columns. Use EXPLAIN to compare both approaches:
EXPLAIN SELECT c.id, c.name FROM customers c WHERE EXISTS (...);
4. Filter as Early as Possible and Avoid Functions on Indexed Columns
Wrapping indexed columns in functions like MONTH() or UPPER() prevents the optimizer from using the index, leading to full scans. Whenever possible, rewrite your queries to filter directly against raw values or range boundaries.
Practical Example: Financial Reporting
Context: A financial analytics system generates transaction reports for May 2024. The transactions table contains 100 million rows with an index on transaction_date.
Suboptimal Query (Invalidates the Index):
SELECT * FROM transactions
WHERE MONTH(transaction_date) = 5 AND YEAR(transaction_date) = 2024;
The Problem: Using MONTH() and YEAR() prevents the engine from leveraging the index, forcing a scan over 100 million rows that takes 20 seconds.
Optimized Query (SARGable, Uses the Index):
SELECT * FROM transactions
WHERE transaction_date BETWEEN '2024-05-01' AND '2024-05-31';
The Solution: Filtering by an explicit range lets the database use the index on transaction_date, reducing execution time to 0.5 seconds.
Advanced Technique: For very large tables, consider table partitioning by date range:
CREATE TABLE transactions (
id BIGINT,
transaction_date DATE,
amount DECIMAL(10,2)
) PARTITION BY RANGE (transaction_date);
Benefits:
- Vastly improved performance: From 20 seconds down to 0.5 seconds.
- Scalability: Partition pruning is ideal for massive datasets.
Bonus Tip: Use EXPLAIN ANALYZE in PostgreSQL to confirm that the index range scan is being executed as expected.
5. Use Keyset Pagination to Avoid Slow Queries
When presenting paginated data (such as a social feed), using OFFSET becomes problematic on large tables because the database must scan and discard all preceding rows. Keyset pagination (also known as the seek method) avoids this overhead entirely.
Practical Example: Social Media Feed
Context: A social platform displays posts sorted by post_id. The posts table contains 50 million rows.
Slow Query Using OFFSET:
SELECT id, content FROM posts ORDER BY post_id DESC LIMIT 10 OFFSET 10000;
The Problem: The engine must read 10,010 rows just to skip the first 10,000, taking 12 seconds.
Keyset Pagination:
SELECT id, content FROM posts
WHERE post_id < 49000000 -- Último post_id de la página anterior
ORDER BY post_id DESC LIMIT 10;
The Solution: Seeking directly via the indexed post_id column cuts execution time down to 0.2 seconds.
Implementation: Pass the post_id of the last seen item in your pagination parameters, for example: /feed?last_id=49000000.
Benefits:
- Fast response times: From 12 seconds to 0.2 seconds.
- Consistent latency: Performance remains constant regardless of page depth.
Bonus Tip: Ensure the column used for keyset pagination (such as post_id or created_at) is indexed.
6. Use EXPLAIN to Understand What Is Happening
The EXPLAIN command acts like an X-ray for your queries: it reveals how the engine plans and executes them, pointing out bottlenecks, missing indexes, and expensive intermediate steps.
Practical Example: Product Inventory
Context: An inventory system looks up products priced above $100 with orders placed in 2024. Tables involved: products (1 million rows) and orders (10 million rows).
Query Being Analyzed:
EXPLAIN ANALYZE
SELECT p.name, o.quantity
FROM products p
JOIN orders o ON p.id = o.product_id
WHERE p.price > 100 AND o.order_date >= '2024-01-01';
Output (PostgreSQL):
Nested Loop (cost=0.85..12345.67 rows=5000 width=40) (actual time=0.050..1500.123 ms)
-> Seq Scan on products p (cost=0.00..5000.00 rows=10000 width=20)
Filter: (price > 100)
-> Index Scan on orders o (cost=0.85..7.34 rows=500 width=20)
Index Cond: (product_id = p.id)
Filter: (order_date >= '2024-01-01')
What This Tells Us: The Seq Scan on products shows that an index on price is missing. Adding the index resolves the issue:
CREATE INDEX idx_products_price ON products (price);
Impact: Lowers execution time from 1.5 seconds to 0.3 seconds.
Benefits:
- Clear diagnostics: Uncover full table scans (
Seq Scan) or high-cost sorts. - Precise indexing: Add indexes only where the execution plan proves they are needed.
Bonus Tip: Visual query plan analyzers in tools like pgAdmin (PostgreSQL) or MySQL Workbench make complex execution plans much easier to digest.
7. Batch Updates and Inserts to Prevent Lock Contention
Massive write operations, like updating millions of rows at once, can lock entire tables, leading to lock contention and blocking end-user transactions. Splitting changes into smaller batches keeps your application responsive.
Practical Example: Black Friday Price Adjustments
Context: An e-commerce store applies a 10% discount to all products in the “Clothing” category for Black Friday. The products table has 5 million rows.
Problematic Query (Extended Table Lock):
UPDATE products SET price = price * 0.9 WHERE category = 'Clothing';
The Problem: Locks the table for 30 seconds, blocking users trying to browse or complete purchases.
Batched Approach:
BEGIN
FOR i IN 1..500 LOOP
UPDATE products
SET price = price * 0.9
WHERE category = 'Clothing'
AND id BETWEEN ((i-1)*10000 + 1) AND (i*10000);
COMMIT;
PERFORM pg_sleep(0.1); -- Pausa breve para no saturar
END LOOP;
END $$;
The Solution: Processing rows in batches of 10,000 takes only 0.1 seconds per chunk, completing the overall update without blocking user traffic.
For Bulk Inserts:
INSERT INTO orders (customer_id, total)
VALUES (1, 100), (2, 200), ...; -- Hasta 1,000 filas por lote
Benefits:
- Zero application freezes: End-users experience no downtime or query timeouts.
- Resource stability: Prevents sudden I/O and CPU spikes on the database host.
Bonus Tip: Automate batch tasks using Python workers (with psycopg2) or stored procedures depending on your deployment model.
8. Monitor and Maintain Your Databases
SQL optimization is not a one-time task. As your dataset grows and traffic patterns shift, you must continuously monitor query performance and refine indexes, queries, and engine settings.
Key Tools:
- Slow query logs: Enable
log_min_duration_statementin PostgreSQL orslow_query_login MySQL. - Engine metrics: Utilize
pg_stat_statements(PostgreSQL) orperformance_schema(MySQL). - APM and observability: Platforms like New Relic, Datadog, or Percona Monitoring provide end-to-end visibility.
Example: Enabling Slow Query Logging in PostgreSQL
SET log_min_duration_statement = 1000; -- Registra consultas que toman más de 1 segundo
Benefit: Identify slow queries in production before they impact your users.
Make Optimization a Regular Habit
Optimizing SQL queries goes far beyond applying quick syntax tricks—it is about keeping your systems resilient, fast, and cost-effective. A poorly designed query can cause latency issues, inflate infrastructure costs, and limit your application’s growth. Conversely, every tuned query brings you closer to a system capable of handling higher throughput with predictable performance.
By selecting only needed columns, indexing strategically, avoiding non-SARGable predicates, and analyzing plans with EXPLAIN, you can achieve significant performance gains. Try these techniques in your environments and make query tuning an integral part of your development workflow.
Are slow SQL queries dragging down your applications? Start optimizing today and take your database performance to the next level.