Here are three examples of SQL interview questions related to PostgreSQL, along with correct answers and explanations:
Question 1: Find the Second Highest Salary in the Employees Table
Question:
Write a SQL query to find the second highest salary in the employees table. Assume the table has columns id, name, and salary.
Answer:
sql
SELECT DISTINCT salary AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees)
ORDER BY salary DESC
LIMIT 1;
Explanation:
The subquery (SELECT MAX(salary) FROM employees) retrieves the highest salary.
The outer query selects salaries less than this maximum value.
DISTINCT ensures uniqueness in case multiple employees have the same salary.
ORDER BY salary DESC sorts the results in descending order, and LIMIT 1 picks the top result (the second highest).
Alternative (using window functions):
sql
SELECT salary
FROM (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn
FROM employees
WHERE salary IS NOT NULL
) AS ranked
WHERE rn = 2;
This method uses ROW_NUMBER() to rank salaries and selects the second rank. It handles ties differently (e.g., if multiple employees have the same salary).
Question 2: Calculate Cumulative Sales per Month
Question:
You have a sales table with columns sale_date (DATE) and amount (NUMERIC). Write a query to show monthly sales and the cumulative sales up to each month.
Answer:
sql
SELECT
date_trunc('month', sale_date) AS month,
SUM(amount) AS monthly_sales,
SUM(SUM(amount)) OVER (ORDER BY date_trunc('month', sale_date)) AS cumulative_sales
FROM sales
GROUP BY date_trunc('month', sale_date)
ORDER BY month;
Explanation:
date_trunc('month', sale_date) groups sales by month.
SUM(amount) calculates the total sales for each month.
The window functionSUM(SUM(amount)) OVER (ORDER BY ...) computes the running total of sales across months.
This approach avoids subqueries and leverages PostgreSQL's efficient window function capabilities.
Question 3: Query JSONB Data in PostgreSQL
Question:
You have a users table with a user_data column of type JSONB containing user details (e.g., {"name": "John", "email": "john@example.com"}). Write a query to find all users whose email domain is "example.com".
Answer:
sql
SELECT *
FROM users
WHERE user_data->>'email' LIKE '%@example.com';
Explanation:
user_data->>'email' extracts the email field as text.
LIKE '%@example.com' filters rows where the email ends with @example.com.
This uses PostgreSQL's JSONB operators (->> for text extraction) and standard SQL string matching.
Alternative (using JSONB functions):
sql
SELECT *
FROM users
WHERE JSONB_EXTRACT_PATH_TEXT(user_data, 'email') LIKE '%@example.com';
This uses JSONB_EXTRACT_PATH_TEXT for compatibility with older PostgreSQL versions, but ->> is more concise and modern.
Key Takeaways
PostgreSQL-specific features like JSONB, date_trunc, and window functions are often tested.
Handling edge cases (e.g., duplicates, NULLs) is critical for robust queries.
Efficiency matters: Use window functions instead of subqueries where possible.