TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1409 284
🐛 SPOT THE BUG #5
Language: SQL

sql
SELECT customer_id, COUNT(*) as order_count
FROM orders
WHERE order_date > '2024-01-01'
GROUP BY customer_id
ORDER BY order_count DESC
LIMIT 1;


Goal: find the customer with the most orders after Jan 1st, 2024.

Looks right at first glance - what's the subtle issue? 👇

.
.
.

The bug: LIMIT 1 silently drops any ties. If TWO customers are tied for the most orders, this query arbitrarily returns just one of them (and which one is returned isn't guaranteed to be consistent across database engines or even across runs).

If the actual requirement is "find ALL customers tied for the most orders," this query quietly gives a wrong (incomplete) answer that LOOKS correct.

Fixed version (handles ties):
sql
WITH ranked AS (
SELECT customer_id, COUNT(*) as order_count,
RANK() OVER (ORDER BY COUNT(*) DESC) as rnk
FROM orders
WHERE order_date > '2024-01-01'
GROUP BY customer_id
)
SELECT customer_id, order_count
FROM ranked
WHERE rnk = 1;


💡 This is a great example of why clarifying requirements matters even in SQL questions - "top 1" and "all customers tied for the top spot" are genuinely different problems, and a query that's correct for one is silently wrong for the other.

Have you ever shipped a query that "worked" but quietly handled ties incorrectly? 👇
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →