Stored Procedures & Functions Interview Questions
Comprehensive stored procedures & functions interview questions and answers for SQL. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is the difference between a stored procedure and a function in SQL?
Basic2. What are the different types of functions in SQL?
Basic3. How do you handle error handling in stored procedures?
Moderate4. What are the benefits of using stored procedures over direct SQL queries?
Basic5. How do you optimize stored procedure performance?
Advanced6. What is parameter sniffing and how do you handle it?
Advanced7. How do you implement dynamic SQL in stored procedures safely?
Advanced8. What are the best practices for stored procedure parameters?
Moderate9. How do you handle transactions in stored procedures?
Advanced10. What are inline table-valued functions and when should they be used?
Moderate11. How do you handle large result sets in stored procedures?
Advanced12. What are the security considerations for stored procedures?
Advanced13. How do you implement logging in stored procedures?
Moderate14. What is the difference between EXEC and sp_executesql?
Moderate15. How do you handle concurrent executions of stored procedures?
Advanced16. What are the best practices for function design?
Moderate17. How do you implement versioning for stored procedures?
Advanced18. What are CLR stored procedures and when should they be used?
Advanced19. How do you handle NULL values in functions?
Moderate20. What are the considerations for nested stored procedure calls?
Advanced21. How do you implement paging in stored procedures?
Moderate22. What are the best practices for temporary table usage in stored procedures?
Advanced23. How do you handle long-running stored procedures?
Advanced24. What are the differences between scalar and aggregate functions?
Basic25. How do you implement retry logic in stored procedures?
Advanced26. What are the considerations for stored procedures in replicated environments?
Advanced27. How do you handle sensitive data in stored procedures?
Advanced28. What are the best practices for stored procedure documentation?
Moderate29. How do you implement idempotent stored procedures?
Advanced1. What is the difference between a stored procedure and a function in SQL?
BasicStored procedures can perform actions and return multiple result sets but don't necessarily return values, while functions must return a value/table and can be used in SELECT statements. Functions are more limited in what they can do (e.g., can't modify data in most cases) but are more flexible in queries.
2. What are the different types of functions in SQL?
BasicSQL supports Scalar functions (return single value), Table-valued functions (return table result set), and Aggregate functions (operate on multiple values). User-defined functions can be either scalar or table-valued, while built-in functions come in all three types.
3. How do you handle error handling in stored procedures?
ModerateError handling in stored procedures uses TRY-CATCH blocks, ERROR_NUMBER(), ERROR_MESSAGE(), and RAISERROR/THROW statements. Implement appropriate error logging, transaction management, and status returns to calling applications.
4. What are the benefits of using stored procedures over direct SQL queries?
BasicBenefits include: better security through encapsulation and permissions, reduced network traffic, code reuse, easier maintenance, cached execution plans, and the ability to implement complex business logic at the database level.
5. How do you optimize stored procedure performance?
AdvancedOptimize by using appropriate indexes, avoiding parameter sniffing issues, implementing proper error handling, using SET NOCOUNT ON, minimizing network roundtrips, and considering query plan reuse. Monitor and analyze execution plans for potential improvements.
6. What is parameter sniffing and how do you handle it?
AdvancedParameter sniffing occurs when SQL Server reuses a cached plan optimized for specific parameter values. Handle it using OPTION (RECOMPILE), local variables, or dynamic SQL in specific cases. Consider data distribution when choosing a solution.
7. How do you implement dynamic SQL in stored procedures safely?
AdvancedImplement dynamic SQL using sp_executesql with parameterization to prevent SQL injection. Properly escape identifiers, validate inputs, and consider performance implications. Avoid string concatenation with user inputs.
8. What are the best practices for stored procedure parameters?
ModerateUse appropriate data types, provide default values when sensible, validate inputs, use meaningful parameter names, document parameters clearly, and consider NULL handling. Implement proper parameter validation logic.
9. How do you handle transactions in stored procedures?
AdvancedImplement explicit transactions with proper error handling, consider nested transaction levels, use appropriate isolation levels, and handle deadlock scenarios. Ensure proper cleanup in error cases.
10. What are inline table-valued functions and when should they be used?
ModerateInline table-valued functions return table results based on a single SELECT statement. They often perform better than multi-statement functions because they can be treated like views and participate in query optimization.
11. How do you handle large result sets in stored procedures?
AdvancedHandle large results using pagination, batch processing, table-valued parameters, temporary tables, or table variables. Consider memory usage, network bandwidth, and client application capabilities.
12. What are the security considerations for stored procedures?
AdvancedConsider EXECUTE permissions, ownership chaining, module signing, dynamic SQL security, and principle of least privilege. Implement proper input validation and avoid SQL injection vulnerabilities.
13. How do you implement logging in stored procedures?
ModerateImplement logging using dedicated log tables, error handling blocks, and appropriate detail levels. Consider performance impact, retention policies, and monitoring requirements.
14. What is the difference between EXEC and sp_executesql?
Moderatesp_executesql supports parameterization and better plan reuse, while EXEC is simpler but more vulnerable to SQL injection. sp_executesql is preferred for dynamic SQL due to security and performance benefits.
15. How do you handle concurrent executions of stored procedures?
AdvancedHandle concurrency using appropriate isolation levels, locking hints, transaction management, and deadlock prevention strategies. Consider implementing retry logic for deadlock victims.
16. What are the best practices for function design?
ModerateKeep functions deterministic when possible, avoid excessive complexity, consider performance impact in queries, use appropriate return types, and document behavior clearly. Avoid side effects in functions.
17. How do you implement versioning for stored procedures?
AdvancedUse schema versioning, naming conventions, source control, and proper documentation. Consider backward compatibility, deployment strategies, and rollback procedures.
18. What are CLR stored procedures and when should they be used?
AdvancedCLR stored procedures are implemented in .NET languages and useful for complex calculations, string operations, or external resource access. Consider security implications and performance overhead compared to T-SQL.
19. How do you handle NULL values in functions?
ModerateHandle NULLs using ISNULL/COALESCE, appropriate function logic, and clear documentation of NULL behavior. Consider impact on query optimization and result accuracy.
20. What are the considerations for nested stored procedure calls?
AdvancedConsider transaction handling, error propagation, parameter passing, and performance impact. Manage transaction scope and error handling appropriately across nested calls.
21. How do you implement paging in stored procedures?
ModerateImplement paging using OFFSET-FETCH, ROW_NUMBER(), or other ranking functions. Consider performance with large datasets, sort stability, and total count requirements.
22. What are the best practices for temporary table usage in stored procedures?
AdvancedConsider scope, reuse, indexing strategy, and cleanup of temporary tables. Balance between table variables and temporary tables based on size and complexity.
23. How do you handle long-running stored procedures?
AdvancedImplement progress reporting, batch processing, appropriate transaction handling, and monitoring capabilities. Consider timeout handling and cancelation support.
24. What are the differences between scalar and aggregate functions?
BasicScalar functions operate on a single value and return a single value, while aggregate functions operate on sets of values and return a single summary value. Scalar functions can be used in SELECT lists and WHERE clauses.
25. How do you implement retry logic in stored procedures?
AdvancedImplement retry logic using WHILE loops, error handling, appropriate wait times, and maximum retry counts. Consider transient error conditions and implement appropriate backoff strategies.
26. What are the considerations for stored procedures in replicated environments?
AdvancedConsider execution order, deterministic operations, identity column handling, and timestamp handling. Ensure procedures work consistently across primary and secondary servers.
27. How do you handle sensitive data in stored procedures?
AdvancedImplement appropriate encryption, use secure parameter passing, avoid logging sensitive data, and consider data masking requirements. Follow security best practices for handling confidential information.
28. What are the best practices for stored procedure documentation?
ModerateDocument purpose, parameters, return values, error conditions, dependencies, and usage examples. Include version history, performance considerations, and any special handling requirements.
29. How do you implement idempotent stored procedures?
AdvancedDesign procedures to produce the same result regardless of multiple executions. Use appropriate checks, handle existing data, and implement proper transaction management for consistency.