Here are 3 SQL interview questions focused on PostgreSQL with answers and explanations:
Question 1: Window Functions
Question: You have a table called sales with columns product_id, sale_date, and revenue. Write a query to find the running total of revenue for each product, ordered by date.
Answer:
SELECT
product_id,
sale_date,
revenue,
SUM(revenue) OVER (
PARTITION BY product_id
ORDER BY sale_date
ROWS UNBOUNDED PRECEDING
) AS running_total
FROM sales
ORDER BY product_id, sale_date;
Explanation: This uses PostgreSQL's window function SUM() OVER(). The PARTITION BY product_id clause ensures we calculate separate running totals for each product. The ORDER BY sale_date within the window function determines the order for accumulation. ROWS UNBOUNDED PRECEDING explicitly states we want all rows from the start of the partition up to the current row (though this is the default behavior when ORDER BY is used).
Question 2: Common Table Expressions (CTEs) and Joins
Question: Given two tables - employees (emp_id, name, department_id, salary) and departments (dept_id, dept_name), write a query to find all departments where the average salary is above $75,000, showing the department name and average salary.
Answer:
WITH dept_avg_salary AS (
SELECT
department_id,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 75000
)
SELECT
d.dept_name,
das.avg_salary
FROM dept_avg_salary das
JOIN departments d ON das.department_id = d.dept_id
ORDER BY das.avg_salary DESC;
Explanation: This solution uses a CTE (Common Table Expression) to first calculate the average salary per department and filter for those above $75,000 using the HAVING clause. The main query then joins this result with the departments table to get department names. CTEs make complex queries more readable and are particularly useful in PostgreSQL for breaking down multi-step operations.
Question 3: JSON Data Handling
Question: You have a table user_profiles with columns user_id and preferences (where preferences is a JSONB column). Write a query to find all users who have 'dark_mode' set to true in their preferences.
Answer:
SELECT
user_id,
preferences->>'dark_mode' AS dark_mode_setting
FROM user_profiles
WHERE preferences->>'dark_mode' = 'true';
Explanation: PostgreSQL's JSONB data type allows storing and querying JSON data efficiently. The ->> operator extracts a JSON field as text. For boolean comparison, we compare against the string 'true' since ->> returns text. Alternatively, you could use (preferences->'dark_mode')::boolean = true to cast the JSON value to a boolean for comparison. JSONB is preferred over JSON in PostgreSQL as it's stored in a binary format that's faster to process and supports indexing.