Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Answer SQL Questions

Sql QnA

Uploaded by

sbsharma5190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Answer SQL Questions

Sql QnA

Uploaded by

sbsharma5190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1. Write a SQL query to find the second-highest salary from a table.

sql
Copy code
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;

2. How would you optimize a slow-running query?

 Analyze the query execution plan using EXPLAIN.


 Ensure appropriate indexing on columns used in JOIN, WHERE, ORDER BY, and GROUP BY.
 Rewrite queries to simplify joins and reduce complexity.
 Use partitioning, caching, and query optimization techniques like avoiding SELECT * and limiting the
result set.
 Adjust database configurations like memory allocation and cache sizes.

3. Explain the difference between JOIN types in SQL (INNER, LEFT, RIGHT, FULL).

 INNER JOIN: Returns only the matching rows between tables.


 LEFT JOIN: Returns all rows from the left table and matching rows from the right table. Non-matching
rows from the right table are filled with NULL.
 RIGHT JOIN: Returns all rows from the right table and matching rows from the left table. Non-
matching rows from the left table are filled with NULL.
 FULL JOIN: Returns all rows when there is a match in either left or right table. Non-matching rows
from both tables are filled with NULL.

4. Write a SQL query to retrieve duplicate records from a table.


sql
Copy code
SELECT Column1, Column2, COUNT(*)
FROM TableName
GROUP BY Column1, Column2
HAVING COUNT(*) > 1;

5. How do you ensure data accuracy and consistency in SQL queries?

 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.

6. Explain the difference between WHERE and HAVING clauses in SQL.

 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;

8. Write a SQL query to find the cumulative sum of a column.


sql
Copy code
SELECT Column1,
SUM(Column2) OVER (ORDER BY Column1) AS CumulativeSum
FROM TableName;

9. How would you handle NULL values in SQL?

 Use COALESCE to replace NULL with a specific value.


 Use IS NULL or IS NOT NULL to filter rows based on NULL values.
 Use aggregate functions like SUM or COUNT with care, as they ignore NULL by default.

10. What is a subquery? Provide an example.

 A subquery is a query nested inside another query.

sql
Copy code
SELECT EmployeeID, Name
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

11. How do you use window functions in SQL? Provide a scenario.

 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?

 Remove duplicates with DELETE or DISTINCT.


 Use TRIM functions to remove whitespace.
 Standardize data formats (e.g., date formats).
 Handle NULL values using COALESCE or by updating them with meaningful values.
 Use CASE statements to correct inconsistent data.

15. Write a SQL query to pivot data from rows to columns.


sql
Copy code
SELECT *
FROM (SELECT Year, Product, Sales FROM SalesData) AS SourceTable
PIVOT (
SUM(Sales)
FOR Product IN ([ProductA], [ProductB], [ProductC])
) AS PivotTable;

16. How would you approach querying large datasets?

 Use proper indexing.


 Partition large tables.
 Limit the dataset with WHERE clauses.
 Use batch processing for large operations.
 Consider query optimizations like avoiding SELECT *.

17. Explain the difference between UNION and UNION ALL in SQL.

 UNION: Combines results from two queries and removes duplicates.


 UNION ALL: Combines results from two queries and retains all duplicates.

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;

20. Explain how to use CASE statements in SQL.

 CASE allows you to perform conditional logic in SQL.


sql
Copy code
SELECT Name,
Salary,
CASE
WHEN Salary < 30000 THEN 'Low'
WHEN Salary BETWEEN 30000 AND 60000 THEN 'Medium'
ELSE 'High'
END AS SalaryRange
FROM Employees;

These answers cover a wide range of SQL concepts and practices, from basic queries to more advanced
techniques.

You might also like