Unlocking the Power of Efficient SQL Queries
Shrishail Wali
Software Engineer | Backend & Gen AI Enthauist | Python, Java, Javascript
Best Practices for Speed and Scalability
Always order your joins from largest table to smallest table: This will help to improve the performance of your queries by reducing the number of rows that need to be joined.
SELECT
FROM orders
INNER JOIN customers ON orders.customer_id = customers.id;
Always "group by" by the attribute/column with the largest number of unique entities/values: This will help to improve the performance of your queries by reducing the number of rows that need to be processed.
SELECT gender, COUNT(*) AS total_count
FROM employees
GROUP BY gender;
Avoid subqueries in the WHERE clause: A subquery is a query nested within another query. Using subqueries in the WHERE clause can make your queries less readable and can also make them less efficient. In most cases, it is better to rewrite the query to avoid using subqueries.
SELECT name
FROM Customers
WHERE customer_id IN (SELECT customer_id FROM Orders);
Use this one:
SELECT DISTINCT Customers. name
FROM Customers
JOIN Orders ON Customers.customer_id = Orders.customer_id;
Use MAX instead of RANK: The RANK function returns the rank of a row within a group, with ties being broken by the order in which the rows appear in the table. The MAX function returns the maximum value in a column. In most cases, the MAX function is a more efficient way to get the top row in a group.
SELECT MAX(salary) AS highest_salary
FROM employees;