Tips for
optimizing
SQL queries
like a pro
Dawn Choo
SQL is fun!
Until you have to have to wait
forever for your query to run...
Here are 9 tips for
optimizing your SQL
queries
1
Remove unnecessary
data processing:
DISTINCT
Avoid using DISTINCT when it’s not
necessary. The DISTINCT operation can be
computationally expensive, especially on
large datasets.
InterviewMaster.AI
2
Remove unnecessary
data processing:
ORDER BY
Avoid using ORDER BY until the final
SELECT statement. Your subqueries and
CTEs typically don’t need to be ordered.
InterviewMaster.AI
3
Remove unnecessary
data processing:
UNION
Use UNION ALL instead of UNION when
you’re okay with duplication of rows, or
if you know there won’t be rows
duplicated.
InterviewMaster.AI
4
Remove unnecessary
data processing:
SELECT
Instead of SELECT * , make sure to
SELECT only the specific columns that
you need.
InterviewMaster.AI
5
Take advantage of
indexes on your table:
WHERE
Filter on the index key where possible
to reduce the size of data processed.
InterviewMaster.AI
6
Take advantage of
indexes on your table:
OR
Minimize the use of OR conditions. Using
OR can lead to full table scans which
can be inefficient.
InterviewMaster.AI
7
Take advantage of
indexes on your table:
Avoid functions
Don’t use functions in WHERE clauses,
because it can interfere with the
indexes.
InterviewMaster.AI
8
Reduce cardinality of
JOINS with
CTEs & sub-queries
Use a CTE or subquery to filter and reduce
the size of your tables before JOINs.
InterviewMaster.AI
9
Reduce cardinality of
JOINS:
Using ON vs. WHERE
Filter conditions in the ON vs. WHERE
clause is typically more efficient.
InterviewMaster.AI
Found this
useful?
Save it
Follow me Dawn Choo
Repost it
Looking for SQL practice questions?
Check out free questions on InterviewMaster.AI