New: Frontend mock interviews added to Exponent Practice →

Top SQL Interview Questions

Review this list of 67 sql interview questions and answers verified by hiring managers and candidates.
  • +35

    "SELECT MIN(id) AS id, TRIM(LOWER(email)) AS cleaned_email FROM users GROUP BY cleaned_email ORDER BY id `"

    Salome L. - "SELECT MIN(id) AS id, TRIM(LOWER(email)) AS cleaned_email FROM users GROUP BY cleaned_email ORDER BY id `"See full answer

    Data Engineer
    SQL
    +2 more
  • Video answer for 'Employee Earnings.'
    +23

    "SELECT e.firstname, m.salary AS managersalary FROM employees AS e INNER JOIN employees AS m ON e.manager_id = m.id WHERE e.salary > m.salary;"

    Riley F. - "SELECT e.firstname, m.salary AS managersalary FROM employees AS e INNER JOIN employees AS m ON e.manager_id = m.id WHERE e.salary > m.salary;"See full answer

    Data Analyst
    SQL
    +2 more
  • +7

    "Answer: select fromcaller, count(DISTINCT tocallee) as num_calls from calls group by fromcaller having count(DISTINCT tocallee) >= 3 Setup: CREATE TABLE calls ( from_caller VARCHAR(20), to_callee VARCHAR(20) ); INSERT INTO calls (fromcaller, tocallee) VALUES ('Alice', 'Bob'), ('Charlie', 'Dave'), ('Alice', 'Frank'), ('Charlie', 'Heidi'), ('Charlie', 'Judy'); "

    KAI - "Answer: select fromcaller, count(DISTINCT tocallee) as num_calls from calls group by fromcaller having count(DISTINCT tocallee) >= 3 Setup: CREATE TABLE calls ( from_caller VARCHAR(20), to_callee VARCHAR(20) ); INSERT INTO calls (fromcaller, tocallee) VALUES ('Alice', 'Bob'), ('Charlie', 'Dave'), ('Alice', 'Frank'), ('Charlie', 'Heidi'), ('Charlie', 'Judy'); "See full answer

    Data Scientist
    SQL
    +1 more
  • "it is really good explanation thanks it is really good explanation thanks"

    Amney M. - "it is really good explanation thanks it is really good explanation thanks"See full answer

    SQL
    Coding
    +1 more
  • +23

    "-- Write your query here Select customer_id , order_date , orderid as secondearliestorderid from ( select * , Rank() over (partition by customerid , orderdate order by order_id ) as rnk from orders) a where rnk =2 order by orderdate, customerid"

    Palak S. - "-- Write your query here Select customer_id , order_date , orderid as secondearliestorderid from ( select * , Rank() over (partition by customerid , orderdate order by order_id ) as rnk from orders) a where rnk =2 order by orderdate, customerid"See full answer

    Data Engineer
    SQL
    +2 more
  • 🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.

  • Tree Node.

    IDE
    Easy
    Video answer for 'Tree Node.'
    +9

    "-- Write your query here select id, (case when p_id is null then 'Root' when pid in (select id from treenode_table) and id in (select pid from treenode_table) then 'Inner' else 'Leaf' end) as node_types from treenodetable order by 1; `"

    Anonymous Roadrunner - "-- Write your query here select id, (case when p_id is null then 'Root' when pid in (select id from treenode_table) and id in (select pid from treenode_table) then 'Inner' else 'Leaf' end) as node_types from treenodetable order by 1; `"See full answer

    Data Engineer
    SQL
    +2 more
  • +42

    "Limit and rank() only works if there are no 2 employees with same salary ( which is okay for this use case) For the query to pass all the test results, we need to use dense_rank with ranked_employees as ( select id, firstname, lastname, salary, denserank() over(order by salary desc) as salaryrank from employees ) select id, firstname, lastname, salary from ranked_employees where salary_rank <= 3 `"

    Vysali K. - "Limit and rank() only works if there are no 2 employees with same salary ( which is okay for this use case) For the query to pass all the test results, we need to use dense_rank with ranked_employees as ( select id, firstname, lastname, salary, denserank() over(order by salary desc) as salaryrank from employees ) select id, firstname, lastname, salary from ranked_employees where salary_rank <= 3 `"See full answer

    Data Engineer
    SQL
    +2 more
  • +24

    "Here's a simpler solution: select u.username , count(p.postid) as countposts from posts as p join users as u on p.userid = u.userid where p.likes >= 100 group by 1 order by 2 desc, 1 asc limit 3 `"

    Bradley E. - "Here's a simpler solution: select u.username , count(p.postid) as countposts from posts as p join users as u on p.userid = u.userid where p.likes >= 100 group by 1 order by 2 desc, 1 asc limit 3 `"See full answer

    Data Engineer
    SQL
    +2 more
  • Video answer for 'E-commerce (1 of 5)'
    +9

    "select sum(orderquantity) as totalunitsorderedyesterday from orders as ord join items as it on ord.itemid=it.itemid where order_date="2023-10-14""

    Rudra pratap S. - "select sum(orderquantity) as totalunitsorderedyesterday from orders as ord join items as it on ord.itemid=it.itemid where order_date="2023-10-14""See full answer

    Data Engineer
    SQL
    +2 more
  • Video answer for 'E-commerce (2 of 5)'
    +8

    "SELECT items.item_category, SUM(orders.orderquantity) AS totalunitsorderedlast7days FROM orders JOIN items ON orders.itemid = items.itemid WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now') GROUP BY items.item_category `"

    Salome L. - "SELECT items.item_category, SUM(orders.orderquantity) AS totalunitsorderedlast7days FROM orders JOIN items ON orders.itemid = items.itemid WHERE orders.order_date BETWEEN DATE('now', '-6 days') AND DATE('now') GROUP BY items.item_category `"See full answer

    Data Engineer
    SQL
    +2 more
  • +17

    "SELECT d.name as departmentname,e.id as employeeid,e.firstname,e.lastname,MAX(e.salary) as salary FROM employees e LEFT JOIN departments d ON e.department_id=d.id GROUP BY department_name ORDER BY department_name;"

    Anisha S. - "SELECT d.name as departmentname,e.id as employeeid,e.firstname,e.lastname,MAX(e.salary) as salary FROM employees e LEFT JOIN departments d ON e.department_id=d.id GROUP BY department_name ORDER BY department_name;"See full answer

    Data Engineer
    SQL
    +2 more
  • Google logoAsked at Google 
    +2

    "DECLARE @n INT = 20, -- number of terms in the series @first INT = 0, -- first term @second INT = 1, -- second term @current INT, -- current term @counter INT = 0 -- counter for loop -- Create a table variable to store the series DECLARE @FibonacciSeries TABLE (Term INT) -- Insert the first two terms into the table variable INSERT INTO @FibonacciSeries (Term) VALUES (@first), (@second) -- Use a WHILE loop to generate the remaining terms WHILE (@counter <"

    Cengiz I. - "DECLARE @n INT = 20, -- number of terms in the series @first INT = 0, -- first term @second INT = 1, -- second term @current INT, -- current term @counter INT = 0 -- counter for loop -- Create a table variable to store the series DECLARE @FibonacciSeries TABLE (Term INT) -- Insert the first two terms into the table variable INSERT INTO @FibonacciSeries (Term) VALUES (@first), (@second) -- Use a WHILE loop to generate the remaining terms WHILE (@counter <"See full answer

    Data Analyst
    SQL
    +2 more
  • Amazon logoAsked at Amazon 

    "1) select avg(session) from table where session> 180 2) select round(sessiontime/300)*300 as sessionbin, count() as sessioncount from table group by round(sessiontime/300)300 order by session_bin 3) SELECT t1.country AS country_a, t2.country AS country_b FROM ( SELECT country, COUNT(*) AS session_count FROM yourtablename GROUP BY country ) AS t1 JOIN ( SELECT country, COUNT(*) AS session_count FROM yourtablename `GROUP BY countr"

    Erjan G. - "1) select avg(session) from table where session> 180 2) select round(sessiontime/300)*300 as sessionbin, count() as sessioncount from table group by round(sessiontime/300)300 order by session_bin 3) SELECT t1.country AS country_a, t2.country AS country_b FROM ( SELECT country, COUNT(*) AS session_count FROM yourtablename GROUP BY country ) AS t1 JOIN ( SELECT country, COUNT(*) AS session_count FROM yourtablename `GROUP BY countr"See full answer

    Data Analyst
    SQL
    +4 more
  • +9

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

    Akshay D. - "SELECT u.user_id, u.user_name, u.email, ROUND(AVG(CASE WHEN b.status = 'Unmatched' THEN 1.0 ELSE 0 END), 2) AS avgunmatchedbookings FROM users u LEFT JOIN bookings b ON u.userid = b.userid GROUP BY u.user_id, u.user_name, u.email; `"See full answer

    Data Engineer
    SQL
    +2 more
  • +16

    "WITH filtered_posts AS ( SELECT p.user_id, p.issuccessfulpost FROM post p WHERE p.postdate >= '2023-11-01' AND p.postdate < '2023-12-01' ), post_summary AS ( SELECT pu.user_type, COUNT(*) AS post_attempt, SUM(CASE WHEN fp.issuccessfulpost = 1 THEN 1 ELSE 0 END) AS post_success FROM filtered_posts fp JOIN postuser pu ON fp.userid = pu.user_id GROUP BY pu.user_type ) SELECT user_type, post_success, post_attempt, CAST(postsuccess AS FLOAT) / postattempt AS postsuccessrate FROM po"

    David I. - "WITH filtered_posts AS ( SELECT p.user_id, p.issuccessfulpost FROM post p WHERE p.postdate >= '2023-11-01' AND p.postdate < '2023-12-01' ), post_summary AS ( SELECT pu.user_type, COUNT(*) AS post_attempt, SUM(CASE WHEN fp.issuccessfulpost = 1 THEN 1 ELSE 0 END) AS post_success FROM filtered_posts fp JOIN postuser pu ON fp.userid = pu.user_id GROUP BY pu.user_type ) SELECT user_type, post_success, post_attempt, CAST(postsuccess AS FLOAT) / postattempt AS postsuccessrate FROM po"See full answer

    Data Engineer
    SQL
    +2 more
  • +8

    "--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column WITH RECURSIVE Hierarchy AS ( SELECT e.Emp_ID, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName, e.Manager_ID, 0 AS Level, CASE WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09 WHEN e.Country = 'INDIA' THEN s.Salary * 0.012 ELSE s.Salary "

    Victor N. - "--country names are UPPERCASE but the table in the in the question showing lowercase. That's why it took me a while to figure it out until I ran the country column WITH RECURSIVE Hierarchy AS ( SELECT e.Emp_ID, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS FullName, e.Manager_ID, 0 AS Level, CASE WHEN e.Country = 'IRELAND' THEN s.Salary * 1.09 WHEN e.Country = 'INDIA' THEN s.Salary * 0.012 ELSE s.Salary "See full answer

    Data Engineer
    SQL
    +2 more
  • "WITH ActiveUsersYesterday AS ( SELECT DISTINCT user_id FROM user_activity WHERE activity_date = CAST(GETDATE() - 1 AS DATE) ), VideoCallUsersYesterday AS ( SELECT DISTINCT user_id FROM video_calls WHERE call_date = CAST(GETDATE() - 1 AS DATE) ) SELECT (CAST(COUNT(DISTINCT v.userid) AS FLOAT) / NULLIF(COUNT(DISTINCT a.userid), 0)) * 100 AS percentagevideocall_users FROM ActiveUsersYesterday a LEFT JOIN VideoCallUsersYesterday v ON a.userid = v.userid;"

    Bala G. - "WITH ActiveUsersYesterday AS ( SELECT DISTINCT user_id FROM user_activity WHERE activity_date = CAST(GETDATE() - 1 AS DATE) ), VideoCallUsersYesterday AS ( SELECT DISTINCT user_id FROM video_calls WHERE call_date = CAST(GETDATE() - 1 AS DATE) ) SELECT (CAST(COUNT(DISTINCT v.userid) AS FLOAT) / NULLIF(COUNT(DISTINCT a.userid), 0)) * 100 AS percentagevideocall_users FROM ActiveUsersYesterday a LEFT JOIN VideoCallUsersYesterday v ON a.userid = v.userid;"See full answer

    Data Scientist
    SQL
    +2 more
  • +16

    "select name, stock from products p left join transactions t on p.id = t.product_id order by date desc limit 1"

    Daniel C. - "select name, stock from products p left join transactions t on p.id = t.product_id order by date desc limit 1"See full answer

    Data Engineer
    SQL
    +2 more
  • +10

    "The user table no longer exists as expected - I get an error that user does not contain user_id. Note that querying the table results in only user:swuoevkivrjfta select * FROM user `"

    Evan R. - "The user table no longer exists as expected - I get an error that user does not contain user_id. Note that querying the table results in only user:swuoevkivrjfta select * FROM user `"See full answer

    Data Engineer
    SQL
    +2 more
Showing 1-20 of 67