46 Pandas and SQL Interview Questions and Answers (with Queries)
46 Pandas and SQL Interview Questions and Answers (with Queries)
Preparing for a data analyst or data scientist interview? These 46 Pandas and SQL questions include guess-the-output puzzles, query writing and real scenarios, with code you can run. Use the contents to jump to a topic, then build the skills with our Python for Data Science Training.
Pandas Fundamentals
1. What is the difference between a Series and a DataFrame?
A Series is a one-dimensional labelled array, and a DataFrame is a two-dimensional table of Series sharing an index. Each DataFrame column is a Series, which is why column operations are vectorised.
2. What is the difference between loc and iloc?
loc selects by label (index and column names) and includes the end of a slice, while iloc selects by integer position and excludes the end.
import pandas as pd
s = pd.Series([10, 20, 30], index=[2, 1, 0])
print(s.loc[0], s.iloc[0])
# Output: 30 103. Guess the output: shape, mean and column access
mean() returns a float and shape is rows, then columns.
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.shape, df["a"].mean())
# Output: (3, 2) 2.04. Guess the output: how pandas treats NaN in aggregations
sum and mean skip NaN by default (skipna=True), and count ignores missing values. The sum becomes a float because NaN is a float.
s = pd.Series([1, None, 3])
print(s.sum(), s.mean(), s.count(), len(s))
# Output: 4.0 2.0 2 35. How do you check and handle missing values in a DataFrame?
Inspect with df.isna().sum(), then choose a strategy: drop rows or columns (dropna), fill with a constant, statistic or forward fill (fillna, ffill), or interpolate for time series. Decide using the business meaning of the missing value and record what you did.
print(df.isna().sum())
df["age"] = df["age"].fillna(df["age"].median())
df = df.dropna(subset=["customer_id"])6. What is the difference between apply, map, applymap and vectorised operations?
Vectorised operations (df[“a”] * 2) run in optimised C code and are fastest. map transforms values of a Series, apply runs a function along an axis or on a Series row by row, and applymap (now DataFrame.map in newer versions) applies a function element-wise. Prefer vectorised code, and use apply only when no vectorised form exists.
7. How do you read data efficiently and reduce memory use?
Select only the needed columns with usecols, set dtypes (category for low-cardinality strings, smaller integer and float types), parse dates, and read in chunks for very large files. Check df.info(memory_usage=”deep”) before and after.
df = pd.read_csv("sales.csv",
usecols=["id", "region", "amount", "date"],
dtype={"region": "category"},
parse_dates=["date"])8. What is the SettingWithCopyWarning, and how do you avoid it?
It warns that you may be modifying a copy of a slice instead of the original DataFrame. Avoid chained indexing; use loc for assignment, or create an explicit copy with .copy(). Newer pandas versions with copy-on-write behave more predictably, so check your version.
# risky
df[df["qty"] > 0]["flag"] = 1
# safe
df.loc[df["qty"] > 0, "flag"] = 19. How do you detect and remove duplicates in pandas?
Use df.duplicated(subset=[…]) to find them and drop_duplicates(subset=[…], keep=”first”) to remove. Decide the business key first, because “duplicate” depends on which columns define a record.
Data Wrangling: groupby, merge and reshape
10. Guess the output: groupby and sum
groupby splits the rows by key, then sums within each group.
df = pd.DataFrame({"dept": ["A", "A", "B"], "sal": [10, 20, 30]})
print(df.groupby("dept")["sal"].sum())
# Output:
# dept
# A 30
# B 30
# Name: sal, dtype: int6411. What is the difference between merge types: inner, left, right and outer?
Inner keeps keys present in both tables, left keeps all rows from the left and matches from the right, right does the reverse, and outer keeps all keys from both with NaN where there is no match. Check the row counts after a merge to catch accidental many-to-many explosions.
left = pd.DataFrame({"id": [1, 2]})
right = pd.DataFrame({"id": [2, 3]})
print(len(left.merge(right, on="id"))) # 1 (inner)
print(len(left.merge(right, on="id", how="outer"))) # 312. How do you pivot data, and what is the difference between pivot and pivot_table?
pivot reshapes data and fails if there are duplicate index and column combinations. pivot_table handles duplicates by aggregating with a function such as sum or mean.
pd.pivot_table(df, index="region", columns="month",
values="sales", aggfunc="sum", fill_value=0)13. What is melt, and when do you use it?
melt converts wide data into long format (one row per observation), which suits plotting libraries and groupby. It is the reverse of pivot.
wide = pd.DataFrame({"id": [1], "jan": [5], "feb": [7]})
print(wide.melt(id_vars="id", var_name="month", value_name="sales"))14. How do you compute a rolling average and a running total in pandas?
Use rolling(window).mean() for a moving average and cumsum() for a running total, usually after sorting by date and grouping if needed.
df = df.sort_values("date")
df["ma7"] = df["sales"].rolling(7).mean()
df["running"] = df["sales"].cumsum()15. How do you find the top 3 products by sales within each category?
Sort, then take the head of each group, or rank within groups.
top3 = (df.sort_values("sales", ascending=False)
.groupby("category")
.head(3))16. How do you handle dates and time zones in pandas?
Convert with pd.to_datetime, use the .dt accessor for parts like month and weekday, set a DatetimeIndex for resampling, and localise then convert time zones with tz_localize and tz_convert. Store timestamps in UTC and convert for display.
df["date"] = pd.to_datetime(df["date"])
monthly = df.set_index("date")["sales"].resample("M").sum()17. Guess the output: boolean filtering with and, or
Combine conditions with & and |, and wrap each in parentheses because of operator precedence. Using the Python and keyword raises a ValueError.
df = pd.DataFrame({"x": [1, 5, 9]})
print(df[(df["x"] > 2) & (df["x"] < 9)])
# Output:
# x
# 1 518. When would you use categorical dtype, and what are the benefits?
For columns with a small number of repeated values (country, status). It reduces memory, speeds up groupby and comparisons, and allows an ordered category such as low, medium, high.
19. How do you combine many CSV files into one DataFrame?
Read each file in a loop or comprehension and concatenate once with pd.concat, rather than appending inside the loop, which is slow.
from pathlib import Path
frames = [pd.read_csv(p) for p in Path("data").glob("*.csv")]
df = pd.concat(frames, ignore_index=True)SQL Fundamentals
20. What is the difference between INNER, LEFT, RIGHT and FULL joins?
INNER returns matching rows only, LEFT returns all left rows and matches (NULL when none), RIGHT does the reverse, and FULL returns all rows from both.
customers ─ LEFT JOIN ─ orders
customers with no orders appear with NULL order columns21. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, and HAVING filters groups after aggregation. You cannot use aggregate functions in WHERE.
SELECT dept, AVG(salary) AS avg_sal
FROM employees
WHERE active = 1
GROUP BY dept
HAVING AVG(salary) > 50000;22. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?
COUNT(*) counts all rows, COUNT(column) counts rows where the column is not NULL, and COUNT(DISTINCT column) counts unique non-NULL values.
-- column values: 1, 1, NULL
COUNT(*) -- 3
COUNT(col) -- 2
COUNT(DISTINCT col) -- 123. How does NULL behave in comparisons?
NULL means unknown, so NULL = NULL is not true. Use IS NULL and IS NOT NULL. Aggregates like SUM and AVG ignore NULLs, and NOT IN with a subquery that returns a NULL returns no rows, which is a common bug; prefer NOT EXISTS.
Build your skills in Data and Python
Join the next live batch with an instructor. Small batches, real projects and a free demo class before you decide.
24. What is the difference between UNION and UNION ALL?
UNION combines results and removes duplicates, which needs a sort or hash, while UNION ALL keeps all rows and is faster. Use UNION ALL unless you truly need de-duplication.
25. Find customers who have never placed an order.
Use a LEFT JOIN with a NULL check, or NOT EXISTS.
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;26. Find duplicate email addresses in a users table.
Group by the column and filter with HAVING.
SELECT email, COUNT(*) AS cnt
FROM users
GROUP BY email
HAVING COUNT(*) > 1;27. What are primary keys, foreign keys and indexes?
A primary key uniquely identifies a row, a foreign key enforces a relationship to another table, and an index is a data structure that speeds up lookups at the cost of slower writes and extra storage. Index columns used in joins, filters and sorts.
28. What are ACID properties?
Atomicity (all or nothing), Consistency (valid state to valid state), Isolation (concurrent transactions do not interfere) and Durability (committed data survives failures). They define reliable transactions in relational databases.
Advanced SQL: Window Functions, CTEs and Performance
29. Find the second highest salary.
Use DENSE_RANK so ties are handled correctly, or a subquery.
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk
FROM employees
) t
WHERE rk = 2;30. Explain ROW_NUMBER, RANK and DENSE_RANK with an example.
For salaries 90, 80, 80, 70 ordered descending: ROW_NUMBER gives 1,2,3,4; RANK gives 1,2,2,4 (gap after ties); DENSE_RANK gives 1,2,2,3 (no gap).
SELECT salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
RANK() OVER (ORDER BY salary DESC) AS rk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dr
FROM employees;31. Return the top 2 earners in each department.
Rank within a partition, then filter.
SELECT * FROM (
SELECT dept, name, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
FROM employees
) t
WHERE rn <= 2;32. Calculate a running total and a month-over-month change.
Use SUM as a window function for the running total and LAG for the previous month.
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running_total,
revenue - LAG(revenue) OVER (ORDER BY month) AS mom_change
FROM monthly_sales;33. What is a CTE, and when would you use it over a subquery?
A common table expression names a query with WITH so it can be read top to bottom and reused. It improves readability for multi-step logic and supports recursion, such as walking an employee hierarchy.
WITH dept_avg AS (
SELECT dept, AVG(salary) AS avg_sal FROM employees GROUP BY dept
)
SELECT e.name, e.salary, d.avg_sal
FROM employees e JOIN dept_avg d ON d.dept = e.dept
WHERE e.salary > d.avg_sal;34. List each employee with their manager name.
Use a self join on the manager id; a LEFT JOIN keeps the top manager who has no manager.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;35. Delete duplicate rows but keep one of each.
Number the rows within each duplicate group and delete the extras (syntax varies by database).
DELETE FROM users
WHERE id IN (
SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) rn
FROM users) t
WHERE rn > 1);36. A query on a table with 100 million rows is slow. How do you investigate?
Read the execution plan (EXPLAIN) to find full scans, check that filters and join columns are indexed and sargable (avoid wrapping columns in functions in WHERE), select only needed columns, reduce rows early, check statistics, and consider partitioning or pre-aggregation for reporting.
37. What is the difference between a clustered and a non-clustered index?
A clustered index defines the physical order of rows (one per table), so range scans on the key are fast. A non-clustered index is a separate structure with pointers to rows, and a table can have many.
38. Pivot rows into columns using conditional aggregation.
Use CASE inside an aggregate, which works in every database.
SELECT product,
SUM(CASE WHEN month = 'Jan' THEN sales END) AS jan,
SUM(CASE WHEN month = 'Feb' THEN sales END) AS feb
FROM sales
GROUP BY product;Scenario Questions
39. Marketing sends you a messy customer file and asks for a count of unique customers by city. How do you proceed?
Load and profile it, standardise case and whitespace in city and email, decide the unique key (email or phone), drop duplicates, then group and count. Document any assumptions such as spelling variants of a city, and share the cleaned result.
df["city"] = df["city"].str.strip().str.title()
df = df.drop_duplicates(subset="email")
print(df.groupby("city")["email"].nunique().sort_values(ascending=False))40. A dashboard number is different from what the SQL query returns. How do you debug it?
Check the filters and date ranges, time zones, joins that multiply rows (many-to-many), NULL handling, deduplication rules and whether the dashboard uses a cached extract. Reconcile with a simple count query at each step.
41. How would you calculate customer retention by month with SQL or pandas?
Assign each customer a cohort month from their first order, compute the month index of each later order, and count distinct customers per cohort and month index, then divide by the cohort size.
first = df.groupby("customer_id")["order_date"].transform("min")
df["cohort"] = first.dt.to_period("M")
df["period"] = (df["order_date"].dt.to_period("M") - df["cohort"]).apply(lambda x: x.n)
ret = df.groupby(["cohort", "period"])["customer_id"].nunique().unstack()42. When would you use SQL for a task, and when would you move to pandas?
Use SQL to filter, join and aggregate close to where the data lives, especially for large tables. Use pandas for exploratory analysis, complex reshaping, statistics, plotting and machine learning on a manageable data size. A common pattern is aggregate in SQL, then analyse in pandas.
43. How do you avoid a join producing more rows than expected?
Check key uniqueness on both sides before joining (df.duplicated on the key, or COUNT versus COUNT DISTINCT in SQL), aggregate one side to the join grain, and compare row counts before and after. In pandas, merge(validate=”one_to_one” or “many_to_one”) raises an error if the assumption is wrong.
orders.merge(customers, on="customer_id", validate="many_to_one")44. Explain normalisation and when denormalisation makes sense.
Normalisation splits data into related tables to reduce redundancy and update anomalies (1NF, 2NF, 3NF). Denormalisation duplicates data deliberately to speed up reads, common in analytics warehouses and reporting tables where joins are costly.
45. How would you load a 10 GB CSV into a database and analyse it?
Do not open it in memory at once: stream or chunk it, create the target table with proper types and indexes, bulk-load with COPY or LOAD DATA, validate counts and null rates, and run the analysis in SQL. For larger-than-memory analysis in Python consider Polars or DuckDB.
46. Describe how you would present a data finding to a non-technical manager.
Lead with the answer and the decision it supports, show one clear chart, explain assumptions and limits in plain words, and offer a next step. Keep the detail in an appendix. Our Power BI and Tableau questions cover the dashboard side.
Build your data skills
Continue with our Python interview questions and Power BI and Tableau questions, or start the Python for Data Science Training.
