Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 15/ 160
01. SQL Foundations & Relational Concepts

Filtering Rows (WHERE, Comparison Operators =, !=, <, >)

Filter result sets with WHERE and comparison operators before aggregation or joins.

BeginnerWHERE · Comparisons3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

WHERE is a question asked of every row. Rows that answer yes stay; the rest are left out.

Think of it like…

Sorting your post: you keep only the letters addressed to you (=), ignore anything marked "to the occupier" (<>), and pick out bills dated after the first of the month (>).

Where you’ve seen it

Orders from November over ₹1,000: SELECT id, amount FROM orders WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01' AND amount > 1000;. Writing created_at <= '2026-11-30' instead would miss every order placed after midnight on the 30th.

Words you’ll hear

Predicate
A condition that's true, false or unknown for each row.
<> / !=
Not equal; both work in most databases, <> is the standard.
Collation
Rules for comparing and sorting text, including case sensitivity.
Half-open range
>= start AND < next start: the safe way to filter dates and times.

Visual diagram

Loading interactive diagram

Theory & example queries

Comparisons and types

A comparison is evaluated for every row, and only rows where it's TRUE are kept. Numbers compare numerically, dates and timestamps chronologically, and text alphabetically according to the column's collation, which also decides whether 'pune' = 'Pune' (true in MySQL's default collations, false in PostgreSQL).

Type mismatches cause quiet bugs. If a number is stored in a text column, '10' < '9' is true because the comparison is character by character. Some databases convert types implicitly, which can also stop indexes being used. Compare values of the same type, casting the constant rather than the column.

Text vs numeric comparisonQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  '10' < '9' AS text_compare,3  10 < 9 AS number_compare;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
text_comparenumber_compare
truefalse

Note: This illustrates lexicographic versus numeric comparison: text starting with 1 sorts before text starting with 9.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns true and false.

Key takeaway: The column's type decides how comparison works; keep types consistent.

Dates, NULLs and indexes

For timestamps, filter with a half-open range: created_at >= '2026-11-01' AND created_at < '2026-12-01'. An end condition like <= '2026-11-30' means midnight at the start of the 30th, so the rest of that day is missed. BETWEEN has the same problem because it's inclusive at both ends.

Any comparison with NULL is UNKNOWN, so WHERE discount <> 10 also drops rows where discount is NULL; add OR discount IS NULL if they should stay. Filters on bare columns can use indexes, while wrapping the column in a function (WHERE DATE(created_at) = …) usually can't.

Not equal, keeping NULLsQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id3FROM4  orders5WHERE6  coupon_code <> 'WELCOME10'7  OR coupon_code IS NULL;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
id
101
103

Note: The sample keeps one order with another coupon and one with no coupon. A plain <> 'WELCOME10' would discard the NULL coupon.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Half-open date ranges, explicit NULL handling, bare columns for indexes.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Requirement

State the condition in words

Write what should be kept: "orders placed in November with amount above 1,000".

Focus at this step

November · amount > 1000

What to watch at this step
Clear
before SQL
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

WHERE keeps only the rows for which its condition is true. Conditions use comparison operators: = (equal), <> or != (not equal), <, >, <= and >=. They work on numbers, text and dates, and the column's type decides how values compare: numbers numerically, text alphabetically by collation, dates chronologically.

Why it matters: Filtering is how you go from millions of rows to the ones that matter, and it's where many subtle bugs hide: missed rows at the end of a date range, NULLs vanishing from not-equal filters, and numbers stored as text comparing alphabetically. It's also where indexes do most of their work.

When to reach for it

  • Every query that needs a subset of rows
  • Date-range reports
  • Status and threshold filters

When to avoid or be careful

  • <= last_day on timestamp columns
  • Comparing numbers stored as text
  • Forgetting that <> excludes NULL rows

Ways to filter a date range

>= start AND < next start
Best for: Timestamps, any period

Strengths: Includes the whole last day; index-friendly; no overlaps between periods.

Watch out: Slightly more to type.

BETWEEN start AND end
Best for: Integers and pure dates

Strengths: Short and readable.

Watch out: Inclusive at both ends, so it misses most of the last day for timestamps.

DATE(col) = … / EXTRACT(…)
Best for: Quick exploration only

Strengths: Easy to write.

Watch out: Usually prevents index use.

Interview signals & numbers to know

When this topic comes up

  • “Orders from last month”
  • “Why are some rows missing?”
  • “Amounts over 1,000”
  • Case-sensitive matching
  • Basic SQL rounds

Benchmarks & rules of thumb

6 -
comparison operators: =, <>, <, >, <=, >=
UNKNOWN -
result of comparing with NULL
'10' < '9' -
true as text

Common mistakes & follow-ups

Common interview mistakes

  • Filtering timestamps with <= '2026-11-30' and losing the last day's orders.
  • Writing WHERE col = NULL instead of IS NULL.
  • Comparing a text column of numbers with a number and getting alphabetical results or a slow scan.

Likely interviewer follow-ups

  • How would you select all orders placed yesterday?
  • Why might WHERE status <> 'cancelled' return fewer rows than expected?
  • Why does '10' < '9' return true?
Interview tip: When a filter involves dates, say "I'll use a half-open range" and write it. It's a small detail that shows real-world experience.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Filtering Rows (WHERE, Comparison Operators =, !=, <, >) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Basic Retrieval (SELECT, Column Aliases AS, DISTINCT)
Next topic
Logical & Range Operators (AND, OR, NOT, BETWEEN, IN)