SQL to pandas Cheat Sheet

Published:

By

A cheat sheet I created to help translate SQL to pandas syntax and examples of the type of practice I worked on.

Python

SQL to pandas cheat sheet

Each entry is the SQL, a few notes, then working pandas code against the toy tables in the setup cell. Run the setup cell first. The UPDATE entry near the end changes emp, so rerun setup to reset it.

Rules that keep coming up

  1. Read SQL in the order it runs, not the order it's written: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. Pandas chains follow the run order.
  2. Chain order for an aggregate query:
Step SQL pandas
1. Prep rows FROM / WHERE / computed columns df[mask], .assign(...)
2. Group GROUP BY .groupby('key')
3. Pick what to aggregate the column inside AVG(...) .col or ['col']
4. Aggregate COUNT / SUM / AVG .size() / .sum() / .mean()
5. Filter groups HAVING filter the result
6. Sort ORDER BY .sort_values()
  1. A row filter needs one True/False per row, with the same index as the thing it filters. If the mask's index doesn't match, pandas errors or misaligns.
  2. Wrap every comparison in parentheses when combining with & or |. They bind tighter than == and >. Python's and / or don't work on a Series at all.
  3. Use .loc[rows, cols] for anything that writes. Reading works several ways, writing only one way reliably.
  4. A NaN in a number column turns the whole column into floats (12 shows as 12.0). SQL INT columns can hold NULL; default pandas int columns can't.
import pandas as pd

emp = pd.DataFrame({
    'emp_id':     [1, 2, 3, 4, 5, 6],
    'name':       ['ana', 'ben', 'cal', 'dee', 'eli', 'fay'],
    'department': ['Sales', 'Sales', 'IT', 'IT', 'HR', 'Sales'],
    'facility':   ['Denton', 'Dallas', 'Denton', 'Denton', 'Dallas', 'Dallas'],
    'age':        [34, 41, 29, 52, 38, 45],
    'salary':     [50000, 62000, 71000, None, 48000, 55000],
    'tax':        [7500, 9300, 10650, 9000, 7200, 8250],
    'sales':      [120, 95, 0, 10, 0, 140],
})

payroll = pd.DataFrame({
    'emp_id':       [1, 2, 3, 4, 5],
    'facility':     ['Denton', 'Dallas', 'Denton', 'Dallas', 'Dallas'],
    'payroll_amt':  [1900, 2400, 2700, 3100, 1800],
    'payroll_date': ['2026-10-15'] * 5,
})

games = pd.DataFrame({
    'player':   ['ana', 'ben', 'cal', 'dee', 'ana', 'ben', 'cal', 'dee'],
    'faction':  ['Filth', 'Cloaks', 'Filth', 'Vanguards', 'Cloaks', 'Filth', 'Vanguards', 'Cloaks'],
    'opponent': ['Cloaks', 'Filth', 'Vanguards', 'Filth', 'Cloaks', 'Vanguards', 'Filth', 'Filth'],
    'result':   ['W', 'L', 'W', 'L', 'W', 'W', 'L', None],
    'turns':    [12, 9, 15, 11, 13, 14, None, 10],
})

Selecting and filtering

SELECT * FROM emp

emp
emp_id name department facility age salary tax sales
0 1 ana Sales Denton 34 50000.0 7500 120
1 2 ben Sales Dallas 41 62000.0 9300 95
2 3 cal IT Denton 29 71000.0 10650 0
3 4 dee IT Denton 52 NaN 9000 10
4 5 eli HR Dallas 38 48000.0 7200 0
5 6 fay Sales Dallas 45 55000.0 8250 140

SELECT col1, col2 FROM emp

  • Double brackets: the inner brackets are a list of columns, which returns a DataFrame.
  • A single string, emp['name'], returns a Series instead.
emp[['name', 'department']]
name department
0 ana Sales
1 ben Sales
2 cal IT
3 dee IT
4 eli HR
5 fay Sales

SELECT col1, col2 FROM emp WHERE condition

  • .loc[rows, cols] does WHERE and the SELECT list in one step. This is the default to reach for.
  • emp[mask][cols] also works for reading, but the same pattern breaks when assigning, so don't build the habit.
emp.loc[emp.department == 'Sales', ['name', 'age']]
name age
0 ana 34
1 ben 41
5 fay 45

SELECT *, calculated_field FROM emp WHERE condition

  • .assign() returns a new table and leaves emp alone, like a SELECT. Prefer this.
  • emp['col'] = ... is closer to ALTER TABLE plus UPDATE: it changes emp for every cell after it.
  • Filtering first (emp[mask].assign(...)) reads in SQL run order, WHERE before SELECT, and does less work on big tables.
emp.assign(commission = emp.sales * .15)[emp.name == 'ana']

# permanent version, changes emp:
# emp['take_home'] = emp.salary - emp.tax
emp_id name department facility age salary tax sales commission
0 1 ana Sales Denton 34 50000.0 7500 120 18.0

WHERE a = 1 AND b = 2

  • & for AND, with parentheses around each comparison (rule 4).
emp[(emp.department == 'Sales') & (emp.age > 35)]
emp_id name department facility age salary tax sales
1 2 ben Sales Dallas 41 62000.0 9300 95
5 6 fay Sales Dallas 45 55000.0 8250 140

WHERE a = 1 OR b = 2

  • | for OR, same parentheses rule.
  • ~ is NOT: emp[~(emp.department == 'IT')].
emp[(emp.department == 'IT') | (emp.facility == 'Dallas')]
emp_id name department facility age salary tax sales
1 2 ben Sales Dallas 41 62000.0 9300 95
2 3 cal IT Denton 29 71000.0 10650 0
3 4 dee IT Denton 52 NaN 9000 10
4 5 eli HR Dallas 38 48000.0 7200 0
5 6 fay Sales Dallas 45 55000.0 8250 140

WHERE col IN ('x', 'y')

  • NOT IN is ~ in front: emp[~emp.emp_id.isin([2, 5, 6])].
emp[emp.emp_id.isin([2, 5, 6])]
emp_id name department facility age salary tax sales
1 2 ben Sales Dallas 41 62000.0 9300 95
4 5 eli HR Dallas 38 48000.0 7200 0
5 6 fay Sales Dallas 45 55000.0 8250 140

WHERE col IS NULL

  • .isnull() and .isna() are the same method.
  • Use it on one column. On the whole DataFrame it returns a True/False grid, one per cell, which can't filter rows (rule 3).
emp[emp.salary.isnull()]
emp_id name department facility age salary tax sales
3 4 dee IT Denton 52 NaN 9000 10

WHERE col IS NOT NULL

  • .notnull() / .notna().
  • To drop rows with a null in any column: emp.dropna().
emp[emp.salary.notnull()]
emp_id name department facility age salary tax sales
0 1 ana Sales Denton 34 50000.0 7500 120
1 2 ben Sales Dallas 41 62000.0 9300 95
2 3 cal IT Denton 29 71000.0 10650 0
4 5 eli HR Dallas 38 48000.0 7200 0
5 6 fay Sales Dallas 45 55000.0 8250 140

WHERE col_a = col_b

  • Compare two columns directly. Use != for <>.
  • Uses games because ana's Cloaks vs Cloaks game is the only match in the sample data.
mirrors = games[games.faction == games.opponent]
mirrors
player faction opponent result turns
4 ana Cloaks Cloaks W 13.0

Shaping the output

SELECT DISTINCT col FROM games

  • .unique() returns a plain NumPy array, which drops you out of pandas. drop_duplicates() stays a Series or DataFrame.
  • It keeps the original index labels (0, 1, 3), where SQL would just return three rows.
  • Distinct over several columns: games[['faction', 'opponent']].drop_duplicates().
games.faction.drop_duplicates()
0        Filth
1       Cloaks
3    Vanguards
Name: faction, dtype: object

col AS new_name

  • rename takes a dictionary, {old: new}. Curly braces with a comma and no colon make a set, which is a different thing.
  • On a Series (like an aggregate result), pass a plain string: .rename('new_name').
games.rename(columns={'turns': 'rounds'})
player faction opponent result rounds
0 ana Filth Cloaks W 12.0
1 ben Cloaks Filth L 9.0
2 cal Filth Vanguards W 15.0
3 dee Vanguards Filth L 11.0
4 ana Cloaks Cloaks W 13.0
5 ben Filth Vanguards W 14.0
6 cal Vanguards Filth L NaN
7 dee Cloaks Filth None 10.0

ORDER BY col DESC

  • Ascending is the default, same as SQL.
  • NaN always sorts last, in either direction. SQL engines disagree on where NULLs go.
games.sort_values('turns', ascending=False)
player faction opponent result turns
2 cal Filth Vanguards W 15.0
5 ben Filth Vanguards W 14.0
4 ana Cloaks Cloaks W 13.0
0 ana Filth Cloaks W 12.0
3 dee Vanguards Filth L 11.0
7 dee Cloaks Filth None 10.0
1 ben Cloaks Filth L 9.0
6 cal Vanguards Filth L NaN

LIMIT 10

games.head(10)
player faction opponent result turns
0 ana Filth Cloaks W 12.0
1 ben Cloaks Filth L 9.0
2 cal Filth Vanguards W 15.0
3 dee Vanguards Filth L 11.0
4 ana Cloaks Cloaks W 13.0
5 ben Filth Vanguards W 14.0
6 cal Vanguards Filth L NaN
7 dee Cloaks Filth None 10.0

LIMIT 10 OFFSET 5

  • Slices are start:stop. OFFSET is the start, and stop is start + LIMIT.
  • Stop isn't included, so 5:15 is rows 5 through 14, exactly 10.
  • Asking for more rows than exist just returns what's there.
  • .iloc is by position. .loc is by index label, which is a different thing once rows are filtered or sorted.
games.iloc[5:15]

# also works, two steps:
# games.iloc[5:].head(10)
player faction opponent result turns
5 ben Filth Vanguards W 14.0
6 cal Vanguards Filth L NaN
7 dee Cloaks Filth None 10.0

Counting and aggregates

SELECT COUNT(*) FROM emp

  • len(df) is the row count. emp.shape[0] gives the same number.
  • emp.size (no parentheses) is rows times columns, every cell. .size() with parentheses only means COUNT(*) after a groupby.
len(emp)
6

SELECT COUNT(*) FROM emp WHERE condition

  • Alternative: .sum() on a True/False column counts the Trues, the same as SUM(CASE WHEN ... THEN 1 ELSE 0 END).
len(emp[emp.department == 'Sales'])

# (emp.department == 'Sales').sum()
3

SELECT COUNT(DISTINCT department) FROM emp

  • nunique() skips nulls like COUNT(DISTINCT).
  • len(emp.drop_duplicates('department')) gives the same answer here, but it keeps a null as one of the values, so it can count one extra.
emp.department.nunique()
3

SELECT department, COUNT(*) FROM emp GROUP BY department

  • Pair with the next entry.
  • .size() counts rows per group, nulls included.
  • The grouping column moves into the index (HR, IT, Sales). .reset_index(name='count') turns it back into a regular table, like SQL's output.
emp.groupby('department').size()
department
HR       1
IT       2
Sales    3
dtype: int64

SELECT department, COUNT(salary) FROM emp GROUP BY department

  • Pair with the entry above.
  • .count() skips nulls like COUNT(col), so IT drops to 1 because dee's salary is NaN.
emp.groupby('department').salary.count()
department
HR       1
IT       1
Sales    3
Name: salary, dtype: int64

SELECT department, AVG(salary) FROM emp GROUP BY department

  • .mean(), not .avg().
  • Skips NaN like AVG skips NULL: IT is 71000 / 1, not / 2.
emp.groupby('department').salary.mean()
department
HR       48000.000000
IT       71000.000000
Sales    55666.666667
Name: salary, dtype: float64

SELECT department, SUM(sales) AS total_sales FROM emp GROUP BY department ORDER BY total_sales

  • .rename('total_sales') names the result Series, the AS.
  • Without picking a column after the groupby, .sum() sums every numeric column.
emp.groupby('department').sales.sum().sort_values().rename('total_sales')
department
HR         0
IT        10
Sales    355
Name: total_sales, dtype: int64

SELECT faction, AVG(CASE WHEN result = 'W' THEN 1 ELSE 0 END) FROM games GROUP BY faction

  • Win rate. The CASE WHEN has to exist as a column before grouping, so assign it first (chain step 1).
  • The mean of a True/False column is a rate: Trues divided by rows.
  • None == 'W' is False, so the game with no result counts as a loss, matching ELSE 0.
  • To leave it out instead (WHERE result IS NOT NULL), filter first: games[games.result.notnull()].assign(...). Cloaks goes from 0.333 to 0.5.
games.assign(wins = games.result == 'W').groupby('faction').wins.mean()
faction
Cloaks       0.333333
Filth        1.000000
Vanguards    0.000000
Name: wins, dtype: float64

SELECT department, COUNT(*) FROM emp GROUP BY department HAVING COUNT(*) > 1

  • HAVING filters the grouped result, so aggregate, save it, then filter it.
  • Filtering emp with this mask errors: the mask is indexed by department, emp by row number (rule 3).
  • Used > 1 because no department in the sample has more than 5.
  • One-chain version: emp.groupby('department').size().loc[lambda s: s > 1].
counts = emp.groupby('department').size()
counts[counts > 1]
department
IT       2
Sales    3
dtype: int64

Joins and updates

.join() .merge()
Matches on right side's index columns on both sides
on= applies to left side only both sides
Default join type left inner

Write how= every time until the defaults are automatic.

SELECT emp.*, pay.payroll_amt, pay.payroll_date FROM emp JOIN payroll pay ON emp.emp_id = pay.emp_id

  • .join(): on='emp_id' only covers the left side. Without set_index on the right, it matches emp_id against payroll's row numbers and silently pairs the wrong rows.
  • .merge(): on= works on both sides, like a SQL ON. Use left_on= / right_on= when the key names differ.
  • Trimming the right side to the columns you want is the SELECT list. Keep the key column in for merge, or pandas can't match on it.
  • Untrimmed, overlapping column names get _x / _y suffixes.
emp.join(payroll.set_index('emp_id')[['payroll_amt', 'payroll_date']], on='emp_id', how='inner')
emp_id name department facility age salary tax sales payroll_amt payroll_date
0 1 ana Sales Denton 34 50000.0 7500 120 1900 2026-10-15
1 2 ben Sales Dallas 41 62000.0 9300 95 2400 2026-10-15
2 3 cal IT Denton 29 71000.0 10650 0 2700 2026-10-15
3 4 dee IT Denton 52 NaN 9000 10 3100 2026-10-15
4 5 eli HR Dallas 38 48000.0 7200 0 1800 2026-10-15
pd.merge(emp, payroll[['emp_id', 'payroll_amt', 'payroll_date']], on='emp_id')
emp_id name department facility age salary tax sales payroll_amt payroll_date
0 1 ana Sales Denton 34 50000.0 7500 120 1900 2026-10-15
1 2 ben Sales Dallas 41 62000.0 9300 95 2400 2026-10-15
2 3 cal IT Denton 29 71000.0 10650 0 2700 2026-10-15
3 4 dee IT Denton 52 NaN 9000 10 3100 2026-10-15
4 5 eli HR Dallas 38 48000.0 7200 0 1800 2026-10-15

... LEFT JOIN payroll pay ON emp.emp_id = pay.emp_id

  • .join() is a left join by default. With merge, add how='left'.
  • payroll_amt turns into floats because fay's missing row brings a NaN (rule 6).
emp.join(payroll.set_index('emp_id')[['payroll_amt', 'payroll_date']], on='emp_id')
emp_id name department facility age salary tax sales payroll_amt payroll_date
0 1 ana Sales Denton 34 50000.0 7500 120 1900.0 2026-10-15
1 2 ben Sales Dallas 41 62000.0 9300 95 2400.0 2026-10-15
2 3 cal IT Denton 29 71000.0 10650 0 2700.0 2026-10-15
3 4 dee IT Denton 52 NaN 9000 10 3100.0 2026-10-15
4 5 eli HR Dallas 38 48000.0 7200 0 1800.0 2026-10-15
5 6 fay Sales Dallas 45 55000.0 8250 140 NaN NaN

... JOIN payroll pay ON emp.emp_id = pay.emp_id AND emp.facility = pay.facility

  • A list in set_index makes a composite key (MultiIndex).
  • dee drops out: she's in Denton in emp but Dallas in payroll, proof both keys are checked.
  • Merge version: pd.merge(emp, payroll, on=['emp_id', 'facility']).
emp.join(payroll.set_index(['emp_id', 'facility']), on=['emp_id', 'facility'], how='inner')
emp_id name department facility age salary tax sales payroll_amt payroll_date
0 1 ana Sales Denton 34 50000.0 7500 120 1900 2026-10-15
1 2 ben Sales Dallas 41 62000.0 9300 95 2400 2026-10-15
2 3 cal IT Denton 29 71000.0 10650 0 2700 2026-10-15
4 5 eli HR Dallas 38 48000.0 7200 0 1800 2026-10-15

UPDATE emp SET col = x WHERE condition

  • The same .loc[rows, col] selector as a read, on the left side of a single =.
  • Never chain it (emp[mask]['facility'] = x). That either warns or silently does nothing.
  • Two = in one line is two assignments, not a comparison.
  • This changes emp permanently. Rerun setup to reset.
emp.loc[emp.facility == 'Denton', 'facility'] = 'Ft.Worth'
emp
emp_id name department facility age salary tax sales
0 1 ana Sales Ft.Worth 34 50000.0 7500 120
1 2 ben Sales Dallas 41 62000.0 9300 95
2 3 cal IT Ft.Worth 29 71000.0 10650 0
3 4 dee IT Ft.Worth 52 NaN 9000 10
4 5 eli HR Dallas 38 48000.0 7200 0
5 6 fay Sales Dallas 45 55000.0 8250 140

Per-row functions

LENGTH(col)

  • .str.len() gives one length per row. Shows 8 for Ft.Worth because of the UPDATE above.
  • Python's len(emp.facility) measures the whole column, so it returns the row count (that's COUNT(*)).
  • .map(lambda x: len(x)) also works per row, but errors on a null. .str.len() returns NaN, like LENGTH(NULL).
  • Typical uses: ZIPs that lost a leading zero, fixed-length IDs, blank-but-not-null text.
emp.facility.str.len()
0    8
1    6
2    8
3    8
4    6
5    6
Name: facility, dtype: int64