A tiny mistake in SQL that can change everything.
Photo by olav_ahren

A tiny mistake in SQL that can change everything.

If the business asks you: "Pull all sales from the Manchester branch in May and July 2024.”

Do you think the query below returns the correct result?

Article content
Wrong Query

Answer: No. Here’s why

SQL evaluates AND before OR. That means the query is actually read as:

Article content
What actually gets filtered

This will include any order placed before July 1st, 2024, even if it’s not from the Manchester branch.

To fix this, we need to group our conditions properly with parentheses:

Article content
The Correct query

It is important to always be careful with AND/OR precedence in SQL, as it can completely change your results.

To view or add a comment, sign in

More articles by Joyce Fred

Explore content categories