ORDER BY & Sorting: Mistakes
Module: SQL Fundamentals
SELECT * FROM products LIMIT 10;
SELECT * FROM products ORDER BY product_id LIMIT 10;
LIMIT without ORDER BY returns arbitrary rows - results change between queries. Database returns first 10 rows it finds (physical order), which is non-deterministic. Always use ORDER BY with LIMIT for consistent results.
Always ORDER BY indexed column before LIMIT. Ensures consistent results and enables efficient pagination.
High
No error, but unpredictable results
SELECT * FROM employees ORDER BY salary;
CREATE INDEX idx_salary ON employees(salary); SELECT * FROM employees ORDER BY salary;
Sorting large tables without index is slow. Database must read all rows, sort in memory, then return results. With index, database reads rows in sorted order (no sort needed). 1M rows: 5s without index vs 0.1s with index (50x faster).
Always index ORDER BY columns for performance. Use covering indexes when possible.
High
No error, but 50x slower on large tables