0% found this document useful (0 votes)
5 views17 pages

SQL Interview Questions

The document contains a series of SQL-related questions and answers, covering topics such as stored procedures, joins, aggregation, and error handling. Each question is followed by a concise answer, often including SQL code examples. The content is structured to provide a comprehensive overview of SQL concepts and practices.

Uploaded by

Somen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

SQL Interview Questions

The document contains a series of SQL-related questions and answers, covering topics such as stored procedures, joins, aggregation, and error handling. Each question is followed by a concise answer, often including SQL code examples. The content is structured to provide a comprehensive overview of SQL concepts and practices.

Uploaded by

Somen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​ iche diye gaye content ko clean kar diya gaya hai.

Saare # tags aur formatting symbols hata​


N
​diye gaye hain, lekin content aur sawalon ki sankhya (50) bilkul wahi hai.​

​1. What is a stored procedure? Write a simple example.​


​ nswer:​​A stored procedure is a pre‑compiled SQL code​​block that can accept parameters​
A
​and perform complex operations. It improves reusability and security.​

​SQL​

​CREATE​​PROCEDURE​​GetEmployee​
​ EmpId​​INT​
@
​AS​
​BEGIN​
​SELECT​​*​​FROM​​Employees​​WHERE​​Id​​=​​@EmpId​​;​
​END​​;​

​2. How do you pass parameters to a stored procedure?​


​ nswer:​​Parameters are defined after the procedure​​name and can be given default values.​
A
​Use NULLIF to handle empty strings.​

​SQL​

​CREATE​​PROCEDURE​​GetOrders​
​@FromDate​​DATE​​=​​NULL​
​ S​
A
​BEGIN​
​SET​​@FromDate​​=​​NULLIF​​(​@FromDate​​,​​''​​);​
​SELECT​​*​​FROM​​Orders​​WHERE​​OrderDate​​>=​​@FromDate​​OR​​@FromDate​​IS​​NULL​​;​
​END​​;​
​3. Explain LEFT JOIN with an example.​
​ nswer:​​LEFT JOIN returns all rows from the left table​​and matching rows from the right table.​
A
​If no match, right side columns are NULL.​

​SQL​

​SELECT​​[Link], [Link]​
​FROM​​Employees E​
​LEFT​​JOIN​​Orders O​​ON​​[Link]​​=​​[Link];​

​ . What is the difference between INNER JOIN and​


4
​LEFT JOIN?​
​ nswer:​​INNER JOIN returns only rows with matches​​in both tables. LEFT JOIN returns all left​
A
​table rows even if no match on the right.​

​ . How do you remove duplicate rows from a result​


5
​set?​
​Answer:​​Use DISTINCT or GROUP BY with appropriate​​aggregation.​

​SQL​

​SELECT​​DISTINCT​​EmpId, ClientId​​FROM​​FeedLog;​

​6. Explain GROUP BY with an example.​


​ nswer:​​GROUP BY groups rows that have the same values​​in specified columns, allowing​
A
​aggregation on other columns.​
​SQL​

​SELECT​​EmpId,​​COUNT​​(​*​)​​AS​​VisitCount​
​FROM​​FeedLog​
​GROUP​​BY​​EmpId;​

​7. What is the error Msg 8120 and how to fix it?​
​ nswer:​​It occurs when a column in SELECT is not part​​of GROUP BY and not aggregated. Fix​
A
​by adding the column to GROUP BY or using an aggregate function.​

​SQL​

-​ - Wrong​
​SELECT​​EmpId, ActivityDate,​​COUNT​​(​*​)​
​FROM​​FeedLog​
​GROUP​​BY​​EmpId;​

-​ - Fix: add ActivityDate to GROUP BY​


​SELECT​​EmpId, ActivityDate,​​COUNT​​(​*​)​
​FROM​​FeedLog​
​GROUP​​BY​​EmpId, ActivityDate;​

​ . How do you calculate the week number of the​


8
​month (not from January)?​
​Answer:​​Use (DAY(date) - 1) / 7 + 1. This resets every​​month.​

​SQL​
​SELECT​​((​​DAY​​(OrderDate)​​-​​1​)​​/​​7​​+​​1​)​​AS​​WeekNo​
​FROM​​Orders;​

​ . Write a query to get the last visit date for each​


9
​outlet.​
​Answer:​​Use MAX(ActivityDate) grouped by outlet and​​employee.​

​SQL​

​SELECT​​EmpId, ClientId,​​MAX​​(ActivityDate)​​AS​​LastVisit​
​FROM​​FeedLog​
​WHERE​​FeedType​​NOT​​IN​​(​'Leave'​​)​
​GROUP​​BY​​EmpId, ClientId;​

​10. What is a subquery? Give an example.​


​ nswer:​​A subquery is a query inside another query.​​It can be used in SELECT, FROM, or​
A
​WHERE clauses.​

​SQL​

​SELECT​​Name​​FROM​​Employees​
​WHERE​​EmpId​​IN​​(​SELECT​​EmpId​​FROM​​Orders​​WHERE​​Amount​​>​​1000​​);​

1​ 1. How do you convert PCS to Units when 5 PCS = 1​


​Unit?​
​Answer:​​Use a CASE expression.​

​SQL​

​SELECT​​Qty,​
​CASE​​WHEN​​UOM​​=​​'PCS'​​THEN​​Qty​​/​​5.0​​ELSE​​Qty​​END​​AS​​Units​
​FROM​​OrderDetails;​

​12. What is a window function? Show an example.​


​ nswer:​​Window functions perform calculations across​​a set of rows related to the current​
A
​row without collapsing them. Example: SUM(...) OVER (PARTITION BY ...).​

​SQL​

​SELECT​​OrderNo, ProductName, Qty,​


​SUM​​(Qty)​​OVER​​(​PARTITION​​BY​​OrderNo)​​AS​​TotalQtyPerOrder​
​FROM​​OrderDetails;​

​13. How do you calculate Month‑to‑Date (MTD) filter?​


​Answer:​​Use DATEFROMPARTS to get the first day of​​the month of the end date.​

​SQL​

​WHERE​​ActivityDate​​>=​​DATEFROMPARTS(​​YEAR​​(​@ToDate​​),​​MONTH​​(​@ToDate​​),​​1​)​
​AND​​ActivityDate​​<​​DATEADD(​​DAY​​,​​1​,​​@ToDate​​);​
​14. What is the purpose of NULLIF? Give an example.​
​ nswer:​​NULLIF returns NULL if the two expressions​​are equal; otherwise returns the first​
A
​expression. Useful to treat empty strings as NULL.​

​SQL​

​SET​​@FromDate​​=​​NULLIF​​(​@FromDate​​,​​''​​);​

​15. How do you handle division by zero in SQL?​


​Answer:​​Use NULLIF on the denominator.​

​SQL​

​SELECT​​OrderQty​​*​​1.0​​/​​NULLIF​​(PC,​​0​)​​AS​​AvgQty​
​FROM​​Performance;​

1​ 6. Write a query to show only rows where an outlet​


​had at least one visit (TC > 0) and show order metrics,​
​otherwise show 0.​
​Answer:​​Use CASE WHEN.​

​SQL​

​SELECT​​OutletId,​
​CASE​​WHEN​​TotalVisits​​>​​0​​THEN​​OrderQty​​ELSE​​0​​END​​AS​​Qty​
​FROM​​...​
1​ 7. How do you join a subquery that aggregates​
​employee performance?​
​Answer:​​Write the subquery, give it an alias, and​​join on EmpId.​

​SQL​

​LEFT​​JOIN​​(​
​SELECT​​EmpId,​​MAX​​(OrderQty)​​AS​​OrderQty​
​FROM​​EmployeeWorkPerformance​
​GROUP​​BY​​EmpId​
​) EWP​​ON​​[Link]​​=​​[Link]​

1​ 8. What is the difference between COUNT(*) and​


​COUNT(column)?​
​ nswer:​​COUNT(*) counts all rows including NULLs.​​COUNT(column) counts only non‑NULL​
A
​values in that column.​

1​ 9. How do you get the latest CheckOut date per​


​outlet (only within current month)?​
​Answer:​​Use MAX with a CASE inside the aggregate and​​MTD date filter.​

​SQL​

​SELECT​​EmpId, ClientId,​
​MAX​​(​CASE​​WHEN​​FeedType​​=​​'CheckOut'​​THEN​​ActivityDate​​END​​)​​AS​​LastProductiveVisit​
​FROM​​FeedLog​
​WHERE​​ActivityDate​​>=​​DATEFROMPARTS(​​YEAR​​(GETDATE()),​​MONTH​​(GETDATE()),​​1​)​
​GROUP​​BY​​EmpId, ClientId;​

​20. Explain the OVER(PARTITION BY ...) clause.​


​ nswer:​​It divides the result set into partitions​​and performs a calculation within each partition,​
A
​without grouping the rows.​

​SQL​

​SELECT​​OrderNo, ProductId, Qty,​


​SUM​​(Qty)​​OVER​​(​PARTITION​​BY​​OrderNo)​​AS​​OrderTotalQty​
​FROM​​OrderDetails;​

​ 1. How would you avoid duplicate rows when joining​


2
​a table that has multiple rows per key?​
​ nswer:​​Either aggregate the table before joining,​​or use DISTINCT on the join condition, or use​
A
​a window function with ROW_NUMBER() to pick one row.​

​SQL​

​LEFT​​JOIN​​(​
​SELECT​​EmpId, ClientId,​​MAX​​(ActivityDate)​​AS​​LastVisit​
​FROM​​FeedLog​
​GROUP​​BY​​EmpId, ClientId​
​) LV​​ON​​...​

​22. Write a query to count the number of CheckOut​


​and Unit type items separately per order.​
​Answer:​​Use conditional aggregation.​

​SQL​

​SELECT​​OrderId,​
​SUM​​(​CASE​​WHEN​​UOM​​=​​'PCS'​​THEN​​Qty​​END​​)​​AS​​TotalPCS,​
​SUM​​(​CASE​​WHEN​​UOM​​=​​'Unit'​​THEN​​Qty​​END​​)​​AS​​TotalUnits​
​FROM​​OrderDetails​
​GROUP​​BY​​OrderId;​

​ 3. What is the purpose of SET NOCOUNT ON in a​


2
​stored procedure?​
​ nswer:​​It prevents SQL Server from sending the “(X​​rows affected)” message after each DML​
A
​statement, which improves performance and reduces network traffic.​

​ 4. How do you handle an optional @EmpId parameter​


2
​that can be a manager (show subordinates)?​
​Answer:​​Use an EXISTS subquery on a subordinate table.​

​SQL​

​WHERE​​(​@EmpId​​IS​​NULL​​OR​​EmpId​​=​​@EmpId​
​OR​​EXISTS​​(​SELECT​​1​​FROM​​Subordinate S​​WHERE​​[Link]​​=​​EmpId​​AND​​[Link]​​=​
​@EmpId​​))​

​25. Write a query to find the week number of a date​


​using ISO standard.​
​Answer:​​Use DATEPART(ISO_WEEK, date).​

​SQL​

​SELECT​​DATEPART(ISO_WEEK, OrderDate)​​AS​​IsoWeekNo​
​FROM​​Orders;​

​ 6. How do you convert an empty string to NULL in a​


2
​parameter?​
​Answer:​​Use SET @Param = NULLIF(@Param, '').​

​27. Explain the difference between MAX and SUM.​


​ nswer:​​MAX returns the highest value in a group;​​SUM adds all values. Use MAX for a single​
A
​value (like last visit date) and SUM for totals.​

​ 8. Write a query that shows total units (5 PCS = 1​


2
​Unit) per order without using GROUP BY.​
​Answer:​​Use a window function.​

​SQL​

​SELECT​​OrderId, ProductId, Qty, UOM,​


​SUM​​(​CASE​​WHEN​​UOM​​=​​'PCS'​​THEN​​Qty​​/​​5.0​​ELSE​​Qty​​END​​)​​OVER​​(​PARTITION​​BY​​OrderId)​​AS​
​OrderUnits​
​FROM​​OrderDetails;​
​29. What is a derived table? Give an example.​
​Answer:​​A derived table is a subquery used in the​​FROM clause. It must have an alias.​

​SQL​

​SELECT​​*​​FROM​​(​SELECT​​EmpId,​​COUNT​​(​*​)​​AS​​Visits​​FROM​​FeedLog​​GROUP​​BY​​EmpId)​​AS​​Derived​
​WHERE​​Visits​​>​​10​​;​

​ 0. How do you prevent a “division by zero” error​


3
​when calculating average?​
​Answer:​​Use NULLIF(PC, 0).​

​SQL​

​SELECT​​OrderQty​​*​​1.0​​/​​NULLIF​​(PC,​​0​)​​AS​​AvgQty​
​FROM​​Performance;​

​ 1. Write a query that returns the latest activity for​


3
​each outlet, but only if it’s a CheckOut.​
​Answer:​​Use conditional aggregation.​

​SQL​

​SELECT​​EmpId, ClientId,​
​MAX​​(​CASE​​WHEN​​FeedType​​=​​'CheckOut'​​THEN​​ActivityDate​​END​​)​​AS​​LastCheckOut​
​FROM​​FeedLog​
​GROUP​​BY​​EmpId, ClientId;​

​32. Explain the use of CAST in date filtering.​


​Answer:​​CAST converts a datetime to date for comparison.​

​SQL​

​WHERE​​CAST​​(CreatedDate​​AS​​DATE​​)​​>=​​@FromDate​

​33. What is the purpose of CONCAT in SQL?​


​Answer:​​It joins two or more strings together.​

​SQL​

​SELECT​​CONCAT(Lat,​​','​​, Lng)​​AS​​Location​​FROM​​Outlets;​

​ 4. How do you create a stored procedure that​


3
​accepts a date range and returns orders in that​
​period?​
​Answer:​

​SQL​
​CREATE​​PROCEDURE​​GetOrdersByDate​
​@FromDate​​DATE​​,​​@ToDate​​DATE​
​ S​
A
​BEGIN​
​SELECT​​*​​FROM​​Orders​
​WHERE​​OrderDate​​BETWEEN​​@FromDate​​AND​​@ToDate​​;​
​END​​;​

​ 5. Write a query to find the total number of distinct​


3
​products sold per employee.​
​Answer:​​Use SUM(UniqueProducts) from the performance​​table grouped by employee.​

​SQL​

​SELECT​​EmpId,​​SUM​​(UniqueProducts)​​AS​​TotalDistinctProducts​
​FROM​​EmployeeWorkPerformance​
​GROUP​​BY​​EmpId;​

​ 6. What is the difference between WHERE and​


3
​HAVING?​
​Answer:​​WHERE filters rows before aggregation; HAVING​​filters groups after aggregation.​

​ 7. How do you write a case‑insensitive search in SQL​


3
​Server?​
​ nswer:​​By default SQL Server is case‑insensitive​​unless using a binary collation. But you can​
A
​use UPPER() or LOWER().​
​SQL​

​SELECT​​*​​FROM​​Products​​WHERE​​UPPER​​(Name)​​=​​'T-SHIRT'​​;​

​ 8. What is the purpose of the _deleted column seen​


3
​in many tables?​
​ nswer:​​It is a soft‑delete flag. _deleted = 0 means​​active; _deleted = 1 means deleted. Queries​
A
​usually filter WHERE _deleted = 0.​

​ 9. Write a query that shows orders and their line​


3
​items, but only for orders that have at least one PCS​
​item.​
​Answer:​​Use EXISTS.​

​SQL​

​SELECT​​*​​FROM​​Orders O​
​WHERE​​EXISTS​​(​SELECT​​1​​FROM​​OrderDetails OD​​WHERE​​[Link]​​=​​[Link]​​AND​​[Link]​​=​​'PCS'​​);​

​ 0. How do you calculate the total time an employee​


4
​spent in the market? (If stored in minutes)​
​Answer:​​Use SUM(TotalTimeSpentInMarket) grouped by​​employee.​

​41. What is a self‑join? Give an example.​


​Answer:​​A self‑join is when a table is joined with​​itself. Example: finding employees under a​
​manager.​

​SQL​

​SELECT​​[Link]​​AS​​Employee, [Link]​​AS​​Manager​
​FROM​​Employees E1​
​LEFT​​JOIN​​Employees E2​​ON​​[Link]​​=​​[Link];​

​ 2. How would you modify a stored procedure to​


4
​include a new column without breaking existing code?​
​ nswer:​​Use ALTER PROCEDURE and add the new column​​at the end of the SELECT list. Avoid​
A
​reordering existing columns.​

​ 3. Write a query to get the second latest CheckOut​


4
​date for each outlet.​
​Answer:​​Use a window function ROW_NUMBER().​

​SQL​

​WITH​​Ranked​​AS​​(​
​SELECT​​EmpId, ClientId, ActivityDate,​
​ROW_NUMBER​​()​​OVER​​(​PARTITION​​BY​​EmpId,​​ClientId​​ORDER​​BY​​ActivityDate​​DESC​​)​​AS​​rn​
​FROM​​FeedLog​​WHERE​​FeedType​​=​​'CheckOut'​
​)​
​SELECT​​*​​FROM​​Ranked​​WHERE​​rn​​=​​2​;​

​44. Explain the difference between VARCHAR and​


​NVARCHAR.​
​ nswer:​​VARCHAR stores non‑Unicode (1 byte per character);​​NVARCHAR stores Unicode (2​
A
​bytes per character) and supports all languages.​

​45. What is an index? Why is it important for joins?​


​ nswer:​​An index speeds up data retrieval. For joins,​​indexes on join columns (like EmpId,​
A
​ClientId) can dramatically improve performance.​

​ 6. Write a query that shows each employee and the​


4
​number of outlets they visited, even if zero.​
​Answer:​​Left join the outlet master with feed log​​counts.​

​SQL​

​SELECT​​[Link],​​COUNT​​(​DISTINCT​​[Link])​​AS​​OutletsVisited​
​FROM​​Employees E​
​LEFT​​JOIN​​FeedLog F​​ON​​[Link]​​=​​[Link]​​AND​​[Link]​​NOT​​IN​​(​'Leave'​​)​
​GROUP​​BY​​[Link];​

​47. How do you debug a stored procedure?​


​ nswer:​​Use PRINT statements, run it with sample parameters,​​check intermediate results by​
A
​selecting from subqueries, and use SQL Server Profiler.​

​ 8. Write a query to find orders where the total​


4
​quantity in units (5 PCS = 1 Unit) is greater than 10.​
​Answer:​
​SQL​

​SELECT​​OrderId,​​SUM​​(​CASE​​WHEN​​UOM​​=​​'PCS'​​THEN​​Qty​​/​​5.0​​ELSE​​Qty​​END​​)​​AS​​TotalUnits​
​FROM​​OrderDetails​
​GROUP​​BY​​OrderId​
​HAVING​​SUM​​(​CASE​​WHEN​​UOM​​=​​'PCS'​​THEN​​Qty​​/​​5.0​​ELSE​​Qty​​END​​)​​>​​10​​;​

​ 9. What is the purpose of BEGIN TRANSACTION and​


4
​COMMIT?​
​ nswer:​​They define a transaction – a group of SQL​​statements that are executed as a single​
A
​unit. If an error occurs, you can ROLLBACK to undo all changes.​

​ 0. How would you explain the entire​


5
​USP_GetEmployeeOutletEfficiency stored procedure​
​to a non‑technical manager?​
​Answer:​

“​ This procedure creates a report that shows, for each outlet, how many times an employee​
​visited, how many of those visits were productive (ended with a CheckOut), the last time they​
​visited, and the last time they had a CheckOut. It also shows order‑related totals (quantity,​
​value, unique products) – but those numbers are for the whole employee, not per outlet. If an​
​outlet had no visits, we show zero for order metrics. The report can be run for a single​
​employee or a manager to see their whole team.”​

You might also like