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 16/ 160
01. SQL Foundations & Relational Concepts

Logical & Range Operators (AND, OR, NOT, BETWEEN, IN)

Combine predicates with AND/OR/NOT and express ranges with BETWEEN and IN lists.

BeginnerAND / OR / NOT · BETWEEN3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

AND means both must be true, OR means at least one, NOT flips it. Use brackets so the computer reads your rule the way you mean it.

Think of it like…

A shop discount rule: "members AND (spending over ₹500 OR buying on a Sunday)". Without the brackets, it reads as "(members AND spending over ₹500) OR anyone on a Sunday", which is a very different, much more expensive rule.

Where you’ve seen it

Paid or shipped orders from a premium customer: WHERE customer_tier = 'premium' AND (status = 'paid' OR status = 'shipped'), or more simply WHERE customer_tier = 'premium' AND status IN ('paid', 'shipped'). Dropping the parentheses would include every shipped order from any customer.

Words you’ll hear

Precedence
NOT is evaluated first, then AND, then OR.
BETWEEN
Inclusive range: x >= low AND x <= high.
IN
Shorthand for several = conditions joined by OR.
NOT IN trap
x NOT IN (…, NULL) is never true.

Visual diagram

Loading interactive diagram

Theory & example queries

AND, OR, NOT and precedence

Conditions combine with AND (both true), OR (at least one true) and NOT (the opposite). SQL evaluates NOT first, then AND, then OR, just as multiplication comes before addition. So a AND b OR c means (a AND b) OR c. When a condition mixes AND and OR, add parentheses to state the grouping you mean, even when it happens to match the default.

NULLs make the logic three-valued: NOT (x = 1) is UNKNOWN when x is NULL, so negating a condition doesn't bring NULL rows back. Rewriting with De Morgan's laws helps clarity: NOT (a OR b) equals NOT a AND NOT b.

Correct groupingQuery 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  customer_tier = 'premium'7  AND (8    status = 'paid'9    OR status = 'shipped'10  );
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/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative matching orders3 sample rows
Representative matching orders
id
501
518
642

Note: Assumes these premium orders are paid or shipped. Other premium statuses and non-premium orders are excluded.

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

Key takeaway: AND before OR; parenthesise every mix.

BETWEEN and IN, and their traps

BETWEEN 100 AND 500 includes both 100 and 500, which suits integers and dates. On timestamps, BETWEEN '2026-11-01' AND '2026-11-30' stops at midnight on the 30th; use >= '2026-11-01' AND < '2026-12-01' instead. BETWEEN with the bounds reversed (BETWEEN 500 AND 100) returns nothing.

IN is cleaner than a chain of ORs on one column and is usually planned the same way. NOT IN fails badly with NULLs: if the list or subquery contains a NULL, x NOT IN (…) is never true and returns no rows. Use NOT EXISTS for subqueries. For long lists from the application, pass an array (= ANY($1) in PostgreSQL) or join to a VALUES list rather than building thousands of literals.

A list parameter in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  products5WHERE6  id = ANY ($1::BIGINT[]);
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/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative matching products3 sample rows
Representative matching products
idnameprice
11SQL Handbook999
42Mechanical Keyboard2999
77USB-C Hub1799

Note: Assumes an illustrative products table with these columns and all three ids present; result order is unspecified without ORDER BY.

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

with $1 = '{11, 42, 77}' instead of building IN (11, 42, 77) as text.

Key takeaway: BETWEEN is inclusive; NOT IN breaks on NULL; pass long lists as arrays.

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

Write the rule in plain words

Spell out the logic with explicit grouping: "premium customers, and status paid or shipped".

Focus at this step

premium AND (paid OR shipped)

What to watch at this step
Grouping
explicit
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

AND requires both conditions, OR either one, and NOT reverses a condition. BETWEEN a AND b is shorthand for >= a AND <= b, inclusive at both ends. IN (…) checks membership in a list: status IN ('paid', 'shipped'). AND is evaluated before OR, so mixing them without parentheses often means something different from what you intended.

Why it matters: The AND/OR precedence bug returns wrong rows without any error, which makes it one of the most common logic mistakes in reports and access checks. BETWEEN on timestamps and NOT IN with NULLs are two more classic traps that interviewers like to test.

When to reach for it

  • Combining filters on status, dates and amounts
  • Membership checks with IN
  • Integer and date ranges with BETWEEN

When to avoid or be careful

  • Mixing AND and OR without parentheses
  • BETWEEN on timestamp columns
  • NOT IN against data that can contain NULL

IN vs OR chains vs = ANY(array)

IN (list)
Best for: A short fixed list of values for one column

Strengths: Readable; planned efficiently.

Watch out: Building long lists as SQL text is clumsy and risky.

OR chain
Best for: Conditions on different columns

Strengths: Expresses any combination.

Watch out: Easy to get precedence wrong; verbose for one column.

= ANY($1) with an array parameter
Best for: Long or variable lists from the application (PostgreSQL)

Strengths: One parameter, safe and plan-friendly.

Watch out: PostgreSQL syntax; other databases use table-valued parameters or temp tables.

Interview signals & numbers to know

When this topic comes up

  • “The report includes rows it shouldn't”
  • “Orders that are paid or shipped”
  • “Between two dates”
  • NOT IN returns nothing
  • Access-control conditions

Benchmarks & rules of thumb

NOT > AND > OR -
evaluation order
Both ends -
included by BETWEEN
1 NULL -
makes NOT IN return no rows

Common mistakes & follow-ups

Common interview mistakes

  • Writing a AND b OR c and getting every row where c is true.
  • Using BETWEEN on a timestamp and missing most of the end date.
  • Using NOT IN (SELECT …) when the subquery can return NULL.

Likely interviewer follow-ups

  • How does SQL evaluate a AND b OR c?
  • Is BETWEEN inclusive or exclusive?
  • Why can NOT IN return no rows at all?
Interview tip: Show the precedence bug with one example and the parenthesised fix. It's short, memorable, and the kind of bug interviewers have seen in real code.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Logical & Range Operators (AND, OR, NOT, BETWEEN, IN) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Filtering Rows (WHERE, Comparison Operators =, !=, <, >)
Next topic
Pattern Matching (LIKE, ILIKE, Wildcards % and _)