25 SQL Questions As Per JD
25 SQL Questions As Per JD
Intermediate-Level (Medium)
Write an SQL query to find employees who have joined in the last 30 days in a table
named Employees with a JoinDate column.
sql
Copy code
SELECT * FROM Employees WHERE JoinDate >= NOW() - INTERVAL 30 DAY;
11. 12. What is a subquery, and how is it used in SQL? Provide an example.
A subquery is a query within another query, often used to filter results. Example:
sql
Copy code
SELECT * FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments
WHERE Location = 'Pune');
* How would you retrieve data from multiple tables with matching records? Write
a query using an INNER JOIN.
sql
Copy code
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
13. Write an SQL query to calculate the average salary in the Employees table and
group the result by Department.
sql
Copy code
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;
14. 15. Explain UNION vs UNION ALL. How do they differ?
* UNION combines the results of two queries and removes duplicates. UNION ALL
includes all records, including duplicates.
16. What is a primary key constraint, and why is it important in SQL?
* A primary key uniquely identifies each row in a table, ensuring that no
duplicate values are in the key column(s), which is essential for data integrity.
How would you retrieve the 5th highest salary from a table named Salaries?
sql
Copy code
SELECT DISTINCT Salary
FROM Salaries
ORDER BY Salary DESC
LIMIT 1 OFFSET 4;
17. Write a query to find duplicate records in a table named Orders with columns
OrderID, CustomerID, and OrderDate.
sql
Copy code
SELECT CustomerID, OrderDate, COUNT(*)
FROM Orders
GROUP BY CustomerID, OrderDate
HAVING COUNT(*) > 1;
18. 19. What is a stored procedure, and why would you use it?
* A stored procedure is a precompiled set of SQL statements saved in the
database. It is used to encapsulate complex logic, improve performance, and reduce
repetitive code.
Write an SQL query to fetch records where the OrderDate is within the last 7 days.
sql
Copy code
SELECT * FROM Orders WHERE OrderDate >= NOW() - INTERVAL 7 DAY;
20. ________________