0% found this document useful (0 votes)
21 views6 pages

SQL query Q&A

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views6 pages

SQL query Q&A

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

1) Write a SQL query to get the second highest salary from the 'Employee` table.

SELECT MAX(Salary) AS SecondHighestSalary


FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);

2) Write a SQL query to get the Nth highest salary from the `Employee` table.

SELECT Salary
FROM Employee
ORDER BY Salary
DESC LIMIT N-1, 1;

3) Write a SQL query to rank the scores from highest to lowest.

SELECT Score, RANK()


OVER (ORDER BY Score DESC) AS Rank
FROM Scores;
4) Write a SQL query to find all numbers that appear consecutively at least three times.

SELECT DISTINCT Number


FROM (
SELECT Number,
LEAD(Number) OVER (ORDER BY id) AS next_number,
LEAD(Number,2) OVER (ORDER BY id) AS next_next_number
FROM YourTable -- Replace YourTable with the actual table name
) AS SubQuery
WHERE Number = next_number AND Number = next_next_number;

5) Write a SQL query to find employees who earn more than their managers.

SELECT e.Name AS EmployeeName


FROM Employee e
JOIN Employee m ON e.ManagerID = m.ID
WHERE e.Salary > m.Salary;

6) Write a SQL query to find all duplicate email addresses in the Person` table.

SELECT Email
FROM Person
GROUP BY Email
HAVING COUNT(Email) > 1;

7) Explain order of execution of SQL.


FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
8) What is difference between where and having?

WHERE filters records before grouping.


HAVING filters records after grouping.

9) What is the use of group by?

Groups rows that have the same values in specified columns into summary rows.

10) Explain all types of joins in SQL?

1) INNER JOIN: Returns records with matching values in both tables.


2) LEFT (OUTER) JOIN: Returns all records from the left table, and matched
records from the right table.
3) RIGHT (OUTER) JOIN: Returns all records from the right table, and matched
records from the left table.
4) FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table.
5) CROSS JOIN: Returns the Cartesian product of the sets of rows from the joined
tables.

11) What are triggers in SQL?

A trigger is a set of SQL statements that automatically "fires" when an event occurs in the
database.

12) What is stored procedure in SQL.

A stored procedure is a prepared SQL code that you can save and reuse.

13) Explain all types of window functions? (Mainly rank, row_num, dense_rank, lead & lag)

• RANK(): Assigns a unique rank to each distinct row.


• ROW_NUMBER(): Assigns a sequential integer to rows within a partition.
• DENSE_RANK(): Similar to RANK, but ranks without gaps.
• LEAD(): Provides access to a row at a given physical offset which follows the current
row.
• LAG(): Provides access to a row at a given physical offset which precedes the current
row.

14) What is the difference between TRUNCATE and DELETE?

• TRUNCATE removes all rows and resets table storage.


• DELETE removes rows one at a time and records an entry in the transaction log for
each deleted row.

15) What is difference between DML, DDL and DCL?


• DML (Data Manipulation Language) deals with data manipulation (INSERT,
UPDATE, DELETE).
• DDL (Data Definition Language) deals with schema and database structure
(CREATE, ALTER, DROP).
• DCL (Data Control Language) deals with rights, permissions, and other controls
(GRANT, REVOKE).

16) Which is faster between CTE and Subquery?

Generally, performance is similar. Specific scenarios might Favor one over the other
depending on the database system's optimization.

17) What are constraints and types of Constraints?

Ensure the accuracy and reliability of data in a database. Types include PRIMARY KEY,
FOREIGN KEY, UNIQUE, NOT NULL, and CHECK.

18) Different types of Operators?

Arithmetic, Comparison, Logical, etc.

19) Explain View concepts?

A view is a virtual table based on the result-set of an SQL statement.

20) Difference between char and Varchar?

CHAR is fixed-length, VARCHAR is variable-length.

21) What is an index? Explain its different types.

An index is used to speed up search queries. Types include Unique, Composite,


Clustered, Non-clustered.

22) Differentiate between UNION and UNION ALL.

UNION removes duplicate records, UNION ALL includes all duplicates.

23) How many types of clauses in SQL?

In SQL, there are several types of clauses that are commonly used to construct queries
and manipulate data. The major clauses include:
SELECT: Used to specify the columns to be retrieved.
FROM: Specifies the tables from which to retrieve data.
WHERE: Filters records that fulfill a specified condition.
GROUP BY: Groups rows sharing a property so that an aggregate function can be applied
to each group.
HAVING: Filters groups according to some condition (works like a WHERE clause but for
groups).
ORDER BY: Specifies the order in which to return the rows.
JOIN: Combines rows from two or more tables based on a related column between them.
LIMIT (or FETCH FIRST in some systems): Specifies the maximum number of records to
return.
UNION: Combines the result-set of two or more SELECT statements.
INTERSECT: Returns the common records from multiple SELECT statements.
EXCEPT: Returns records from the first SELECT statement that aren't output by the
second SELECT statement.
WITH: Often used to define Common Table Expressions (CTEs).
These clauses allow SQL to be very flexible and powerful in querying relational
databases.

24) What are the various types of relationships in SQL?

One-to-One, One-to-Many, and Many-to-Many.

25) Difference between Primary Key and Secondary Key?

Primary Key uniquely identifies each record, whereas Secondary Key is not the primary
means of identifying records but can still identify them.

26) Find the second highest salary of an employee?

SELECT MAX(Salary)
FROM Employees
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employees);

27) Difference between Function and Store procedure?

Functions must return a value and cannot modify database state. Stored procedures may
or may not return values and can modify the database.

28) How would you optimize a slow SQL query?

Use indexes, optimize joins, avoid SELECT *, reduce subqueries, etc.

29) How do you handle duplicate rows in a SQL query?

Use DISTINCT or group functions and GROUP BY to handle duplicates.

30) Write a SQL query to find the top 3 departments with the highest average salary.

SELECT DepartmentID, AVG(Salary) AS AverageSalary


FROM Employees
GROUP BY DepartmentID
ORDER BY AverageSalary DESC
LIMIT 3;

31) Write a SQL query to find the employees who have the same name and work in the same
department.
SELECT Name, DepartmentID
FROM Employees
GROUP BY Name, DepartmentID
HAVING COUNT(*) > 1;

32) Write a SQL query to find the departments with no employees.

SELECT DepartmentID
FROM Departments
WHERE DepartmentID NOT IN (SELECT DISTINCT DepartmentID FROM Employees);

33) How do you use indexing to improve SQL query performance?

Create indexes on columns that are frequently used in WHERE clauses, JOIN conditions,
or as part of an ORDER BY.

34) Write a SQL query to find the employees who have worked for more than 5 years.

SELECT EmployeeID, Name


FROM Employees
WHERE DATEDIFF(year, HireDate, GETDATE()) > 5;

35) What is the difference between SUBQUERY and JOIN?

Subqueries can be used when the output of one query is needed in another. Joins are
used to combine rows from two or more tables.

36) Write a SQL query to find the top 2 products with the highest sales.

SELECT ProductID, SUM(Sales) AS TotalSales


FROM Sales
GROUP BY ProductID
ORDER BY TotalSales DESC
LIMIT 2;

37) How do you use stored procedures to improve SQL query performance?

Precompile complex queries and reuse them, encapsulate logic to maintain consistency.

38) Write a SQL query to find the customers who have placed an order but have not made a
payment.

SELECT CustomerID
FROM Orders
WHERE PaymentDone = 'No';

39) Write a SQL query to find the employees who work in the same department as their
manager.

SELECT e.EmployeeID
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID
WHERE e.ManagerID = d.ManagerID;

40) How do you use window functions to solve complex queries?

Utilize OVER() with PARTITION BY, ORDER BY clauses to perform complex, grouped
calculations over a set of rows.

41) Write a SQL query to find the top 3 products with the highest average price.

SELECT ProductID, AVG(Price) AS AveragePrice


FROM Products
GROUP BY ProductID
ORDER BY AveragePrice DESC
LIMIT 3;

42) Write a SQL query to find the employees who have not taken any leave in the last 6
months.

SELECT EmployeeID, Name


FROM Employees
WHERE EmployeeID NOT IN (SELECT DISTINCT EmployeeID FROM Leaves WHERE
LeaveDate >= DATEADD(month, -6, GETDATE()));

You might also like