Coming from SQL

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

If you think in SQL, you already know most of what pandas does: a DataFrame is a table, a column is a Series, a query is a chain of operations. This page maps each SQL construct to its pandas 3.1 counterpart, shows both side by side, and spends most of its time on the places where the models differ and silently give different answers: missing values, row counts, join keys and ordering. It follows the official "Comparison with SQL" guide, but uses a small in-code dataset instead of a download, and every example was run on Python 3.13 with pandas 3.1.0 (checked in October 2026); the output shown is real.

For the SQL side of each example see the SQL pages of this site: Querying Data (SELECT), Aggregate and Window Functions and Modifying Data. Reading from and writing to real databases is covered in SQL Databases; the tool choice between pandas, Polars, DuckDB and the database itself is in Choosing Tools & Learning Path.

The mental model

A SQL query is declarative: you describe the result and the engine decides how to compute it. A pandas program is imperative: you call one operation after another and each returns a new object. The logical order in which a database evaluates a query is the order in which you will usually write the pandas calls.

The logical evaluation order of a SQL query: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY and LIMIT, each paired with its pandas counterpart
Figure 1. The logical evaluation order of a SQL query and the pandas call that matches each step

Four differences cause most surprises:

  • Rows have an order and an index. A table has no inherent order; a DataFrame does, and every row carries a label that survives filtering and sorting. Use reset_index(drop=True) when you want fresh positions.

  • Most operations return a new object. Assign the result (df = df.sort_values("col")). The inplace= argument is deprecated in pandas 3.1 for drop, rename, reset_index, set_index, dropna, drop_duplicates, sort_values, sort_index, eval and query; do not use it in new code.

  • There is no query optimiser. Each call runs eagerly, in the order you wrote it. Filter before you join, and select only the columns you need.

  • Missing is NaN, not NULL, with different semantics (see below).

The dataset

Everything below uses a small restaurant table, defined in code so that the examples are self-contained. It has the shape of the tips dataset used by the official guide:

import numpy as np
import pandas as pd

tips = pd.DataFrame({
    "total_bill": [16.99, 10.34, 21.01, 23.68, 24.59, 25.29, 8.77, 26.88, 15.04, 14.78, 35.26, 18.43],
    "tip":        [1.01, 1.66, 3.50, 3.31, 3.61, 4.71, 2.00, 3.12, 1.96, 3.23, 5.00, 3.00],
    "sex":        ["F", "M", "M", "M", "F", "M", "M", "M", "M", "M", "F", "M"],
    "smoker":     ["No", "No", "No", "No", "No", "No", "No", "No", "Yes", "Yes", "Yes", "No"],
    "day":        ["Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sat", "Sat", "Sat", "Sat"],
    "time":       ["Dinner"] * 8 + ["Lunch", "Dinner", "Dinner", "Lunch"],
    "size":       [2, 3, 3, 2, 4, 4, 2, 4, 2, 2, 5, 3],
})

Source: pandas documentation, Comparison with SQL (the original loads the 244-row tips file from the pandas test data).

SELECT

Choose columns with a list inside the brackets; calculate new ones with assign, which returns a new frame and leaves the original untouched:

SQL pandas

SELECT total_bill, tip, smoker, time FROM tips

tips[["total_bill", "tip", "smoker", "time"]]

SELECT *, tip / total_bill AS tip_rate FROM tips

tips.assign(tip_rate=tips["tip"] / tips["total_bill"])

print(tips[["total_bill", "tip", "smoker", "time"]].head(3))
print(tips.assign(tip_rate=tips["tip"] / tips["total_bill"]).round({"tip_rate": 3}).head(3))
   total_bill   tip smoker    time
0       16.99  1.01     No  Dinner
1       10.34  1.66     No  Dinner
2       21.01  3.50     No  Dinner
   total_bill   tip sex smoker  day    time  size  tip_rate
0       16.99  1.01   F     No  Sun  Dinner     2     0.059
1       10.34  1.66   M     No  Sun  Dinner     3     0.161
2       21.01  3.50   M     No  Sun  Dinner     3     0.167

In pandas 3 a column expression can replace the repeated frame name: tips.assign(tip_rate=pd.col("tip") / pd.col("total_bill")) (see pd.col, Select & Filter).

WHERE

A comparison gives a boolean Series; indexing a frame with it keeps the True rows. Combine conditions with & for AND, | for OR and ~ for NOT. Every comparison needs its own parentheses, because the bitwise operators bind tighter than > and ==. The keywords and, or and not do not work on Series.

SQL pandas

WHERE total_bill > 25

tips[tips["total_bill"] > 25]

WHERE time = 'Dinner' AND tip > 4

tips[(tips["time"] == "Dinner") & (tips["tip"] > 4)]

WHERE size >= 5 OR total_bill > 25

tips[(tips["size"] >= 5) | (tips["total_bill"] > 25)]

WHERE day IN ('Sat')

tips[tips["day"].isin(["Sat"])]

WHERE total_bill BETWEEN 15 AND 20

tips[tips["total_bill"].between(15, 20)]

WHERE time LIKE '%inn%'

tips[tips["time"].str.contains("inn")]

WHERE NOT smoker = 'No'

tips[~tips["smoker"].eq("No")]

print(tips[tips["total_bill"] > 25])
print(tips[(tips["time"] == "Dinner") & (tips["tip"] > 4)])
print(tips[(tips["size"] >= 5) | (tips["total_bill"] > 25)])
    total_bill   tip sex smoker  day    time  size
5        25.29  4.71   M     No  Sun  Dinner     4
7        26.88  3.12   M     No  Sun  Dinner     4
10       35.26  5.00   F    Yes  Sat  Dinner     5
    total_bill   tip sex smoker  day    time  size
5        25.29  4.71   M     No  Sun  Dinner     4
10       35.26  5.00   F    Yes  Sat  Dinner     5
    total_bill   tip sex smoker  day    time  size
5        25.29  4.71   M     No  Sun  Dinner     4
7        26.88  3.12   M     No  Sun  Dinner     4
10       35.26  5.00   F    Yes  Sat  Dinner     5

Note that the row labels (5, 7, 10) are kept. query offers a SQL-like string syntax that avoids repeating the frame name (tips.query("time == 'Dinner' and tip > 4")); it also accepts a reference to a Python variable with @name.

NULL and NaN

SQL uses three-valued logic: any comparison with NULL is unknown, and WHERE keeps only the rows where the predicate is true. pandas uses NaN (and NaT, and pd.NA in the nullable dtypes), and an ordinary comparison simply gives False. The functions to know are isna and notna:

SQL pandas

WHERE col2 IS NULL

frame[frame["col2"].isna()]

WHERE col1 IS NOT NULL

frame[frame["col1"].notna()]

COALESCE(col2, 'none')

frame["col2"].fillna("none")

frame = pd.DataFrame({"col1": ["A", "B", np.nan, "C", "D"], "col2": ["F", np.nan, "G", "H", "I"]})
print(frame[frame["col2"].isna()])
print(frame[frame["col1"].notna()])
print((frame["col1"] == "A").tolist())
print((frame["col1"] != "A").tolist())
  col1 col2
1    B  NaN
  col1 col2
0    A    F
1    B  NaN
3    C    H
4    D    I
[True, False, False, False, False]
[False, True, True, True, True]

The last line is the trap: frame["col1"] != "A" is True for the row whose col1 is missing, whereas in SQL neither col1 = 'A' nor col1 <> 'A' is true for a NULL, so such a row is never returned. If you port a query that relies on three-valued logic, test notna() explicitly.

Other places where missing values behave differently:

  • Aggregates. SQL’s SUM of no non-null values is NULL; pandas returns 0 unless you pass min_count=1 (pd.Series([np.nan]).sum() is 0.0, with min_count=1 it is NaN).

  • Group keys. A GROUP BY produces a group for NULL; groupby drops missing keys unless you pass dropna=False.

  • Sorting. ORDER BY places NULL first or last depending on the engine; sort_values puts missing values last by default and takes na_position="first".

  • Join keys. Two NULL keys never match in SQL; two NaN keys do match in a pandas merge (shown below).

The details of missing data in pandas, including Kleene logic in the nullable dtypes, are in Missing Data and Nullable Dtypes.

ORDER BY, LIMIT, OFFSET and DISTINCT

SQL pandas

ORDER BY day, total_bill DESC

tips.sort_values(["day", "total_bill"], ascending=[True, False])

LIMIT 10

tips.head(10)

LIMIT 10 OFFSET 5

tips.iloc[5:15] (after the sort)

ORDER BY tip DESC LIMIT 10 OFFSET 5

tips.nlargest(10 + 5, columns="tip").tail(10)

SELECT DISTINCT sex, smoker

tips[["sex", "smoker"]].drop_duplicates()

COUNT(DISTINCT day)

tips["day"].nunique()

print(tips.sort_values(["day", "total_bill"], ascending=[True, False])[["day", "total_bill"]].head(4))
print(tips.nlargest(5 + 3, columns="tip").tail(3)[["tip"]])    # ORDER BY tip DESC LIMIT 3 OFFSET 5
print(tips[["sex", "smoker"]].drop_duplicates())
print(tips["day"].nunique())
    day  total_bill
10  Sat       35.26
11  Sat       18.43
8   Sat       15.04
9   Sat       14.78
     tip
9   3.23
7   3.12
11  3.00
   sex smoker
0    F     No
1    M     No
8    M    Yes
10   F    Yes
2

nlargest and nsmallest are faster than a full sort when you only need the top few. Remember that the default sorting algorithm of sort_values is not guaranteed to be stable on a single column; pass kind="stable" when ties must keep their original order.

GROUP BY and HAVING

groupby splits the rows, an aggregation reduces each group and the group keys become the index of the result. The distinction between size and count is the classic stumbling block: size() counts rows, including those with missing values, like COUNT(*); count() counts the non-missing values of each column, like COUNT(column).

print(tips.groupby("sex").size())                                    # COUNT(*) ... GROUP BY sex
print(tips.groupby("sex").count().iloc[:, :2])                       # COUNT(col) for every column
print(tips.groupby(["smoker", "day"]).agg(n=("tip", "size"), avg_tip=("tip", "mean")).round(2))
sex
F    3
M    9
dtype: int64
     total_bill  tip
sex
F             3    3
M             9    9
            n  avg_tip
smoker day
No     Sat  1     3.00
       Sun  8     2.86
Yes    Sat  3     3.40

The last call uses named aggregation, result_name=("column", "function"), which is the clearest equivalent of SELECT COUNT(*) AS n, AVG(tip) AS avg_tip. The dictionary form agg({"tip": ["size", "mean"]}) also works but produces two-level column labels.

pandas has no HAVING keyword: filter the aggregated frame afterwards, either with a boolean mask or with query:

res = tips.groupby("day").agg(n=("tip", "size"), avg_tip=("tip", "mean"))
print(res[res["n"] > 5])
print(res.query("n > 5"))           # the same, SQL-like
     n  avg_tip
day
Sun  8    2.865
     n  avg_tip
day
Sun  8    2.865

Both forms are the equivalent of GROUP BY day HAVING COUNT(*) > 5. When the filter must drop whole groups but keep the original rows, use groupby(...).filter(func) instead.

Window functions

SQL window functions compute a value per row from a group of rows, without collapsing them. In pandas the group is a groupby object and the per-row operations are rank, cumcount, transform, shift and the cumulative and rolling methods:

SQL pandas

ROW_NUMBER() OVER (PARTITION BY day ORDER BY total_bill DESC)

sort, then groupby("day").cumcount() + 1

RANK() OVER (PARTITION BY day ORDER BY total_bill DESC)

groupby("day")["total_bill"].rank(method="min", ascending=False)

AVG(tip) OVER (PARTITION BY day)

groupby("day")["tip"].transform("mean")

SUM(tip) OVER (ORDER BY id)

tips["tip"].cumsum()

AVG(tip) OVER (ORDER BY id ROWS 2 PRECEDING)

tips["tip"].rolling(3).mean()

LAG(tip, 1) OVER (PARTITION BY day ORDER BY id)

groupby("day")["tip"].shift(1)

Top two bills per day, the usual "top N per group" query:

t = tips.sort_values("total_bill", ascending=False)
t["rn"] = t.groupby("day").cumcount() + 1                             # ROW_NUMBER()
print(t.query("rn < 3")[["day", "total_bill", "rn"]])

t["rnk"] = t.groupby("day")["total_bill"].rank(method="min", ascending=False)   # RANK()
print(t[["day", "total_bill", "rnk"]].head(3))
    day  total_bill  rn
10  Sat       35.26   1
7   Sun       26.88   1
5   Sun       25.29   2
11  Sat       18.43   2
    day  total_bill  rnk
10  Sat       35.26  1.0
7   Sun       26.88  1.0
5   Sun       25.29  2.0

rank returns floats. The method argument decides ties: "min" gives tied rows the same rank and leaves gaps, like SQL’s RANK(); "dense" leaves no gaps, like DENSE_RANK(); "first" breaks ties by position, like ROW_NUMBER(). Because pandas does not guarantee a row order inside a group unless you sorted first, always sort before cumcount, shift or cumsum.

CASE WHEN

Use numpy.where for a two-way condition and numpy.select for several branches, evaluated in order like the WHEN clauses of a CASE:

bill = tips["total_bill"]
print(np.where(bill < 15, "low", "high")[:4])
print(np.select([bill < 15, bill < 25], ["low", "mid"], default="high")[:4])
['high' 'low' 'high' 'high']
['mid' 'low' 'mid' 'mid']

Series.where(cond, other) keeps values where the condition is true, and Series.mask does the opposite; pd.cut and pd.qcut turn a number into labelled bins.

Source: pandas documentation, Comparison with spreadsheets: If-then logic (the same idiom as the SQL CASE).

JOIN

merge is the SQL join. Pass the key with on (same name on both sides) or left_on and right_on (different names), and the join type with how. pandas 3.0 added the anti-joins, so the whole family is now available:

SQL how= Result

INNER JOIN

"inner" (default)

Rows whose key is in both frames; left key order kept.

LEFT OUTER JOIN

"left"

All left rows; missing right values are NaN.

RIGHT OUTER JOIN

"right"

All right rows.

FULL OUTER JOIN

"outer"

The union of keys, sorted lexicographically.

CROSS JOIN

"cross"

The Cartesian product (no on).

WHERE NOT EXISTS (left)

"left_anti"

Left rows with no match on the right (new in 3.0).

WHERE NOT EXISTS (right)

"right_anti"

Right rows with no match on the left (new in 3.0).

WHERE EXISTS (semi join)

no how; use isin

Left rows that have a match, without duplicating them.

customers = pd.DataFrame({"customer_id": [1, 2, 3, 4], "name": ["Ada", "Ben", "Cy", "Dee"]})
orders = pd.DataFrame({"order_id": [10, 11, 12, 13],
                       "customer_id": [1, 1, 3, 9],
                       "amount": [50.0, 20.0, 75.0, 5.0]})

for how in ["inner", "left", "right", "outer", "cross", "left_anti", "right_anti"]:
    kw = {} if how == "cross" else {"on": "customer_id"}
    print(how, customers.merge(orders, how=how, **kw).shape)

print(customers.merge(orders, on="customer_id", how="left"))
inner (3, 4)
left (5, 4)
right (4, 4)
outer (6, 4)
cross (16, 5)
left_anti (2, 4)
right_anti (1, 4)
   customer_id name  order_id  amount
0            1  Ada      10.0    50.0
1            1  Ada      11.0    20.0
2            2  Ben       NaN     NaN
3            3   Cy      12.0    75.0
4            4  Dee       NaN     NaN

Notice that order_id became a float: the missing values in a numeric column force NaN. Customer 1 appears twice, because it has two orders; a one-to-many join multiplies rows exactly as in SQL.

In pandas 3.1.0 an anti-join returns the columns of both frames, with the columns of the second frame filled with NaN. Pass only the key columns of the second frame to get a clean "customers without orders" result, or use isin:

print(customers.merge(orders[["customer_id"]], on="customer_id", how="left_anti"))     # NOT EXISTS
print(customers[~customers["customer_id"].isin(orders["customer_id"])])                # the same with isin
print(customers[customers["customer_id"].isin(orders["customer_id"])])                 # EXISTS (semi join)
   customer_id name
2            2  Ben
4            4  Dee
   customer_id name
1            2  Ben
3            4  Dee
   customer_id name
0            1  Ada
2            3   Cy

Four more options protect you from the silent mistakes of SQL joins:

  • validate="one_to_one" (or "one_to_many", "many_to_one", "many_to_many") raises a MergeError when the key uniqueness is not what you expect, which is how you catch an accidental fan-out.

  • indicator=True adds a _merge column with left_only, right_only or both, the quick way to audit what matched.

  • suffixes=("_a", "_b") names the overlapping non-key columns (the default is _x and _y).

  • left_on and right_on join columns with different names; both key columns are kept in the result.

Missing keys behave differently from SQL. In SQL a NULL never equals another NULL, so such rows do not join. In a pandas merge two NaN keys match each other:

l = pd.DataFrame({"k": [1.0, np.nan], "left_val": ["x", "y"]})
r = pd.DataFrame({"k": [np.nan, 2.0], "right_val": ["p", "q"]})
print(l.merge(r, on="k"))      # a SQL inner join would return no rows

try:
    customers.merge(pd.concat([orders, orders]), on="customer_id", validate="one_to_one")
except Exception as exc:
    print(type(exc).__name__, "-", str(exc).splitlines()[0])
    k left_val right_val
0 NaN        y         p
MergeError - Merge keys are not unique in right dataset; not a one-to-one merge

Drop or fill missing keys before merging when the SQL semantics matter. DataFrame.join is a convenience wrapper that joins on the index by default (left.join(right, how="left")).

UNION, INTERSECT and EXCEPT

concat stacks frames (a UNION ALL); add drop_duplicates for a UNION. The other two set operations are merges:

x = pd.DataFrame({"a": [1, 2]})
y = pd.DataFrame({"a": [2, 3]})
print(pd.concat([x, y], ignore_index=True)["a"].tolist())    # UNION ALL
print(pd.concat([x, y]).drop_duplicates()["a"].tolist())     # UNION
print(x.merge(y, how="inner")["a"].tolist())                 # INTERSECT: merges on all common columns
print(x.merge(y, how="left_anti")["a"].tolist())             # EXCEPT
[1, 2, 2, 3]
[1, 2, 3]
[2]
[1]

concat aligns columns by name and fills the ones missing in a frame with NaN, while a SQL UNION matches columns by position, so reorder or rename columns first when porting.

INSERT, UPDATE and DELETE

pandas is an analysis library, not a transactional store, and its answers to the data modification statements reflect that. Always assign the result, and never grow a frame row by row: DataFrame.append was removed in pandas 2.0.

SQL pandas

INSERT INTO tips VALUES (...)

tips = pd.concat([tips, new_rows], ignore_index=True), with the new rows collected in a list first

UPDATE tips SET tip = tip * 2 WHERE tip < 2

tips.loc[tips["tip"] < 2, "tip"] *= 2

DELETE FROM tips WHERE tip > 4

tips = tips.loc[tips["tip"] <= 4]

t2 = tips.copy()
t2.loc[t2["tip"] < 2, "tip"] *= 2          # UPDATE: one .loc call, rows and column together
print(t2["tip"].head(3).tolist())

t2 = t2.loc[t2["tip"] <= 4]                # DELETE: keep what you want instead of dropping the rest
print(len(tips), len(t2))
[2.02, 3.32, 3.5]
12 10

For DELETE, keep the rows you want rather than dropping the rest, because the condition is then written exactly as in a WHERE clause. The single .loc[rows, column] call matters: chained indexing such as tips[tips["tip"] < 2]["tip"] *= 2 changes a temporary copy and never the original, because Copy-on-Write is the only mode in pandas 3.

Running SQL from pandas

You do not have to choose between the two. to_sql writes a frame to a table and read_sql_query runs a query and returns a DataFrame; use a SQLAlchemy engine (the supported route for most databases) and a parameterised query rather than string formatting:

import sqlalchemy as sa

engine = sa.create_engine("sqlite://")          # in-memory SQLite
customers.to_sql("customers", engine, index=False)
orders.to_sql("orders", engine, index=False)

query = """
    SELECT c.name, SUM(o.amount) AS total
    FROM customers c JOIN orders o ON o.customer_id = c.customer_id
    GROUP BY c.name ORDER BY total DESC
"""
print(pd.read_sql_query(query, engine))
print(pd.read_sql_query(sa.text("SELECT * FROM orders WHERE amount > :m"), engine, params={"m": 30}))
  name  total
0   Cy   75.0
1  Ada   70.0
   order_id  customer_id  amount
0        10            1    50.0
1        12            3    75.0

Source: pandas.read_sql_query and DataFrame.to_sql. Connection strings, chunking and driver choices are in SQL Databases.

Two alternatives are worth knowing when you want to write SQL against data that is already in memory. DuckDB can query a DataFrame by its variable name (duckdb.sql("SELECT day, AVG(tip) FROM tips GROUP BY day").df()) and is often much faster on large frames; Polars offers a SQL context too. Both are compared in Beyond the Core: Polars, Arrow, DuckDB & Deep Learning. The reverse advice also holds: for filtering and joining tables that are far larger than memory, let the database do it and read only the result.

Quick reference

You write in SQL You write in pandas

SELECT a, b

df[["a", "b"]]

WHERE a > 1 AND b = 'x'

df[(df["a"] > 1) & (df["b"] == "x")] or df.query("a > 1 and b == 'x'")

ORDER BY a DESC

df.sort_values("a", ascending=False)

LIMIT n

df.head(n)

SELECT DISTINCT a

df["a"].drop_duplicates()

COUNT(*) GROUP BY a

df.groupby("a").size()

SUM(b) GROUP BY a HAVING SUM(b) > 10

s = df.groupby("a")["b"].sum() then s[s > 10]

JOIN ... ON a.id = b.id

a.merge(b, on="id")

UNION ALL

pd.concat([a, b])

CASE WHEN ... END

np.select(conditions, choices, default=...)

COALESCE(a, 0)

df["a"].fillna(0)

a IS NULL

df["a"].isna()

Where older tutorials are outdated

Many "pandas for SQL users" articles were written for pandas 0.2x and 1.x:

Older advice pandas 3.1

Add rows with df.append(row)

Removed in 2.0; collect rows in a list and call pd.concat once, or build the frame from the list.

Anti-joins need merge(..., indicator=True) and a filter

how="left_anti" and how="right_anti" exist since 3.0.

observed=False is the default for categorical group keys

The default is observed=True since 3.0.

df.loc[df.a > 1]["b"] = 0

Never worked reliably and does nothing in pandas 3; use df.loc[df["a"] > 1, "b"] = 0.

inplace=True for speed

Not faster, and deprecated in pandas 3.1.