Pandas ↔ SQL Cheat Sheet

Python · Reshaping & Workflow

Theory

Most SQL clauses map directly to a pandas method. SELECT cols is df[['a', 'b']]; WHERE is a boolean mask or df.query(); ORDER BY is sort_values(); LIMIT n is head(n); DISTINCT is drop_duplicates(); CASE WHEN is np.where or np.select; GROUP BY with aggregates is groupby().agg(); HAVING filters the aggregated result; JOIN is merge(how=...); UNION ALL is pd.concat() and UNION adds drop_duplicates(); COALESCE is fillna() or combine_first().

Window functions follow one pattern - groupby(partition) then a per-row method: SUM() OVER (PARTITION BY ...) is transform('sum'); ROW_NUMBER, RANK and DENSE_RANK are cumcount() + 1 and rank(method='first' / 'min' / 'dense'); LAG/LEAD are shift(1)/shift(-1); running totals are cumsum(); moving averages are rolling(n).mean(). The main difference to remember is order: SQL runs FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, while in pandas you write the steps in the order you want them to happen.

Why we use it

Many learners already think in SQL. A direct mapping lets you translate any query you know into pandas, and back, which speeds up learning and helps in interviews that ask for both.

When to use it

Use this sheet when translating a query into pandas or checking which method matches a SQL idea. For data already in a database, push heavy filtering and joining into SQL and use pandas for the final analysis and charts.

How it works

  1. FROM / JOIN: start with df or df.merge(...)
  2. WHERE: df[mask] or .query(...)
  3. GROUP BY + aggregates: .groupby(...).agg(...)
  4. HAVING: filter the aggregated result
  5. SELECT / window functions: assign, transform, rank, shift
  6. ORDER BY / LIMIT: .sort_values(...).head(n)
  7. Same answer as the SQL query

Syntax

WHERE      -> df[mask] / df.query()
GROUP BY   -> df.groupby(k).agg(...)
HAVING     -> filter the agg result
JOIN       -> df.merge(other, on=k, how=...)
UNION ALL  -> pd.concat([a, b])
OVER()     -> groupby(k)[c].transform / rank / shift / cumsum

Example

# SELECT city, SUM(amount) AS total FROM orders
# WHERE amount > 500 GROUP BY city HAVING SUM(amount) > 2000
# ORDER BY total DESC LIMIT 2
t = df[df['amount'] > 500].groupby('city', as_index=False).agg(total=('amount', 'sum'))
print(t[t['total'] > 2000].sort_values('total', ascending=False).head(2))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic