All cheat sheets

Pandas ↔ SQL

The same operation in both, side by side. For when you know one and are reaching for the other.

1 min read

Selecting

SQLpandas
select * from tdf
select a, b from tdf[["a", "b"]]
select distinct a from tdf["a"].drop_duplicates()
select * from t limit 10df.head(10)

Filtering

select * from orders where amount > 100 and status = 'paid';
orders[(orders["amount"] > 100) & (orders["status"] == "paid")]

Each condition needs its own brackets — & binds tighter than > in Python.

Grouping

select customer_id, count(*) as n, sum(amount) as total
from orders group by customer_id;
orders.groupby("customer_id").agg(n=("amount", "size"), total=("amount", "sum"))

Joining

SQLpandas
inner joindf.merge(other, on="id")
left joindf.merge(other, on="id", how="left")
full outer joindf.merge(other, on="id", how="outer")

Window functions

sum(amount) over (partition by customer_id order by order_date)
orders.sort_values("order_date").groupby("customer_id")["amount"].cumsum()

The one that catches everyone

GROUP BY in SQL drops the other columns. groupby in pandas moves the key into the index — add .reset_index() to get a flat frame back.