One Missing Bracket Adds 40% Extra Rows to Your Report

Beginner 4 min read Updated 30 Jul 2026 UPA AI Partner

The query runs, throws no error, and returns exactly 40% too much. The cause is an operator precedence rule nobody teaches you.

The problem

You need VIP customers in Vietnam or the US. The query writes itself:

SELECT * FROM customers
WHERE country = 'VN' OR country = 'US' AND vip = 1;

It returns non-VIP Vietnamese customers too. No syntax error anywhere.

✗ Không có ngoặc✓ Có ngoặcidtenquoc_giavip1AnVN12BenUS03ChiVN0Ben lọt vào vì AND chạy trước ORidtenquoc_giavip1AnVN12BenUS03ChiVN0Chỉ An thoả cả hai vế

The common mistake

SQL has precedence just like arithmetic: NOT > AND > OR. The engine reads your query as:

WHERE country = 'VN'
   OR (country = 'US' AND vip = 1);

Which means “every Vietnamese customer, plus American customers who are VIP”. Not what you asked for.

The rule Whenever a WHERE clause contains both AND and OR, bracket the OR part. No exceptions.

The fix

SELECT * FROM customers
WHERE (country = 'VN' OR country = 'US')
  AND vip = 1;

For longer lists, IN is shorter and harder to get wrong:

WHERE country IN ('VN','US','SG','TH')
  AND vip = 1;

The companion trap: NOT and NULL

-- Silently drops rows where country IS NULL
WHERE country NOT IN ('VN','US')

-- Safe
WHERE (country NOT IN ('VN','US') OR country IS NULL)

NULL is neither equal nor unequal to anything, so those rows quietly disappear.

BETWEEN includes both ends

WHERE age BETWEEN 18 AND 25   -- 18 and 25 included

Never use BETWEEN on timestamps. BETWEEN '2026-01-01' AND '2026-01-31' misses everything after midnight on the 31st. Use >= start AND < next_day.

Practice

  • LeetCode 595 — Big Countries
  • LeetCode 584 — Find Customer Referee (the classic NULL trap)
  • LeetCode 1148 — Article Views I
  • HackerRank — Weather Observation Station 6 through 12

Key takeaways

  • AND always binds tighter than OR.
  • Mixing both in one WHERE means you must use brackets.
  • Use IN instead of long OR chains.
  • NOT IN silently drops NULL rows.
  • Never use BETWEEN on timestamps.

You have just learned AND, OR và dấu ngoặc

Ready to practise?

Work through AND, OR và dấu ngoặc exercises on real data, graded the moment you hit run.

Start practising →