Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

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
Data Science topics
Lesson 22/ 160
02. SQL & Data Engineering Basics

SELECT, WHERE, ORDER BY & Filtering

Write precise SELECT queries with filters, sorting, LIMIT, and NULL-safe comparisons.

BeginnerSELECT · WHERE3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

You tell the database exactly which columns and rows you want, in what order, and how many, so you only download what you need.

Think of it like…

Ordering from a menu instead of carrying home the whole kitchen: you name only the dishes (columns) and conditions (filters) you want, and ask for the first few to taste before ordering more.

Where you’ve seen it

A data scientist needs last quarter's paid orders over ₹500 for one region. Instead of pd.read_sql("SELECT * FROM orders", ...) (180 million rows), she runs SELECT order_id, customer_id, amount, created_at FROM orders WHERE created_at >= :start AND created_at < :end AND status = 'paid' AND amount > 500 AND region = :region, getting 410,000 rows in 3 seconds. Her first attempt used WHERE coupon = NULL to find orders without a coupon and returned nothing; IS NULL fixed it.

Words you’ll hear

SELECT list
The columns (and expressions) returned; name them instead of using SELECT *.
WHERE
Row filter evaluated before grouping; supports AND, OR, IN, BETWEEN, LIKE and IS NULL.
Three-valued logic
Comparisons with NULL are unknown, so rows with NULLs are excluded unless handled.
Bound parameters
Values passed separately from the SQL text, which prevents injection and quoting mistakes.

Visual diagram

Loading interactive diagram

Theory & deep dive

Writing precise filters

Combine conditions with AND and OR (use parentheses, since AND binds tighter), IN ('paid', 'refunded') for sets, BETWEEN for inclusive ranges (careful with timestamps: created_at BETWEEN '2026-01-01' AND '2026-01-31' excludes most of 31 January, so prefer >= '2026-01-01' AND < '2026-02-01'), and LIKE 'IN-%' for patterns. Comparisons with NULL yield unknown, so coupon <> 'SAVE10' excludes rows where coupon is NULL; add OR coupon IS NULL if you want them. Boolean traps like NOT IN (subquery) returning nothing when the subquery has a NULL are covered in the SQL track.

Sort with ORDER BY amount DESC, created_at (add a tie-breaker such as the id for reproducibility), and use LIMIT 1000 for exploration; without ORDER BY the rows returned by LIMIT are arbitrary, so don't treat them as a sample. For a random sample use the database's feature (TABLESAMPLE, ORDER BY random() LIMIT n on small tables, or a hash of the id modulo n) so it's reproducible.

A reproducible 1% sample

SELECT * FROM events WHERE abs(hashtext(user_id::text)) % 100 = 0 selects the same 1% of users every time (PostgreSQL), which keeps all of a user's events together, unlike a random row sample.

Key takeaway: Half-open date ranges, NULL-aware logic, deterministic ORDER BY and samples.

Running SELECT from Python safely

Use SQLAlchemy or the driver's parameter style: pd.read_sql(text("SELECT ... WHERE created_at >= :start"), engine, params={"start": start}). Never build SQL by pasting user-supplied values with f-strings, which breaks on quotes and is an injection risk. Select explicit columns, push filters and simple aggregations to the database, and set dtypes after loading (parse_dates, dtype) so IDs and dates are typed correctly.

For large results stream in chunks (chunksize=100_000) or write the query result to Parquet in the warehouse and read that. Check what you loaded: df.shape, date min and max, null counts compared with a COUNT(*) run in SQL. Use EXPLAIN or the warehouse's query preview to check scanned bytes before running expensive queries, and keep the SQL in a file or a versioned notebook cell so the dataset is reproducible.

A parameterised pull with checks

df = pd.read_sql(text(sql), engine, params={"start": "2026-07-01", "end": "2026-10-01", "region": "West"}, parse_dates=["created_at"]) followed by assert df.created_at.min() >= pd.Timestamp("2026-07-01").

Key takeaway: Parameterise, select explicitly, set dtypes and verify what you loaded.

How it works, step by step

Step 1 of 4
Plan

1. List the columns you need

Write down the features, keys and label columns and avoid SELECT *.

order_id, customer_id, amount, created_at
Key numbers at this step
Fewer columns
faster, cheaper

When to use it & trade-offs

What it is

For a data scientist, a SELECT query is how you pull the dataset you need: choose only the columns you'll use, filter rows in the database with WHERE (so you don't download everything), sort with ORDER BY, and cap exploratory pulls with LIMIT. Filtering must be NULL-safe (= NULL never matches; use IS NULL), and queries run from Python should use bound parameters (WHERE created_at >= :start), not string formatting. The pandas version is pd.read_sql(query, engine, params=...).

Why it matters: Pulling a whole table into pandas wastes minutes and memory, and loading less than you think (a forgotten date filter, NULLs silently excluded by a comparison) produces wrong training data without any error. Pushing filters and column selection into SQL makes analysis faster and cheaper, especially on warehouses that bill by data scanned.

When to reach for it

  • Pulling training and evaluation datasets
  • Exploring tables with LIMIT and ORDER BY
  • Parameterised pulls from notebooks and scripts

When to avoid or be careful

  • SELECT * on wide or large tables
  • = NULL comparisons
  • BETWEEN for timestamp ranges

Where to filter

Filter in SQL (WHERE)
Best for: Large tables and warehouses

Strengths: Less data transferred; uses indexes and partitions.

Watch out: Requires care with NULLs and dates.

Load then filter in pandas
Best for: Small tables

Strengths: Flexible, interactive.

Watch out: Wastes memory and time on big data.

Pre-built views or marts
Best for: Repeated, governed datasets

Strengths: Consistent definitions.

Watch out: Less flexible; depends on owners.

Interview signals & numbers to know

When this topic comes up

  • “Why is my query returning no rows?”
  • “Loading the table takes forever”
  • “How do you get a reproducible sample?”
  • NULL handling
  • SQL from Python

Benchmarks & rules of thumb

180M → 410K -
rows before and after filtering in the example
half-open -
date ranges: >= start AND < end
100,000 -
a typical chunksize

Common mistakes & follow-ups

Common interview mistakes

  • Using WHERE coupon = NULL and getting zero rows.
  • Using BETWEEN with a date and losing most of the last day.
  • Treating LIMIT 1000 without ORDER BY as a random sample.

Likely interviewer follow-ups

  • How do you get a reproducible random sample in SQL?
  • Why use bound parameters when querying from Python?
  • How do you check the data you loaded is complete?
Interview tip: Mention half-open date ranges and IS NULL. Two small details that signal you've been burned by silent filtering errors.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply SELECT, WHERE, ORDER BY & Filtering with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Relational Database Concepts & Schemas
Next topic
Aggregate Functions & GROUP BY / HAVING