0% found this document useful (0 votes)
3 views28 pages

SQL Interview Questions and Answers Final PDF

This document contains a comprehensive list of SQL interview questions and answers covering various topics such as SQL clauses, joins, indexing, normalization, transactions, and functions. It provides clear definitions and differences between key SQL concepts, along with practical examples and explanations. The content is structured to assist candidates in preparing for SQL-related interviews.

Uploaded by

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

SQL Interview Questions and Answers Final PDF

This document contains a comprehensive list of SQL interview questions and answers covering various topics such as SQL clauses, joins, indexing, normalization, transactions, and functions. It provides clear definitions and differences between key SQL concepts, along with practical examples and explanations. The content is structured to assist candidates in preparing for SQL-related interviews.

Uploaded by

Shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

SQL Interview Questions and Answers

1. What is the difference between WHERE and HAVING clause?

 WHERE: Filters rows before grouping. Used with SELECT, UPDATE, DELETE.
 HAVING: Filters groups after aggregation. Used with GROUP BY.

2. What are the different types of JOINs in SQL?

 INNER JOIN : Returns rows with matching keys in both tables.


 LEFT JOIN : All rows from the left, matched rows from right (NULL if no match).
 RIGHT JOIN : All rows from right, matched rows from left.
 FULL OUTER JOIN : All rows from both, with NULLs where there is no match.
 SELF JOIN : A table joined with itself.

3. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?


Used for row numbering in result sets:

 ROW_NUMBER(): Unique number for each row.


 RANK(): Skips numbers for duplicates.
 DENSE_RANK(): No gaps in ranking.
4. What are indexes? What types are there?
Indexes speed up search queries.

Types:

 Clustered Index: Alters physical order (1 per table)


 Non-Clustered Index: Logical pointer to data (many per table)
 Unique Index: Enforces uniqueness
 Composite Index: Multiple columns

5. What is the difference between DELETE, TRUNCATE, and DROP?

Operation Deletes Rows? Rollback? Affects Schema?


DELETE Yes (with WHERE) Yes No
TRUNCATE Yes (all rows) No (can vary) No
DROP Entire table No Yes

6. What is a subquery? Types?


A query inside another query. Types:

 Single-row subquery
 Multi-row subquery (IN, ANY, ALL)
 Correlated subquery: Uses outer query column.
7. What is normalization? Explain 1NF to 3NF.
Normalization organizes data to remove redundancy.

 1NF: Atomic values only.


 2NF: 1NF + no partial dependency (whole key).
 3NF: 2NF + no transitive dependency (non-key depending on non-key).

8. What is a primary key vs foreign key?

 Primary Key: Uniquely identifies rows; no NULLs.


 Foreign Key: Points to primary key in another table; ensures referential integrity.

9. What are aggregate functions in SQL?


Functions that perform calculations on multiple rows:

 SUM(), COUNT(), AVG(), MIN(), MAX()


10. What is the difference between IN and EXISTS?

 IN: Compares a column with a list of values.


 EXISTS: Checks if the subquery returns any row (more efficient with large datasets).

11. What is a view? What are its pros and cons?


A virtual table based on a query.

✅ Pros:

 Simplifies complex queries


 Adds security (column-level access)

❌ Cons:

 Cannot always update data directly


 Slower for complex views
12. How do you retrieve the second highest salary?

13. What is a transaction? Explain ACID properties.


Transaction: Logical unit of work.

ACID:

 Atomicity: All or nothing


 Consistency: DB remains valid state
 Isolation: No interference between transactions
 Durability: Changes persist after commit

14. What is the difference between UNION and UNION ALL?

 UNION: Removes duplicates


 UNION ALL: Includes duplicates, better performance

15. What is the use of CASE in SQL?

Conditional logic like if-else.


16. How do you update rows based on a join?

17. What are stored procedures?


Precompiled SQL code stored in the DB.

18. What is the difference between ISNULL() and COALESCE()?

 ISNULL(a, b): Returns b if a is NULL


 COALESCE(a, b, c): Returns the first non-null value in the list
19. How do you identify duplicate rows in a table?

20. What is a common table expression (CTE)?


A temporary result set defined using WITH.

21. What is a trigger in SQL?

A trigger is a stored procedure that automatically runs in response to certain events on a table
22. What is the difference between INNER JOIN and OUTER JOIN?

 INNER JOIN: Returns only matching rows.


 LEFT OUTER JOIN: All rows from left + matching rows from right.
 RIGHT OUTER JOIN: All rows from right + matching from left.
 FULL OUTER JOIN: All rows from both tables with NULLs where no match.

23. What is a composite key?


A composite key is a primary key made of two or more columns that together uniquely
identify each row.

24. What is a correlated subquery?


A subquery that uses values from the outer query and runs once per row.

25. What is indexing and when should you avoid it?


Indexing improves query speed, but:

❌ Avoid indexing:
 Small tables
 Columns with frequent INSERT/UPDATE
 Columns with low cardinality (e.g., gender)

26. What is the difference between CHAR and VARCHAR?

 CHAR(n): Fixed length


 VARCHAR(n): Variable length
Use CHAR when values are uniform (e.g., country code), otherwise prefer VARCHAR.

27. What is the purpose of GROUP BY clause?


It groups rows that have the same values in specified columns and allows aggregate functions to
work on these groups.

28. What is a window function in SQL?


Performs calculations across a set of rows related to the current row, without collapsing rows
like GROUP BY.
29. How do you handle NULL values in SQL?

Use:

 IS NULL, IS NOT NULL for filtering


 ISNULL() or COALESCE() to replace NULLs
 NULLIF() to return NULL if values are equal

30. What is the difference between TEMP and TABLE VARIABLE?

Feature Temporary Table (#temp) Table Variable (@table)


Scope Connection Batch/Stored Procedure
Transaction Participates Limited
Indexing Yes Limited
Performance Better for large data Better for small data

31. How do you identify and delete duplicate rows in SQL?

32. What is normalization vs denormalization?

 Normalization: Reduces redundancy (splits data into multiple tables)


 Denormalization: Combines tables to improve read performance (at the cost of
redundancy)

33. What are user-defined functions (UDFs) in SQL?

Reusable blocks that return values or tables.


34. How do you convert rows to columns (pivot) in SQL?
Using PIVOT:

35. What is a schema in SQL?


A schema is a logical container for objects (tables, views, procedures).
It helps in organizing and securing database objects.

36. What is the use of MERGE statement?


Combines INSERT, UPDATE, and DELETE into one.

37. What is the difference between CAST() and CONVERT()?


Both convert data types:

 CAST() is ANSI standard.


 CONVERT() is SQL Server-specific and supports formatting.

38. What are constraints in SQL?


Rules to enforce data integrity:

 PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, DEFAULT, NOT NULL

39. What is an execution plan?


A graphical/textual representation of how SQL Server executes a query.
It helps with performance tuning and identifying bottlenecks.

View using:

Or click "Display Estimated Execution Plan" in SSMS.

40. How do you optimize slow SQL queries?

 Create indexes
 Avoid SELECT *
 Use joins efficiently
 Minimize subqueries
 Avoid functions on indexed columns
 Analyze execution plan
 Limit rows using TOP, OFFSET-FETCH

41. What is the use of DISTINCT in SQL?


DISTINCT removes duplicate rows from the result set.

42. What is the difference between COUNT(*) and COUNT(column_name)?

 COUNT(*): Counts all rows, including rows with NULLs.


 COUNT(column): Counts non-null values only in the specified column.

43. What are the types of relationships in SQL?

 One-to-One
 One-to-Many (most common)
 Many-to-Many (requires a junction table)

44. What is a surrogate key?


An artificial, system-generated unique identifier (e.g., auto-incrementing ID) used as a primary
key when no natural key exists.

45. What is a natural key?


A column or group of columns that naturally identifies a record (e.g., SSN, email address).
46. What is a covering index?
An index that includes all columns required by a query, so the database engine doesn’t need to
access the table (avoids key lookup).

47. How do you find the nth highest salary in SQL?


Using ROW_NUMBER() or DENSE_RANK():

48. What is the difference between TRUNCATE and DELETE with no WHERE?

Feature DELETE TRUNCATE


Logging Fully logged Minimal logging
Rollback Yes Yes (in most modern DBs)
Identity reset No Yes
Triggers fire Yes No

49. What is a non-repeatable read?


Occurs when a row is read twice during a transaction and the values differ due to another
transaction modifying it in between.

Prevention: Use REPEATABLE READ or higher isolation level.


50. What is phantom read?
Occurs when new rows are added by another transaction after the current transaction has read a
set of rows using a condition.

Fix: Use SERIALIZABLE isolation level.

51. What is a deadlock? How to prevent it?


Two transactions hold locks on resources and wait for each other to release them.

✅ Prevention:

 Always access tables in the same order


 Keep transactions short
 Use appropriate isolation level

52. What is a clustered index seek vs. clustered index scan?

 Seek: Efficient, directly locates rows


 Scan: Reads all rows (less efficient)

Use indexing to convert scans to seeks when possible.

53. What is the difference between REPLACE() and STUFF() in SQL Server?

 REPLACE(): Replaces all occurrences of a substring.


 STUFF(): Deletes and inserts string at a specified position.

54. What is an identity column?


Auto-incrementing column typically used as a surrogate primary key.
55. What is a rollback? When is it used?
Reverts changes made in a transaction before it is committed.

56. How do you check the execution time of a query?


SQL Server:

Or use Execution Plan in SSMS.

57. What is the OFFSET-FETCH clause used for?


Used for pagination of results.

58. What is NOLOCK and why is it risky?


WITH (NOLOCK) allows reading uncommitted data (dirty reads) — may return incorrect data.

59. What is the difference between TEMP TABLE and CTE?

Feature TEMP TABLE CTE


Scope Session/Connection Single query/block
Indexing Yes No
Reusable Yes No (unless recursive)
Performance Better for large sets Better for readable logic

60. How do you find all tables that contain a specific column in SQL Server?

61. What is ISNULL() vs COALESCE()? Which is better?

 ISNULL(expr1, expr2) → returns expr2 if expr1 is NULL


 COALESCE(expr1, expr2, ..., exprN) → returns first non-NULL from the list

📌 Difference:

 COALESCE supports multiple values


 COALESCE is ANSI standard; ISNULL is SQL Server-specific
 Data type precedence is better handled by COALESCE
62. What are the isolation levels in SQL Server?
Defines how transaction integrity is maintained.

Isolation Level Description Prevents


Read Uncommitted Dirty reads allowed Nothing
Read Committed Reads only committed data Dirty reads
Repeatable Read Locks rows to prevent changes Dirty + Nonrepeatable reads
Serializable Full locks on rows & ranges All above + Phantom
Snapshot Uses row versions (no blocking) All above

63. What is the difference between EXISTS and IN?

 IN: Best when subquery returns small set of static values


 EXISTS: Better with correlated subqueries and large datasets

64. How to get current date/time in SQL Server?

 GETDATE() – current date and time


 SYSDATETIME() – higher precision
 CURRENT_TIMESTAMP – ANSI equivalent of GETDATE()

65. How do you handle division by zero in SQL?


Use NULLIF() to prevent error:

If quantity is 0, NULLIF(quantity, 0) becomes NULL → no divide-by-zero error.

66. What is a scalar function vs table-valued function?

 Scalar Function: Returns a single value


 Table-Valued Function (TVF): Returns a result set (table)

67. What is a CROSS JOIN?


Returns a Cartesian product – each row of table A is combined with every row of table B.
68. What is the difference between UNION and JOIN?

 UNION: Combines rows from multiple result sets vertically (same structure)
 JOIN: Combines rows horizontally based on relationships

69. How to list all indexes on a table in SQL Server?

70. What is a recursive CTE?


A CTE that references itself to handle hierarchical data.
71. What are the advantages of stored procedures?

 Precompiled → faster performance


 Promotes code reuse
 Reduces SQL injection risks
 Centralized logic
 Parameterization

72. What is a binary tree or adjacency list in SQL?


Used to represent hierarchical data like categories, org charts.
Each record points to its parent.

73. How do you get the total number of rows in a table?

Or faster (approximate) using system views:

74. What is a candidate key?


Any column (or combo) that uniquely identifies a row.
Every table can have multiple candidate keys.
The primary key is chosen from among them.
75. How to remove duplicates while inserting?
Use NOT EXISTS or MERGE.

76. What is the use of FOR XML PATH in SQL Server?


Converts SQL result to XML format (or helps with string aggregation).

77. What is the use of OPENQUERY in SQL Server?


Used to execute a query on a linked server.

78. How to find the size of a table in SQL Server?


79. What is the difference between DELETE CASCADE and DELETE SET NULL?

 CASCADE: Deletes child rows when parent is deleted


 SET NULL: Sets foreign key column to NULL when parent is deleted

80. How to rename a table or column in SQL Server?

81. How do you update data in one table based on another table?

82. What is a filtered index?

An index created on a subset of rows using a WHERE clause.


83. How to disable or enable constraints in SQL Server?

You can also disable a specific constraint by name.

84. What is the use of ROLLUP in SQL?


Used with GROUP BY to get subtotals and grand totals.

85. What is the difference between SCOPE_IDENTITY() and @@IDENTITY?

 SCOPE_IDENTITY(): Returns the last identity value in the current scope


 @@IDENTITY: Returns last identity across all scopes (may include triggers)

✅ Use SCOPE_IDENTITY() for safer identity retrieval.


86. What is a materialized view?
A physical copy of data from a query, stored and periodically refreshed.
Not available in SQL Server — available in Oracle/PostgreSQL.

87. How to reverse a string in SQL Server?

88. How to get top 3 salaries per department?

89. What is the difference between VARCHAR and NVARCHAR?

 VARCHAR: Non-Unicode (1 byte/char)


 NVARCHAR: Unicode (2 bytes/char, supports international characters)

✅ Use NVARCHAR for multilingual apps.

90. What is the use of PATINDEX() and CHARINDEX()?

 CHARINDEX: Returns position of a substring


 PATINDEX: Supports wildcards (like %, _)
91. How to fetch only even or odd rows?
Assuming ID is sequential:

92. What is the difference between TEMPDB, MASTER, MODEL, and MSDB databases?

System DB Purpose
MASTER Tracks server-level info (logins, linked servers)
TEMPDB Stores temporary tables, temp vars, intermediate results
MODEL Template for new databases
MSDB Manages jobs, alerts, scheduling (SQL Agent)

93. What is the use of CROSS APPLY?


Used to call table-valued functions per row. Also works for joins with derived tables.

94. What is TRY_CAST() and TRY_CONVERT()?


Safe versions of CAST()/CONVERT() that return NULL instead of error if conversion fails.
95. What is an indexed view?
A view with a clustered index — becomes materialized and improves performance.

📌 Requirements:

 Deterministic functions only


 Schema binding
 No GROUP BY ROLLUP, TOP, UNION, etc.

96. How to perform full-text search in SQL Server?

Useful for word-based search in large text columns.

97. What is a log shipping?


High-availability feature to automatically send transaction logs from one server to another for
backup or failover.

98. What is the difference between WITH TIES and TOP?

WITH TIES: Includes additional rows with the same value as the last row.
99. What is a blocking vs deadlock?

 Blocking: One transaction holds a lock, others wait


 Deadlock: Two or more transactions wait for each other — circular dependency

✅ Deadlocks are fatal (one gets killed), blocking just causes delay.

100. How to export SQL query results to a file in SSMS?

1. Go to Query → Results To → Results to File


2. Run query
3. Save as .csv or .txt

Or use command line:

You might also like