Answer SQL Questions
Answer SQL Questions
sql
Copy code
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;
3. Explain the difference between JOIN types in SQL (INNER, LEFT, RIGHT, FULL).
Use constraints (primary keys, foreign keys, unique, check, and not null constraints).
Employ transactions to ensure atomic operations.
Validate data before insertion and use triggers for automatic enforcement of rules.
Normalize your database to eliminate redundancy and perform regular data audits.
WHERE: Filters rows before grouping and aggregation. Used with individual rows.
HAVING: Filters rows after grouping and aggregation. Used with aggregate functions.
7. How would you retrieve the top N records from a dataset in SQL?
sql
Copy code
SELECT *
FROM TableName
ORDER BY SomeColumn DESC
LIMIT N;
sql
Copy code
SELECT EmployeeID, Name
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Window functions perform calculations across a set of table rows related to the current row.
Scenario: Calculate the running total of sales per month.
sql
Copy code
SELECT Month,
Sales,
SUM(Sales) OVER (ORDER BY Month) AS RunningTotal
FROM SalesData;
12. Explain the concept of indexing and its impact on query performance.
Indexing: Creates a data structure that improves the speed of data retrieval operations.
Impact: Indexes make queries faster by allowing the database to locate rows more quickly. However,
they can slow down INSERT, UPDATE, and DELETE operations because indexes need to be maintained.
13. Write a SQL query to find employees who joined in the last year.
sql
Copy code
SELECT *
FROM Employees
WHERE JoinDate >= DATEADD(YEAR, -1, GETDATE());
14. How do you perform data cleaning in SQL?
17. Explain the difference between UNION and UNION ALL in SQL.
18. Write a SQL query to join three tables with common keys.
sql
Copy code
SELECT A.Column1, B.Column2, C.Column3
FROM TableA A
JOIN TableB B ON A.Key = B.Key
JOIN TableC C ON B.Key = C.Key;
19. How do you write a SQL query to calculate the moving average?
sql
Copy code
SELECT Date,
AVG(Value) OVER (ORDER BY Date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS
MovingAvg
FROM Data;
These answers cover a wide range of SQL concepts and practices, from basic queries to more advanced
techniques.