β 10 Most Useful SQL Interview Queries
Commonly asked SQL queries with examples to help you crack interviews πΌ
1οΈβ£ Find the Second Highest Salary
This query uses a subquery to exclude the highest salary and then finds the maximum from the remaining values.
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2οΈβ£ Count Employees in Each Department
Uses GROUP BY to count employees department-wise.
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
3οΈβ£ Fetch Duplicate Emails
Identifies duplicate email addresses using HAVING with aggregate functions.
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
4οΈβ£ Join Orders with Customer Names
Demonstrates an INNER JOIN to combine data from customers and orders tables.
SELECT c.name, o.order_date
FROM customers c
JOIN orders o ON c.id = o.customer_id;
5οΈβ£ Get Top 3 Highest Salaries
Retrieves the top 3 unique salaries using ORDER BY and LIMIT.
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
6οΈβ£ Retrieve Latest 5 Logins
Orders records by login time to fetch the most recent login entries.
SELECT *
FROM logins
ORDER BY login_time DESC
LIMIT 5;
7οΈβ£ Employees with No Manager
Finds employees who are at the top of the hierarchy by checking NULL values.
SELECT name
FROM employees
WHERE manager_id IS NULL;
8οΈβ£ Search Names Starting with βSβ
Uses the LIKE operator for pattern matching.
SELECT *
FROM employees
WHERE name LIKE 'S%';
9οΈβ£ Total Sales Per Month
Groups sales data by month and calculates total sales amount.
SELECT MONTH(order_date) AS month, SUM(amount)
FROM sales
GROUP BY MONTH(order_date);
π Delete Inactive Users
Deletes users who have been inactive since a specific date.
DELETE FROM users
WHERE last_active < '2023-01-01';
Comments (0)
No comments yet
Be the first to share your thoughts!
Leave a Comment