CodeEraFree roadmap

Blogs

Best Practices for Writing Efficient SQL Code

Performance  , 3 min read

A slow query usually comes from a few repeating mistakes. These ten habits prevent most of them.

1. Use indexes

An index lets the database find rows without scanning the whole table. Create indexes on columns that appear often in WHERE, JOIN and ORDER BY. Do not index everything: each index slows down INSERT, UPDATE and DELETE, and takes disk space.

2. Use the correct data types

The right type saves space and avoids conversions. If a date is stored as text (varchar), the database converts it on every comparison, which is slow and can stop an index from being used. Pick the smallest type that safely fits your data.

3. Use parameterized queries

A parameterized query has placeholders that are filled in at run time. This blocks SQL injection and lets the database reuse the query plan, because only the values change.

4. Avoid SELECT *

Ask only for the columns you need. Fewer columns means less data to read and send over the network, and the code is clearer about what it uses.

-- instead of this
SELECT * FROM employees;

-- write this
SELECT id, name, salary FROM employees;

5. Choose subqueries carefully

Modern databases optimise many subqueries well, but a correlated subquery that runs once per row can be slow on big tables. If a query is slow, try rewriting it as a JOIN or a temporary table and compare the plans. Make sure the columns used inside the subquery are indexed.

6. Use EXISTS instead of COUNT to check for a row

EXISTS stops as soon as it finds one match. COUNT has to count every matching row first.

-- slower for a yes/no question
SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END
FROM orders WHERE customer_id = 7;

-- faster
SELECT EXISTS (SELECT 1 FROM orders WHERE customer_id = 7);

On SQL Server and Oracle, use IF EXISTS (...) or WHERE EXISTS (...) in the same way.

7. Use UNION ALL when duplicates do not matter

UNION removes duplicate rows, which means extra sorting or hashing. UNION ALL just stacks the two results, so it is faster. Use UNION only when you really need the duplicates removed.

8. Consider stored procedures for repeated work

A stored procedure lives on the server, so only its parameters travel over the network, and the database can reuse its plan. This helps most for queries that run very often.

9. Avoid cursors

A cursor walks through a result one row at a time, which is slow on large data. Prefer set-based operations such as joins and aggregations, which let the database work on all rows at once.

10. Read the query plan

The optimizer picks a plan it believes is cheapest, but it can be wrong. Look at the plan to see what really happens: EXPLAIN in MySQL and PostgreSQL, or the execution plan in SQL Server Management Studio. Check whether your index is used, then adjust the query or the index.

EXPLAIN SELECT name FROM employees WHERE id = 42;