SQL Interview Questions
SQL Interview Questions
1. Write a SQL query to find the second highest salary from the employees
table.
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2. Write a query to pivot data from rows to columns for sales data by month.
SELECT
product_id,
SUM(CASE WHEN MONTH(sale_date) = 1 THEN amount ELSE 0 END) AS
January,
SUM(CASE WHEN MONTH(sale_date) = 2 THEN amount ELSE 0 END) AS
February,
...
FROM sales
GROUP BY product_id;
3. Create a SQL query that retrieves all orders placed in the last 30 days along
with customer details.
SELECT o.order_id, o.order_date, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= NOW() - INTERVAL 30 DAY;
4. Write a query to find employees with salaries above the average salary of
their department.
SELECT e.employee_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE
department_id = e.department_id);
5. Write a SQL statement to update employee salaries by increasing them by
10% for those in the 'Sales' department.
UPDATE employees
SET salary = salary * 1.10
WHERE department = 'Sales';
6. Write a query to find all products that have never been sold (assuming there
is a sales table).
SELECT p.product_id, p.product_name
FROM products p
LEFT JOIN sales s ON p.product_id = s.product_id
WHERE s.product_id IS NULL;
7. Create a SQL query that retrieves the count of orders placed by each
customer in descending order of count.
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY order_count DESC;
10.Write a SQL query that retrieves all unique email domains from a user table.
SELECT DISTINCT SUBSTRING_INDEX(email, '@', -1) AS domain
FROM users;
WITH RankedEmployees AS (
SELECT EmployeeID, DepartmentID, Salary,
ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY Salary
DESC) AS Rank
FROM Employees
)
SELECT EmployeeID, DepartmentID, Salary
FROM RankedEmployees
WHERE Rank <= 3;