# Top 25 SQL Data Science Interview Questions

Aced (formerly Exponent) publishes a public search API over its indexed pages; the guide is at https://www.aced.io/agents/agent-access.

Source: https://www.aced.io/blog/top-sql-data-science-interview-questions
Source observed: 2026-11-04T22:21:34.848Z
Last checked: 2026-11-04T22:21:34.848+00:00
Indexed: 2026-11-06T17:13:26.546+00:00

---

# Top 25 SQL Data Science Interview Questions

We created this guide to help data science candidates prepare for SQL interviews. SQL supports querying, manipulating, and interpreting data, and interview expectations vary by seniority. Junior candidates should know basic querying and aggregation; mid-level candidates should know joins, subqueries, `CASE WHEN`, dates, CTEs, set operations, and string functions; senior candidates should know window functions, pivot tables, transformations, normalization, indexing, schema design, transactions, and execution plans.

The guide contains excerpts from our [data science interview course](https://www.aced.io/courses/data-science?ref=exponent-blog.ghost.io) and [SQL interview course](https://www.aced.io/courses/sql-interviews?ref=exponent-blog.ghost.io). Each example includes a question, sample SQL, and an explanation. We compiled the examples with input from data analysts, data scientists, and machine learning engineers at Meta, Google, Dropbox, Amazon, and top consulting firms. Derrick Mwiti, a senior data scientist and [course instructor](https://www.udemy.com/user/mwitiderrick/?ref=exponent-blog.ghost.io), wrote and compiled the guide.

## Quick preparation guidance

- **Junior:** Practice `WHERE`, `INNER JOIN`, `LEFT JOIN`, `ORDER BY`, `GROUP BY`, `COUNT()`, `SUM()`, `AVG()`, `MIN()`, and `MAX()`.
- **Mid-level:** Practice complex joins, nested and correlated subqueries, `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, `LEAD()`, `LAG()`, `CASE WHEN`, date and time manipulation, `WITH`, `UNION`, `INTERSECT`, `EXCEPT`, `CONCAT()`, `SUBSTRING()`, and `REPLACE()`.
- **Senior:** Practice window functions, efficient queries and execution plans, recursive CTEs, pivot tables, complex transformations and aggregations, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, normalization, indexing, and schema design.
- At every level, understand the data, ask clarifying questions, explain your approach, and then write the query.

## Beginner SQL

Beginner interviews commonly test filtering, joins, aggregation, grouping, sorting, and relational-database concepts. Refresh our lessons on [SQL syntax](https://www.aced.io/courses/sql-interviews/sql-syntax?ref=exponent-blog.ghost.io), [aggregations](https://www.aced.io/courses/sql-interviews/introduction-to-sql-aggregations?ref=exponent-blog.ghost.io), [joins](https://www.aced.io/courses/sql-interviews/joins?ref=exponent-blog.ghost.io), [relational databases](https://www.aced.io/courses/sql-interviews/relational-databases?ref=exponent-blog.ghost.io), and [WHERE clauses](https://www.aced.io/courses/sql-interviews/where-clause?ref=exponent-blog.ghost.io).

### 1. Employees Earning More Than Managers

Given `employee(employee_id, name, salary, department_id, manager_id)`, return `employee_id` and `employee_name` for employees whose salary exceeds their direct manager’s salary.

```sql
SELECT e.employee_id, e.name AS employee_name
FROM employee e
JOIN employee m ON e.manager_id = m.employee_id
WHERE e.salary > m.salary;
```

We alias the table as `e` for employees and `m` for managers, join through `e.manager_id = m.employee_id`, filter on salary, and select the employee identifier and name. Practice with [Employee Earnings](https://www.aced.io/courses/sql-interviews/employee-earnings?ref=exponent-blog.ghost.io).

### 2. Average Unmatched Bookings on Lyft

This is a **sample interview scenario about Lyft**, a ride-sharing company. Given `users(user_id, user_name, email)` and `bookings(booking_id, user_id, driver_id, booking_time, status)`, return each user and `avg_unmatched_bookings`, rounded to two decimal places.

```sql
SELECT u.user_id, u.user_name, u.email,
       COALESCE(
         ROUND(AVG(CASE WHEN b.status = 'Unmatched' THEN 1 ELSE 0 END), 2),
         0
       ) AS avg_unmatched_bookings
FROM users u
LEFT JOIN bookings b ON u.user_id = b.user_id
GROUP BY u.user_id, u.user_name, u.email;
```

The `LEFT JOIN` retains users with no bookings. `CASE` converts unmatched bookings to `1` and other bookings to `0`; `AVG`, `ROUND`, and `COALESCE` calculate, round, and default the result. Practice with [Lyft Ride Requests](https://www.aced.io/courses/sql-interviews/lyft-ride-requests?ref=exponent-blog.ghost.io).

### 3. Successful Posts Per User Type

Given `post(post_id, post_date, user_id, interface, is_successful_post)` and `post_user(user_id, user_type, age)`, calculate November 2023 posts by `user_type`. Return successful posts, total attempts, and a success rate from `0.00` to `1.00`, ordered by descending rate.

```sql
SELECT pu.user_type,
       COUNT(CASE WHEN p.is_successful_post = 1 THEN 1 END) AS post_success,
       COUNT(p.post_id) AS post_attempt,
       ROUND(
         COUNT(CASE WHEN p.is_successful_post = 1 THEN 1 END) * 1.0
         / COUNT(p.post_id), 2
       ) AS post_success_rate
FROM post p
JOIN post_user pu ON p.user_id = pu.user_id
WHERE p.post_date >= '2023-11-01'
  AND p.post_date < '2023-12-01'
GROUP BY pu.user_type
ORDER BY post_success_rate DESC;
```

We join by `user_id`, use the date range for November, count successful posts conditionally, multiply by `1.0` for floating-point division, group by user type, and sort descending.

### 4. Average Duration of a Marketing Campaign

Given `campaign(upsell_campaign_id, date_start, date_end)`, calculate average campaign duration in days. The scenario also names `user(user_id, name, is_eligible_for_upsell_campaign)` and `transaction(transaction_id, user_id, product_id, transaction_date, quantity)`.

```sql
SELECT AVG(DATEDIFF(date_end, date_start)) AS avg_campaign_length
FROM campaign;
```

`DATEDIFF` calculates each campaign’s length and `AVG` calculates the average. Practice with [Marketing Campaign Duration](https://www.aced.io/courses/sql-interviews/marketing-campaign-duration?ref=exponent-blog.ghost.io).

### 5. Total Viewership on Laptops and Mobile Devices

This is a **sample interview scenario about Netflix**. Given `viewership(user_id, device_type, view_time)`, where device types are `phone`, `tablet`, and `laptop`, count laptop views and mobile views. Mobile means phone plus tablet.

```sql
SELECT
  SUM(CASE WHEN device_type = 'laptop' THEN 1 ELSE 0 END) AS laptop_views,
  SUM(CASE WHEN device_type IN ('phone', 'tablet') THEN 1 ELSE 0 END) AS mobile_views
FROM viewership;
```

### 6. Average Star Rating of Product by Month

Given `reviews(review_id, user_id, submit_date, product_id, stars)`, return numerical month, product ID, and average stars rounded to two decimals, ordered by month and product ID.

```sql
SELECT EXTRACT(MONTH FROM submit_date) AS mth,
       product_id,
       ROUND(AVG(stars), 2) AS avg_stars
FROM reviews
GROUP BY EXTRACT(MONTH FROM submit_date), product_id
ORDER BY mth, product_id;
```

### 7. Discount Product Catalog

This is a **sample interview scenario about Amazon**. Given `products(name, type, price)`, apply these seasonal discounts: electronics 10%, clothing 20%, groceries 5%, and books 15%. Return `name`, `type`, and a discounted price rounded to cents.

```sql
SELECT name, type,
       ROUND(
         price * CASE
           WHEN type = 'Electronic' THEN 0.90
           WHEN type = 'Clothing' THEN 0.80
           WHEN type = 'Grocery' THEN 0.95
           WHEN type = 'Book' THEN 0.85
           ELSE 1.00
         END,
         2
       ) AS discounted_price
FROM products;
```

### 8. Differences in Credit Cards Issued

This is a **sample interview scenario about a bank like Capital One**. Given monthly issuance data with `card_name`, `issued_amount`, `issue_month`, and `issue_year`, calculate the range between the highest and lowest issuance amount for each card and sort by the largest difference.

```sql
SELECT card_name,
       MAX(issued_amount) - MIN(issued_amount) AS difference
FROM monthly_cards_issued
GROUP BY card_name
ORDER BY difference DESC;
```

### 9. Transactions by City

Given `users(id, first_name, last_name, user_city, email)` and `transactions(id, customer_id, product_id, currency_code, date, amount)`, count transactions by city and sort descending.

```sql
SELECT u.user_city,
       COUNT(t.id) AS number_of_transactions
FROM users u
JOIN transactions t ON u.id = t.customer_id
GROUP BY u.user_city
ORDER BY number_of_transactions DESC;
```

Practice with [Sales by Customer City](https://www.aced.io/courses/sql-interviews/sales-by-city?ref=exponent-blog.ghost.io).

## Intermediate SQL

Intermediate candidates should be able to clean, transform, preprocess, and summarize larger datasets. Practice [subqueries](https://www.aced.io/courses/sql-interviews/subqueries?ref=exponent-blog.ghost.io), [cross joins](https://www.aced.io/courses/sql-interviews/cross-joins?ref=exponent-blog.ghost.io), [date and time functions](https://www.aced.io/courses/sql-interviews/date-and-time?ref=exponent-blog.ghost.io), and [CTEs](https://www.aced.io/courses/sql-interviews/common-table-expressions?ref=exponent-blog.ghost.io).

### 10. Revenue by Country

Given `purchase_orders(quantity, price, country)`, compute revenue as `quantity * price`, sum it by country, and order by descending revenue.

```sql
SELECT country, SUM(quantity * price) AS total_revenue
FROM purchase_orders
GROUP BY country
ORDER BY total_revenue DESC;
```

### 11. Categorize Orders by Size

Given `orders(quantity)`, label orders with `quantity >= 2` as `large` and all others as `small`.

```sql
SELECT *,
       CASE WHEN quantity >= 2 THEN 'large' ELSE 'small' END AS size
FROM orders;
```

### 12. Orders Per Month

Given timestamps in `orders.order_date`, aggregate order counts by month. Syntax varies by database:

```sql
-- SQLite
SELECT DATE(order_date, 'start of month') AS order_month,
       COUNT(*) AS no_orders
FROM orders
GROUP BY order_month;
```

Use `DATE_TRUNC('month', column)` in PostgreSQL or `EXTRACT(MONTH FROM column)` in MySQL.

### 13. Retention Based on Signup and Churn Dates

Given `users(signup_date, churn_date)`, calculate average retention in days grouped by signup month.

```sql
SELECT date_trunc('month', signup_date) AS signup_month,
       AVG(datediff('day', signup_date, churn_date)) AS avg_retention
FROM users
GROUP BY signup_month;
```

### 14. Orders with Customer Data from March

Given `customers` and `orders`, where `orders.customer_id` references `customers.id`, return orders and customer data for March 2022.

```sql
SELECT orders.id AS order_id, customers.*
FROM orders
INNER JOIN customers ON orders.customer_id = customers.id
WHERE orders.order_date BETWEEN '2022-03-01' AND '2022-04-01';
```

### 15. Customers with At Least One Order Using Subqueries

Return customers with at least one order using either approach:

```sql
SELECT *
FROM customers
WHERE (SELECT COUNT(*)
       FROM orders
       WHERE customers.id = orders.customer_id) > 0;
```

```sql
SELECT *
FROM customers
WHERE id IN (SELECT customer_id FROM orders);
```

Learn more about [subqueries and derived tables](https://www.aced.io/courses/sql-interviews/subqueries?ref=exponent-blog.ghost.io).

### 16. Customers with At Least One Order Using CTEs

A CTE is defined before the main query and can be referenced multiple times; a subquery is defined inside the main query.

```sql
WITH customer_orders AS (
  SELECT customer_id, COUNT(*) AS num_orders
  FROM orders
  GROUP BY customer_id
)
SELECT customers.*
FROM customers
JOIN customer_orders ON customers.id = customer_orders.customer_id
WHERE customer_orders.num_orders > 0;
```

### 17. Orders Ranked by Total Price

Given `orders(price, quantity)`, calculate each order’s total price and rank it. Ties receive the same `RANK()` value; `DENSE_RANK()` also gives ties the same value but does not skip the next rank.

```sql
SELECT orders.*,
       SUM(quantity * price) AS total_price,
       RANK() OVER (ORDER BY SUM(quantity * price) DESC) AS rank
FROM orders
GROUP BY id, customer_id;
```

## Advanced SQL

Senior candidates should be comfortable working with very large datasets and with questions involving companies such as Meta, Microsoft, TikTok, and Google. The guide also connects SQL preparation with [machine learning interview preparation](https://www.aced.io/blog/top-machine-learning-interview-questions?ref=exponent-blog.ghost.io).

### 18. Top Earning Employee by Department

Return one highest-paid employee per department, ordered by department name. The sample schema contains:

```text
employees                             projects
+---------------+---------+           +---------------+---------+
| id            | int     |<----+  +->| id            | int     |
| first_name    | varchar |     |  |  | title         | varchar |
| last_name     | varchar |     |  |  | start_date    | date    |
| salary        | int     |     |  |  | end_date      | date    |
| department_id | int     |--+  |  |  | budget        | int     |
+---------------+---------+  |  |  |  +---------------+---------+
                             |  |  |
departments                  |  |  |  employees_projects
+---------------+---------+  |  |  |  +---------------+---------+
| id            | int     |<-+  |  +--| project_id    | int     |
| name          | varchar |     +-----| employee_id   | int     |
+---------------+---------+           +---------------+---------+
```

Expected output format:

```text
department_name | employee_id | first_name | last_name | salary
----------------+-------------+------------+-----------+-------
varchar         | int         | varchar    | varchar   | int
```

```sql
WITH ranked_employees AS (
  SELECT e.id AS employee_id,
         e.first_name,
         e.last_name,
         e.salary,
         d.name AS department_name,
         ROW_NUMBER() OVER (
           PARTITION BY e.department_id
           ORDER BY e.salary DESC
         ) AS rank
  FROM employees e
  JOIN departments d ON e.department_id = d.id
)
SELECT department_name, employee_id, first_name, last_name, salary
FROM ranked_employees
WHERE rank = 1
ORDER BY department_name;
```

This uses `ROW_NUMBER()` to choose one top earner per department. Practice with [Top Salaries by Department](https://www.aced.io/courses/sql-interviews/top-salaries-by-department?ref=exponent-blog.ghost.io).

### 19. Group Users by Number of Tweets in 2022

Given `tweets(tweet_id, user_id, msg, tweet_date)`, count tweets per user in 2022, then count users in each tweet-count bucket.

```sql
WITH tweet_cte AS (
  SELECT user_id, COUNT(*) AS tweet_bucket
  FROM tweets
  WHERE EXTRACT(YEAR FROM tweet_date) = 2022
  GROUP BY user_id
)
SELECT tweet_bucket, COUNT(*) AS users_num
FROM tweet_cte
GROUP BY tweet_bucket;
```

### 20. Monthly Active Users in July 2022

This is a **sample interview scenario about Facebook**. Given `user_actions(user_id, event_id, event_type, event_date)`, count users active in both June and July 2022, considering `sign-in`, `like`, and `comment` events.

```sql
WITH june_actions AS (
  SELECT DISTINCT user_id
  FROM user_actions
  WHERE event_date BETWEEN '2022-06-01' AND '2022-06-30'
    AND event_type IN ('sign-in', 'like', 'comment')
), july_actions AS (
  SELECT DISTINCT user_id
  FROM user_actions
  WHERE event_date BETWEEN '2022-07-01' AND '2022-07-31'
    AND event_type IN ('sign-in', 'like', 'comment')
)
SELECT 7 AS month,
       COUNT(*) AS monthly_active_users
FROM july_actions
WHERE user_id IN (SELECT user_id FROM june_actions);
```

We also offer the [Analyze monthly customer transactions](https://www.aced.io/courses/sql-interviews/mock-interview-analyze-monthly-customer-transactions?ref=exponent-blog.ghost.io) mock interview.

### 21. Success Rate of a Post When the Previous Post Failed

Given `post` and `post_user`, calculate each user’s next-post success rate after a failed post and order by increasing rate.

```sql
WITH post_seq AS (
  SELECT p.user_id,
         p.post_id,
         ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY post_date
         ) AS post_seq_id,
         is_successful_post
  FROM post AS p
), post_pairings AS (
  SELECT ps.user_id,
         ps.post_seq_id AS fail_post_id,
         ps.post_seq_id + 1 AS next_post_id
  FROM post_seq AS ps
  WHERE ps.is_successful_post = 0
)
SELECT pp.user_id,
       ROUND(SUM(p2.is_successful_post) * 1.0
             / COUNT(p2.is_successful_post), 2) AS next_post_sc_rate
FROM post_pairings AS pp
JOIN post AS p2 ON pp.next_post_id = p2.post_id
GROUP BY 1
ORDER BY next_post_sc_rate ASC;
```

Practice with [Post Success After Failure](https://www.aced.io/courses/sql-interviews/post-success-after-failure?ref=exponent-blog.ghost.io).

### 22. Identify Repeat Payments

Given `transactions(transaction_id, merchant_id, credit_card_id, amount, transaction_timestamp)`, count payments at the same merchant using the same card and amount when they occur within 10 minutes of the preceding transaction. The first transaction is not a repeat; three qualifying transactions produce two repeats.

```sql
WITH PreviousTransactions AS (
  SELECT transaction_id,
         merchant_id,
         credit_card_id,
         amount,
         transaction_timestamp,
         LAG(transaction_timestamp) OVER (
           PARTITION BY merchant_id, credit_card_id, amount
           ORDER BY transaction_timestamp
         ) AS previous_transaction
  FROM transactions
), RepeatPayments AS (
  SELECT transaction_id,
         merchant_id,
         credit_card_id,
         amount,
         transaction_timestamp
  FROM PreviousTransactions
  WHERE previous_transaction IS NOT NULL
    AND transaction_timestamp <= previous_transaction + INTERVAL '10 MINUTE'
)
SELECT COUNT(*) AS payment_count
FROM RepeatPayments;
```

### 23. Top Customers by Order Count in the Last 5 Years

Given `orders(order_id, customer_id, order_date, order_amount, department_id)`, `departments(department_id, department_name)`, and `customers(customer_id, first_name, last_name)`, identify the top customers by order count for 2019–2023. The requested output is customer identity, total orders, and year; the sample query returns rows ranked first for each year.

```sql
WITH orders_per_year AS (
  SELECT c.customer_id,
         c.first_name,
         c.last_name,
         EXTRACT(YEAR FROM o.order_date) AS years,
         COUNT(o.order_id) AS total_orders,
         RANK() OVER (
           PARTITION BY EXTRACT(YEAR FROM o.order_date)
           ORDER BY COUNT(o.order_id) DESC
         ) AS order_rankings
  FROM orders o
  JOIN customers c ON o.customer_id = c.customer_id
  WHERE EXTRACT(YEAR FROM o.order_date) IN (2019, 2020, 2021, 2022, 2023)
  GROUP BY EXTRACT(YEAR FROM o.order_date),
           c.customer_id, c.first_name, c.last_name
)
SELECT first_name, last_name, total_orders, years
FROM orders_per_year
WHERE order_rankings = 1
ORDER BY years ASC;
```

### 24. Calculate Total Server Uptime

This is a **sample interview scenario about a cloud provider like AWS**. Given `server_utilization(server_id, status_time, session_status)`, where status is `start` or `stop`, sum all server sessions and return uptime in days.

```sql
WITH SessionDurations AS (
  SELECT server_id,
         status_time AS start_time,
         LEAD(status_time) OVER (
           PARTITION BY server_id ORDER BY status_time
         ) AS stop_time,
         session_status
  FROM server_utilization
), FilteredSessions AS (
  SELECT server_id, start_time, stop_time
  FROM SessionDurations
  WHERE session_status = 'start'
    AND stop_time IS NOT NULL
), CalculatedDurations AS (
  SELECT server_id,
         EXTRACT(EPOCH FROM (stop_time - start_time)) AS uptime_seconds
  FROM FilteredSessions
)
SELECT ROUND(SUM(uptime_seconds) / (24 * 60 * 60), 0) AS total_uptime_days
FROM CalculatedDurations;
```

### 25. Top 2 Players by Highest Score

Given `players(player_id, player_name, team_id)` and `scores(score_id, player_id, game_score)`, find each player’s highest score and return the top two score ranks per team. Ties are retained, so a team can have more than two players.

```sql
WITH PlayerMaxScores AS (
  SELECT p.team_id,
         p.player_name,
         MAX(s.game_score) AS max_score
  FROM players p
  JOIN scores s ON p.player_id = s.player_id
  GROUP BY p.team_id, p.player_name
), RankedPlayers AS (
  SELECT team_id,
         player_name,
         max_score,
         DENSE_RANK() OVER (
           PARTITION BY team_id ORDER BY max_score DESC
         ) AS rank
  FROM PlayerMaxScores
)
SELECT team_id, player_name, max_score
FROM RankedPlayers
WHERE rank <= 2
ORDER BY team_id, max_score DESC, player_name;
```

## Interview resources

We offer:

- [Data scientist interview questions](https://www.aced.io/questions?role=data-science&src=blog).
- A [free mock interview session](https://www.aced.io/practice?ref=exponent-blog.ghost.io).
- [Data science interviewing coaching](https://www.aced.io/coaching?category=mock_interviews&role=data-science&ref=exponent-blog.ghost.io), including mock interviews, career coaching, and resume review.
- A [data science interview course](https://www.aced.io/courses/data-science?ref=exponent-blog.ghost.io) with mock interviews, frameworks, statistics, experimentation, coding, SQL, machine learning, and behavioral preparation.
- A [SQL interview course](https://www.aced.io/courses/sql-interviews?ref=exponent-blog.ghost.io).

Our related [Data Science Interview Prep Course](https://www.aced.io/courses/data-science) has 8 courses and 5,300 students. Our [Python Coding Questions for Data Scientists](https://www.aced.io/courses/python-coding-data-scientist-questions) course has 18 lessons and 1,000 students. We also link to [Top 25 Python Data Science Interview Questions](https://www.aced.io/blog/top-python-data-science-interview-questions), [Top 25 Statistics Data Science Interview Questions](https://www.aced.io/blog/top-statistics-data-science-interview-questions), [Data Science Career Path](https://www.aced.io/blog/data-science-career-path), and [Complete Data Scientist Resume Guide](https://www.aced.io/blog/data-science-resume).


---

[Read this page’s summary](https://www.aced.io/agents/api/public/v1/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fblog%2Ftop-sql-data-science-interview-questions&trace=t_679ff9ab98f3)

## Ask a follow-up about this page

Need a more specific answer? Ask the exact question you have. It returns a fresh, cited answer from Aced (formerly Exponent)’s knowledge base. No account or API key required.

Open this URL with your own question, URL-encoded. Include your question in q. All research inputs are optional; no account or setup.

`GET https://www.aced.io/agents/agent/faq?q={question}&trace=t_679ff9ab98f3`

[Tool guide and examples](https://www.aced.io/agents/agent-access) · [OpenAPI](https://www.aced.io/agents/api/public/v1/openapi.json) · [Page TLDR form](https://www.aced.io/agents/agent-tools/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fblog%2Ftop-sql-data-science-interview-questions). Opening a form does not execute a tool.