40 Most Asked SQL
40 Most Asked SQL
SQL Query
SELECT a.*, b.* FROM tableA a INNER JOIN tableB b ON a.id = b.id;
• LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and
matched rows from the right table.
SQL Query
SELECT a.*, b.* FROM tableA a LEFT JOIN tableB b ON a.id = b.id;
• RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table,
and matched rows from the left table.
SQL Query
SELECT a.*, b.* FROM tableA a RIGHT JOIN tableB b ON a.id = b.id;
• FULL JOIN (or FULL OUTER JOIN): Returns rows when there is a match in
one of the tables.
SQL Query
SELECT a.*, b.* FROM tableA a FULL JOIN tableB b ON a.id = b.id;
5. How do you use the GROUP BY clause in SQL?
• The GROUP BY clause is used to arrange identical data into groups.
SQL Query
SELECT column1, COUNT(*) FROM table GROUP BY column1;
6. What is the difference between WHERE and HAVING clauses?
• WHERE: Filters rows before grouping.
SQL Query
SELECT * FROM table WHERE condition;
• HAVING: Filters groups after grouping.
SQL Query
SELECT column1, COUNT(*) FROM table GROUP BY column1 HAVING COUNT(*) > 1;
7. Explain the concept of indexes in SQL. What are the types of indexes?
• Index: A database object that improves the speed of data retrieval operations on a
table.
• Types: Clustered Index, Non-Clustered Index, Unique Index, Full-Text Index.
8. How do you create and drop a table in SQL?
• Create Table:
SQL Query
CREATE TABLE tableName ( column1 datatype, column2 datatype, ... );
• Drop Table:
SQL Query
DROP TABLE tableName;
SQL Query
UPDATE tableName SET column1 = value1, column2 = value2, ... WHERE condition;
13. Explain the use of UNION and UNION ALL.
• UNION: Combines the result of two queries and removes duplicates.
SQL Query
SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2;
• UNION ALL: Combines the result of two queries including duplicates.
SQL Query
SELECT column1, column2 FROM table1 UNION ALL SELECT column1, column2 FROM
table2;
14. What is a subquery? Differentiate between correlated and non-correlated subqueries.
• Subquery: A query nested inside another query.
• Correlated Subquery: Depends on the outer query for its values.
SQL Query
SELECT column1 FROM table1 WHERE column2 > (SELECT AVG(column2) FROM table2
WHERE table2.id = table1.id);
• Non-Correlated Subquery: Independent of the outer query.
SQL Query
SELECT column1 FROM table1 WHERE column2 > (SELECT AVG(column2) FROM table2);
15. Explain the concept of window functions in SQL.
• Window Functions: Perform calculations across a set of table rows related to the
current row.
SQL Query
SELECT column1, column2, RANK() OVER (PARTITION BY column1 ORDER BY column2
DESC) as rank FROM table;
16. How do you use the CASE statement in SQL?
SQL Query
SELECT column1, CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE
result3 END as alias FROM table;
17. What are stored procedures? How do they differ from functions?
• Stored Procedure: A set of SQL statements with an assigned name stored in the
database.
• Functions: Returns a single value and can be used in SQL expressions.
SQL Query
-- Stored Procedure CREATE PROCEDURE procedureName AS BEGIN -- SQL Statements END;
-- Function CREATE FUNCTION functionName (@param datatype) RETURNS returnType AS
BEGIN -- SQL Statements RETURN value; END;
18. Explain the concept of transactions. What are ACID properties?
• Transaction: A sequence of SQL statements that form a logical unit of work.
• ACID Properties:
• Atomicity: All operations in a transaction complete successfully or none do.
• Consistency: Transaction transforms the database from one valid state to
another.
• Isolation: Transactions do not interfere with each other.
• Durability: Changes made by a transaction are permanent.
19. How do you handle errors in SQL?
• Use TRY...CATCH blocks in SQL Server or error handling mechanisms specific to the
SQL database.
SQL Query
BEGIN TRY -- SQL Statements END TRY BEGIN CATCH -- Error Handling END CATCH;
20. Write a query to find the second highest salary from a table.
SQL Query
SELECT MAX(salary) as SecondHighestSalary FROM table WHERE salary < (SELECT
MAX(salary) FROM table);
21. How would you retrieve the top N records from a table?
• In SQL Server:
SQL Query
SELECT TOP N * FROM table ORDER BY column;
• In MySQL:
SQL Query
SELECT * FROM table ORDER BY column LIMIT N;
SQL Query
SELECT column1, COUNT(*) FROM table GROUP BY column1 HAVING COUNT(*) > 1;
23. How can you calculate the running total in SQL?
SQL Query
SELECT column1, SUM(column2) OVER (ORDER BY column1) as RunningTotal FROM table;
24. Explain the RANK(), DENSE_RANK(), and ROW_NUMBER() functions.
• RANK(): Provides a rank to each row within the partition of a result set with gaps in
rank.
SQL Query
SELECT column1, RANK() OVER (ORDER BY column2 DESC) as rank FROM table;
• DENSE_RANK(): Similar to RANK() but without gaps in rank.
SQL Query
SELECT column1, DENSE_RANK() OVER (ORDER BY column2 DESC) as dense_rank FROM
table;
• ROW_NUMBER(): Assigns a unique sequential integer to rows.
SQL Query
SELECT column1, ROW_NUMBER() OVER (ORDER BY column2 DESC) as row_number FROM
table;
25. How can you optimize a SQL query for better performance?
• Use indexes appropriately.
• Avoid using SELECT *, specify columns.
• Optimize joins, subqueries, and aggregations.
• Analyze and rewrite complex queries.
• Use appropriate data types and normalize the database.
26. What are execution plans in SQL? How do you analyze them?
• Execution Plan: A visual representation of the data retrieval methods chosen by
the SQL query optimizer.
• Analyze using tools like EXPLAIN in MySQL, EXPLAIN PLAN in Oracle, or viewing the
graphical execution plan in SQL Server Management Studio (SSMS).
27. Explain the use of indexes in improving query performance.
• Indexes speed up data retrieval by providing quick access to rows in a table.
• They work like a book's index, allowing the database to find data without scanning
the entire table.
28. What is partitioning in SQL? How does it help in query optimization?
• Partitioning: Dividing a table into smaller, more manageable pieces.
• Improves performance by allowing queries to scan only relevant partitions instead
of the entire table.
29. How would you handle a situation where a query takes too long to execute?
• Analyze the execution plan.
• Optimize indexes and rewrite the query.
• Partition large tables.
• Use caching strategies.
• Increase hardware resources if necessary.
30. Provide a scenario where you used SQL to solve a complex business problem.
• For example, generating a detailed sales report for different regions by joining
sales and customer tables, using window functions to calculate running totals, and
optimizing performance with appropriate indexing.
SQL Query
SELECT c.CustomerName, p.ProductName, SUM(o.Quantity * p.Price) as TotalSpent FROM
Orders o JOIN Customers c ON o.CustomerID = c.CustomerID JOIN Products p ON
o.ProductID = p.ProductID GROUP BY c.CustomerName, p.ProductName;
2. Self-Join:
• Question: Using an Employees table, write a query to find all employees who have
the same manager.
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, ManagerID)
• Expected Query:
SQL Query
SELECT e1.EmployeeName as Employee, e2.EmployeeName as Manager FROM Employees
e1 JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID ORDER BY e2.EmployeeName,
e1.EmployeeName;
3. Using RANK() Function:
• Question: Write a query to find the top 3 highest-paid employees in each
department.
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, DepartmentID, Salary) --
Departments table Departments(DepartmentID, DepartmentName)
• Expected Query:
SQL Query
SELECT e.EmployeeName, d.DepartmentName, e.Salary, rnk.Rank FROM ( SELECT
EmployeeID, EmployeeName, DepartmentID, Salary, RANK() OVER (PARTITION BY
DepartmentID ORDER BY Salary DESC) as Rank FROM Employees ) e JOIN Departments d
ON e.DepartmentID = d.DepartmentID WHERE e.Rank <= 3 ORDER BY d.DepartmentName,
e.Rank;
4. Combining Multiple Concepts:
• Question: Write a query to find the average salary of employees, excluding the top
5 highest-paid employees in each department.
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, DepartmentID, Salary) --
Departments table Departments(DepartmentID, DepartmentName)
• Expected Query:
SQL Query
WITH RankedEmployees AS ( SELECT EmployeeID, DepartmentID, Salary, RANK() OVER
(PARTITION BY DepartmentID ORDER BY Salary DESC) as Rank FROM Employees ) SELECT
DepartmentID, AVG(Salary) as AverageSalary FROM RankedEmployees WHERE Rank > 5
GROUP BY DepartmentID;
5. Complex Joins and Aggregations:
• Question: Write a query to find each customer's most frequently ordered product.
Tables Structure:
-- Orders table Orders(OrderID, CustomerID, ProductID, Quantity, OrderDate) -- Customers
table Customers(CustomerID, CustomerName) -- Products table Products(ProductID,
ProductName)
• Expected Query:
SQL Query
WITH OrderFrequency AS ( SELECT CustomerID, ProductID, COUNT(*) as OrderCount,
RANK() OVER (PARTITION BY CustomerID ORDER BY COUNT(*) DESC) as Rank FROM Orders
GROUP BY CustomerID, ProductID ) SELECT c.CustomerName, p.ProductName,
of.OrderCount FROM OrderFrequency of JOIN Customers c ON of.CustomerID =
c.CustomerID JOIN Products p ON of.ProductID = p.ProductID WHERE of.Rank = 1 ORDER
BY c.CustomerName;
SQL Query
SELECT c.CategoryName, SUM(o.Quantity * p.Price) as TotalSales, COUNT(o.OrderID) as
NumberOfOrders FROM Orders o JOIN Products p ON o.ProductID = p.ProductID JOIN
Categories c ON p.CategoryID = c.CategoryID GROUP BY c.CategoryName;
7. Self-Join for Hierarchical Data:
• Question: Write a query to find the hierarchy of employees and their direct reports
(subordinates).
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, ManagerID)
• Expected Query:
SQL Query
SELECT e1.EmployeeName as Manager, e2.EmployeeName as Subordinate FROM
Employees e1 LEFT JOIN Employees e2 ON e1.EmployeeID = e2.ManagerID ORDER BY
e1.EmployeeName, e2.EmployeeName;
8. Using RANK() to Identify Trends:
• Question: Write a query to rank the monthly sales for each product and identify
the month with the highest sales for each product.
Tables Structure:
-- Orders table Orders(OrderID, ProductID, Quantity, OrderDate) -- Products table
Products(ProductID, ProductName, Price)
• Expected Query:
SQL Query
SELECT p.ProductName, DATE_FORMAT(o.OrderDate, '%Y-%m') as Month, SUM(o.Quantity
* p.Price) as MonthlySales, rnk.Rank FROM Orders o JOIN Products p ON o.ProductID =
p.ProductID GROUP BY p.ProductName, DATE_FORMAT(o.OrderDate, '%Y-%m') WITH
ROLLUP ) SELECT ProductName, Month, MonthlySales FROM ( SELECT ProductName,
Month, MonthlySales, RANK() OVER (PARTITION BY ProductName ORDER BY MonthlySales
DESC) as Rank FROM MonthlySales ) rnk WHERE rnk.Rank = 1 ORDER BY ProductName;
9. Combining Self-Join and Aggregation:
• Question: Write a query to find employees who earn more than the average salary
of their department.
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, DepartmentID, Salary)
• Expected Query:
SQL Query
SELECT e1.EmployeeName, e1.Salary, e1.DepartmentID FROM Employees e1 JOIN ( SELECT
DepartmentID, AVG(Salary) as AvgSalary FROM Employees GROUP BY DepartmentID ) e2
ON e1.DepartmentID = e2.DepartmentID WHERE e1.Salary > e2.AvgSalary ORDER BY
e1.DepartmentID, e1.Salary DESC;
10. Nested Aggregations and Self-Join:
• Question: Write a query to find the employee who has been with the company the
longest in each department.
Table Structure:
-- Employees table Employees(EmployeeID, EmployeeName, DepartmentID, HireDate) --
Departments table Departments(DepartmentID, DepartmentName)
• Expected Query:
SQL Query
SELECT e.EmployeeName, d.DepartmentName, e.HireDate FROM Employees e JOIN
Departments d ON e.DepartmentID = d.DepartmentID WHERE e.HireDate = ( SELECT
MIN(HireDate) FROM Employees e2 WHERE e2.DepartmentID = e.DepartmentID ) ORDER
BY d.DepartmentName, e.HireDate;
Explanation of Concepts
• Complex Aggregations with Joins: Combining data from multiple tables and performing
aggregate functions like SUM() and COUNT().
• Self-Join for Hierarchical Data: Using self-joins to explore hierarchical relationships within
the same table.
• RANK() Function for Trends: Using RANK() to identify patterns and trends within grouped
data.
• Nested Aggregations: Applying aggregations within subqueries to compare and filter
results.
• Combining Concepts: Integrating multiple advanced concepts, such as self-joins,
aggregations, and date functions, to solve complex queries.