Query constructs

Optimize your SQL logic with efficient syntax and by avoiding unnecessary operations.

Avoid Unnecessary ORDER BY

Sorting large datasets is expensive. Only use ORDER BY when necessary—and only on reduced result sets.

Instead of:

SELECT ... 
FROM device_data 
ORDER BY reading_time DESC 
LIMIT 10;

Use:

SELECT ...
FROM device_data 
WHERE reading_time >= '2024-12-20' 
ORDER BY reading_time DESC 
LIMIT 10;

Format Output Last

Delay formatting (e.g., with DATE_FORMAT) until the final result step to preserve optimizer flexibility.

Bad:

Better:

Replace CASE in Filtering or Grouping

Avoid using CASE expressions in filters, joins, or groupings when alternatives exist.

Bad:

Better:

Prefer GROUP BY Over DISTINCT

Instead of:

Use:

Use Subqueries When Groups Are Known

If the group keys are known, use correlated subqueries to avoid materializing full group sets in memory.

Instead of:

Use:

Last updated