Day 55: Data Science Interview Questions
✅ Today you will learn
- Know the interview rounds
- Revise SQL, Python, statistics and ML answers
- Solve live coding problems step by step
- Handle case and product questions
- Follow a 7-day revision plan
🏢 In the real world
Most data interviews in India follow the same pattern: an online test (SQL + Python + aptitude), a technical round, a case/project discussion and an HR round. The questions repeat across companies. This page collects the ones you are most likely to face – with answers you can say out loud.
The interview rounds
- 1Online assessment: SQL, Python, aptitude (60–90 min)
- 2Technical: SQL live + pandas + statistics
- 3Project / case discussion
- 4Hiring manager: problem solving, communication
- 5HR: expectations, notice period
SQL questions
🗄️ SQL – click a question to see the answer
Q1. Second-highest salary (handle ties).
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); or DENSE_RANK() = 2 in a sub-query.
Q2. WHERE vs HAVING?
WHERE filters rows before grouping; HAVING filters groups after aggregation.
Q3. INNER vs LEFT JOIN – when do you use each?
INNER keeps only matches (clean analysis); LEFT keeps every row of the main table and adds details where available (e.g. all customers, even without orders).
Q4. How do you find duplicate emails in a users table?
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
Q5. Running total of daily sales?
SUM(sales) OVER (ORDER BY day) – or with PARTITION BY month for month-to-date.
Q6. ROW_NUMBER vs RANK vs DENSE_RANK?
With ties 100,100,90: ROW_NUMBER 1,2,3; RANK 1,1,3; DENSE_RANK 1,1,2.
Q7. What is a CTE and why use it?
A named temporary result (WITH x AS (…)) that makes multi-step queries readable and lets you reuse a step.
Q8. COUNT(*) vs COUNT(col)?
COUNT(*) counts rows; COUNT(col) counts non-NULL values in that column.
import sqlite3
import pandas as pd
con = sqlite3.connect("bazaar.db")
pd.read_csv("sales_data.csv").to_sql("sales", con, if_exists="replace", index=False)
pd.read_csv("employees.csv").to_sql("employees", con, if_exists="replace", index=False)
pd.read_csv("departments.csv").to_sql("departments", con, if_exists="replace", index=False)
print([r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type = 'table'")])Live problem 1: top earner per department
import sqlite3
import pandas as pd
con = sqlite3.connect("bazaar.db")
q = lambda sql: pd.read_sql(sql, con)
print(q("""
WITH r AS (
SELECT d.dept_name, e.name, e.salary,
RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rk
FROM employees e JOIN departments d ON e.dept_id = d.dept_id
)
SELECT dept_name, name, salary FROM r WHERE rk = 1 ORDER BY salary DESC
"""))Live problem 2: month-over-month revenue growth
import sqlite3
import pandas as pd
con = sqlite3.connect("bazaar.db")
q = lambda sql: pd.read_sql(sql, con)
print(q("""
WITH m AS (SELECT strftime('%m', order_date) AS month,
SUM(quantity * unit_price * (1 - discount)) AS rev FROM sales GROUP BY month)
SELECT month, ROUND(rev) AS revenue,
ROUND(100.0 * (rev - LAG(rev) OVER (ORDER BY month)) / LAG(rev) OVER (ORDER BY month), 1) AS growth_pct
FROM m
""").tail(4).to_string(index=False))Live problem 3: cities where the share of COD orders is above 20%
import sqlite3
import pandas as pd
con = sqlite3.connect("bazaar.db")
q = lambda sql: pd.read_sql(sql, con)
print(q("""
SELECT city, COUNT(*) AS orders,
ROUND(100.0 * SUM(CASE WHEN payment_mode = 'Cash on Delivery' THEN 1 ELSE 0 END) / COUNT(*), 1) AS cod_pct
FROM sales GROUP BY city HAVING cod_pct > 20 ORDER BY cod_pct DESC
"""))Python & pandas questions
🐍 Python & pandas
Q1. loc vs iloc?
loc uses labels (end included); iloc uses integer positions (end excluded).
Q2. How do you handle missing values in pandas?
Measure with isna().sum(); drop if few and random; fill with median/mode/group values; add a missing flag; for ML, impute inside a pipeline.
Q3. merge vs concat vs join?
merge = SQL-style join on keys; concat = stack along an axis; join = merge on the index.
Q4. agg vs transform vs apply in groupby?
agg returns one row per group; transform returns a value per original row; apply runs any function per group (most flexible, slowest).
Q5. List vs tuple vs set vs dict?
List: ordered, mutable. Tuple: ordered, immutable. Set: unique unordered items, fast membership. Dict: key → value lookup.
Q6. Why is vectorisation faster than loops?
NumPy/pandas run operations on whole arrays in optimised C code instead of executing Python bytecode per element.
Q7. What is a lambda function?
A small anonymous function: lambda x: x * 2 – handy inside apply, sort keys and map.
Live problem 4: top 2 products per category by revenue (pandas)
import pandas as pd
s = pd.read_csv("sales_data.csv")
s["revenue"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
top = (s.groupby(["category", "product"], as_index=False)["revenue"].sum()
.sort_values(["category", "revenue"], ascending=[True, False])
.groupby("category").head(2))
print(top.round(0).to_string(index=False))Live problem 5: first and latest order date per city, and days between
import pandas as pd
s = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
g = s.groupby("city")["order_date"].agg(first="min", last="max")
g["active_days"] = (g["last"] - g["first"]).dt.days
print(g.sort_values("active_days").head(4))Live problem 6: pure Python – most frequent word
from collections import Counter
text = "data beats opinions data drives decisions and good data wins"
words = text.lower().split()
print(Counter(words).most_common(2))
# without Counter:
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(max(freq, key=freq.get), freq[max(freq, key=freq.get)])Statistics questions
📊 Statistics & experiments
Q1. Mean vs median – which for salaries?
Median, because a few very high salaries pull the mean up.
Q2. What is a p-value?
If the null hypothesis were true, the probability of seeing results at least this extreme. Small p = evidence against H₀. Not the probability H₀ is true.
Q3. Type I vs Type II error?
Type I = false positive (reject a true H₀). Type II = false negative (miss a real effect).
Q4. Explain the Central Limit Theorem.
Means of large random samples are approximately normal around the true mean with SE = σ/√n, whatever the data’s shape.
Q5. Correlation vs causation – example?
Ice-cream sales and drownings both rise in summer (common cause: heat). Only randomised experiments establish causation.
Q6. How do you decide A/B test sample size?
From the baseline rate, minimum detectable effect, α (0.05) and power (0.8) using a power analysis – before starting the test.
Q7. What is a confidence interval?
A range from a method that captures the true parameter in, e.g., 95% of repeated samples.
Live problem 7: is the new checkout better?
import pandas as pd
from statsmodels.stats.proportion import proportions_ztest
ab = pd.read_csv("ab_test.csv")
g = ab.groupby("group")["converted"].agg(["sum", "count"])
z, p = proportions_ztest(g.loc[["B", "A"], "sum"], g.loc[["B", "A"], "count"])
print((g["sum"] / g["count"]).round(4).to_dict(), f"| z = {z:.2f}, p = {p:.4f} →", "B is better" if p < 0.05 and z > 0 else "no clear winner")Machine-learning questions
🤖 Machine learning
Q1. Bias–variance trade-off?
Simple models have high bias (underfit); complex models high variance (overfit). Tune complexity with validation to minimise total error.
Q2. Precision vs recall – which for fraud?
Recall (catch most fraud), balanced with an acceptable precision; choose the threshold by the cost of each error.
Q3. Why is accuracy misleading on imbalanced data?
Predicting the majority class gets high accuracy but finds nothing. Use precision, recall, F1, PR-AUC.
Q4. Random forest vs gradient boosting?
Forest: parallel trees on bootstrap samples, averages, robust. Boosting: sequential trees fixing errors, often most accurate, needs tuning.
Q5. What is data leakage? Give an example.
Training uses information unavailable at prediction time – e.g. “refund_issued” to predict complaints, or scaling before splitting.
Q6. Why use cross-validation?
A more reliable estimate than one split (mean ± std) using all data for training and validation.
Q7. L1 vs L2 regularisation?
L1 (Lasso) can zero coefficients – feature selection. L2 (Ridge) shrinks all smoothly – good with correlated features.
Q8. How do you choose k in K-Means?
Elbow of inertia, silhouette score, and business usefulness of the segments.
Q9. How would you explain a model to a manager?
Lead with the business outcome, show top drivers (coefficients / permutation importance), give an example prediction with reasons, and state limits.
Live problem 8: train, evaluate and explain in 10 lines
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, classification_report
l = pd.read_csv("loan_applications.csv"); l["lti"] = l["loan_amount"] / (l["monthly_income"] * 12)
X, y = l[["credit_score", "lti", "years_employed", "monthly_income"]], l["approved"]
a, b, c, d = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
m = RandomForestClassifier(n_estimators=300, min_samples_leaf=5, random_state=0).fit(a, c)
print("AUC", round(roc_auc_score(d, m.predict_proba(b)[:, 1]), 3))
print(pd.Series(m.feature_importances_, index=X.columns).round(3).sort_values(ascending=False).to_dict())Case & product questions
🧩 Case studies
Q1. Daily orders dropped 20% yesterday. How do you investigate?
Check data/tracking issues first; then segment by platform, city, category, channel and new vs returning users; compare with the same weekday last week; look for external events (outage, holiday, competitor sale); quantify and report.
Q2. Which metrics would you track for a food-delivery app?
North star: weekly orders. Inputs: active users, conversion, AOV, delivery time, cancellation rate, repeat rate, restaurant availability; guardrails: refund rate, ratings.
Q3. Estimate the number of UPI transactions in a day in your city.
Structure it: population × share using UPI × transactions per user per day, sanity-check with known national numbers, and state assumptions clearly.
Clarify the goal → list hypotheses → say which data you would check → segment → quantify → recommend. Think out loud; structure matters more than the “right” number.
7-day revision plan
| Day | Revise | Practice |
|---|---|---|
| 1 | SQL basics, joins (Days 32–33) | 15 SQL problems |
| 2 | Window functions, CTEs (Day 34) | 10 hard SQL problems |
| 3 | pandas (Days 10–20) | Day 20 test again, timed |
| 4 | Statistics & A/B (Days 26–31) | Explain p-value, CI, CLT aloud |
| 5 | ML concepts + metrics (Days 36–45) | Train/evaluate in 15 minutes |
| 6 | Your projects | 2-minute pitch for each project |
| 7 | Mock interview + HR answers | Record yourself, fix filler words |
🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
import sqlite3
import pandas as pd
con = sqlite3.connect("bazaar.db")
q = lambda sql: pd.read_sql(sql, con)
print(q("""WITH cq AS (SELECT city, (CAST(strftime('%m', order_date) AS INT) + 2) / 3 AS qtr, SUM(quantity*unit_price*(1-discount)) AS rev FROM sales GROUP BY city, qtr),
g AS (SELECT city, qtr, rev, LAG(rev) OVER (PARTITION BY city ORDER BY qtr) AS prev FROM cq)
SELECT city FROM g WHERE qtr > 1 GROUP BY city HAVING SUM(CASE WHEN rev > prev THEN 1 ELSE 0 END) = 3"""))
print("Only these cities grew in Q2, Q3 and Q4 – a rare, consistent performer.")Show solution
import pandas as pd
s = pd.read_csv("sales_data.csv"); s["rev"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
a = s.groupby(["region", "payment_mode"])["rev"].mean().reset_index()
print(a.loc[a.groupby("region")["rev"].idxmax()].round(0).to_string(index=False))Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
What is your biggest weakness?
Pick a real, non-critical skill you are actively improving, with evidence: “I used to over-polish charts; now I timebox analysis and share drafts early – my last project went from idea to deployed app in 5 days.”
Do you have any questions for us?
Always yes: “What does success look like in the first 90 days?”, “Which tools and data does the team use?”, “How do analysts work with product and business teams?”
Summary
- Interviews test SQL, pandas, statistics, ML and communication.
- Practise live problems with a timer – and explain while you code.
- Structure case answers; always quantify.
- Next: the 5-day major project that ties everything together.
Major project begins! Day 56: telecom churn – define the business problem and plan the solution.
