Tech Point Fundamentals

Friday, August 12, 2022

SQL Interview Questions and Answers - Part 12

SQL Interview Questions and Answers - Part 12


Are you preparing for the SQL Interview? If yes, then you are at the right place. This is the SQL Interview Questions and Answers article series. Here we will see the Top 100+ SQL Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:

Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.


This is the 12th part of the SQL Interview Questions and Answers article series. Each part contains eight to ten SQL Interview Questions with Answers. Please read all the SQL Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:

SQL Interview Questions and Answers - Part 12

Q100. How can you return value from a stored procedure?

There are three ways of returning data from a procedure to a calling program: result sets, output parameters, and return codes

To trap non-fatal errors in a called stored procedure, the called procedure must have some way to communicate back to the calling procedure that an error has occurred. To do this, pass a value back via the RETURN statement, or use an OUTPUT parameter. Either way works, but once you adopt a method, all the procedures in a system must use it

Using RETURN Statement:

By default when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The value zero indicates that the procedure is completed successfully and the non-zero values indicate an error. 

So every stored procedure returns an integer return code to the caller. If the stored procedure does not explicitly set a value for the return code, the return code is 0. We cannot return more than one value using the return status variable in SQL Server.

A procedure can return an integer value called a return code to indicate the execution status of a procedure. You specify the return code for a procedure using the RETURN statement. Before the introduction of TRY/CATCH/THROW error handling in TSQL return codes was sometimes required to determine the success or failure of stored procedures.

But the stored procedure return value data type can only be an integer and can not be changed. Therefore, we can not assign any data type other than an integer value, otherwise, the assigned value is converted implicitly into an integer or get a data type conversion error.

If a NULL value is assigned to the stored procedure's return value when changing it. SQL Server automatically converts NULL values into 0. So you can never return a NULL value from the stored procedure.

DECLARE @return_value int
EXEC @return_value = [dbo].[procGetUsers]
SELECT 'Return Value' = @return_value

Using OUTPUT Parameter:

If we want multiple return values, we can use the OUT parameter. We can define output parameters instead of the return value in the stored procedure and can assign several data types to it as well unlike the RETURN command. 

DECLARE @return_value int, @factorial int
EXEC @return_value = [dbo].[GetFactorial] @Num = 5, @factorial = @factorial OUTPUT
SELECT @factorial as N'@factorial'
SELECT 'Return Value' = @return_value

The advantage of the OUT parameter is that OUTPUT parameters can be of any type while a return value can only be of integer type.

The second advantage of the OUT parameter is that you can return multiple values by defining multiple OUT parameters.

Using Result SET:

If you include a SELECT statement in the body of a stored procedure the rows specified by the SELECT statement will be sent directly to the client. If multiple such SELECT statements are run during the execution of the stored procedure, multiple result sets will be sent to the client. 

CREATE PROCEDURE procMultipleResults
SELECT TOP(10) Id, Lastname, FirstName FROM Employee;
SELECT TOP(10) Id, RoleName FROM RoleMaster;

This behavior also applies to nested Transact-SQL batches, nested stored procedures, and top-level Transact-SQL batches.

Q101. What is a temporary stored procedure? What is the use of a temp stored procedure?

Temporary Stored Procedure:

Like the temporary table, we can create temporary procedures as well. Temporary procedures are a form of user-defined procedures. The temporary procedures are the same as permanent procedures, except temporary procedures are stored in the "TempDB" database. 

There are two types of temporary procedures: Local and Global. They differ from each other in their names, their visibility, and their availability. But Temporary names cannot be specified for CLR procedures.

Local Temporary Stored Procedures have a single pound sign (#) as the first character of their names. They are visible only to the current user connection, and they are deleted when the connection is closed. 

Local Temporary Stored Procedure name cannot exceed 116 characters(including #). SQL adds the pseudo-random generated suffix in the local temp stored procedures like local temp tables. This is done to avoid name clashes in situations when the same name is used in more than one session.  SQL Server reserves 14 characters for this suffix.

PRINT 'Local temp stored procedure'

Global Temporary Stored Procedures have two-pound signs (##) as the first two characters of their names. They are visible to any user after they are created, and they are deleted at the end of the last session using the procedure.

Global Temporary Stored Procedure name cannot exceed 128 characters (including ##).

PRINT 'Global temp stored procedure'

Q102. What is the difference between recursive vs nested stored procedures? 

Nested Procedures means procedure within a procedure. So when the one stored procedure calls another stored procedure it is called stored procedure nesting. 

This is also known as a switching yard because we often create one stored procedure that executes one of many SPs based on what parameters are sent in. The nesting level increases each time a stored procedure calls another SP. 

The nesting limit in SQL server is up to 32 procedures; however, there is no limit on the number of procedures that can be called from a single procedure. The nesting level of the current procedure can be returned using the @@Nestlevel function. 

When the nest level exceeds 32 the transaction will stop with an error. SQL Server didn’t bother to check if the stored procedure at nesting level 33  existed or not since executing it would have exceeded the max nesting level. So the SQL with throw an error if the stored procedure that would have caused the max nesting level to be exceeded does not exist.

On the other hand,  you can also have a stored procedure that calls itself. This type of nesting is called recursion and you will get an error if you exceed the max nesting level.

Recursion is when a procedure calls itself until a stop condition is reached. However, due to limitations on nesting levels, recursion is also limited to 32 calls. So a stored procedure can call itself up to the maximum nesting level of 32. 

@Num INT,
@factorial INT OUTPUT
DECLARE @n_1 int
DECLARE @factemp int
IF @Num != 1
    SELECT @n_1 = @Num - 1      
    EXEC GetFactorial @n_1, @factemp OUTPUT       
    SELECT @factorial = @Num * @factemp
            SELECT @factorial = 1

You can execute the above SP as follows:

DECLARE @factorial INT
Exec GetFactorial 4, @factorial OUTPUT
SELECT @factorial;

Q103. What is the use of the WITH RECOMPILE option in the stored procedure? Why one should use it?

RECOMPILE options indicate that the Database Engine does not cache a query plan for this procedure, forcing it to be compiled each time it is executed. This option cannot be used when FOR REPLICATION is specified or for CLR procedures.

There are three ways to do this: WITH RECOMPILE option in the procedure definition or when the procedure is called, the RECOMPILE query hint on individual statements, or by using the sp_recompile system stored procedure. 

The WITH RECOMPILE clause is helpful when the parameters supplied to the procedure are not typical, and when a new execution plan should not be cached or stored in memory.


If this option is used when the procedure definition is created, it requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created.

CREATE PROCEDURE procGetEmployees  
-- TSQL Operation

If WITH RECOMPILE option is used in an EXECUTE statement, it requires to EXECUTE permissions on the procedure. 

Permissions are not required on the EXECUTE statement itself but execute permissions are required on the procedure referenced in the EXECUTE statement.



This feature is used when the procedure is created and the hint is included in Transact-SQL statements in the procedure. Therefore, it requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created.

It is used to instruct the Database Engine to discard query plans for individual queries inside a procedure, use the RECOMPILE query hint in the definition of the query. 

FROM Address

sp_recompile System Stored Procedure: It requires ALTER permission on the specified procedure.

EXEC sp_recompile N'dbo.procGetUserHistory';   


When a procedure is compiled for the first time or recompiled, the procedure's query plan is optimized for the current state of the database and its objects. If a database undergoes significant changes to its data or structure, recompiling a procedure updates and optimizes the procedure's query plan for those changes. This can improve the procedure's processing performance.

There are times when procedure recompilation must be forced and other times when it occurs automatically. Automatic recompiling occurs whenever SQL Server is restarted. It also occurs if an underlying table referenced by the procedure has undergone physical design changes.

Another reason to force a procedure to recompile is to counteract the "parameter sniffing" behavior of procedure compilation. When SQL Server executes procedures, any parameter values that are used by the procedure when it compiles are included as part of generating the query plan.

SQL Server features statement-level recompilation of procedures. When SQL Server recompiles stored procedures, only the statement that caused the recompilation is compiled, instead of the complete procedure.
If certain queries in a procedure regularly use typical or temporary values, procedure performance can be improved by using the RECOMPILE query hint inside those queries

Q104. How can you ENCRYPT and DECRYPT the stored procedure? 

In SQL Server, you can encrypt a stored procedure at the time you create it, or you can alter it later to include encryption. To create a stored procedure with T-SQL, you can use the WITH ENCRYPTION option.

The WITH ENCRYPTION option indicates that SQL Server converts the original text of the CREATE PROCEDURE statement to an obfuscated format. The output of the obfuscation is not directly visible in any of the catalog views in SQL Server. This option is not valid for CLR procedures.

The WITH ENCRYPTION option obfuscates (Make obscure or unclear) the definition of the procedure when querying the system catalog or using metadata functions i.e sp_helptext or sys.sql_modules.

Users who have no access to system tables or database files cannot retrieve the obfuscated text. However, the text is available to privileged users who can either access system tables over the DAC port or directly access database files. 

Also, users who can attach a debugger to the server process can retrieve the decrypted procedure from memory at runtime. Procedures created with this option cannot be published as part of SQL Server replication.

CREATE PROCEDURE procGetEmployees  
-- TSQL Operation

Q105. How can you improve the performance of a stored procedure?

Following are some best practices that should be followed while creating a stored procedure. 

  1. Use the SET NOCOUNT ON statement as the first statement in the body of the procedure. This turns off messages that SQL Server sends back to the client.
  2. Use schema names when creating or referencing database objects in the procedure. It takes less processing time for the Database Engine to resolve object names if it does not have to search multiple schemas. 
  3. Avoid wrapping functions around columns specified in the WHERE and JOIN clauses. Doing so makes the columns non-deterministic and prevents the query processor from using indexes.
  4. Reduce the no of JOINs and use the columns which have proper indexes.
  5. Avoid using scalar functions in SELECT statements that return many rows of data. Because the scalar function must be applied to every row, the resulting behavior is like row-based processing and degrades performance.
  6. Avoid the use of SELECT *. Instead, specify the required column names. This can prevent some Database Engine errors that stop procedure execution. 

  7. Use the UNION ALL operator instead of the UNION or OR operators, unless there is a specific need for distinct values. 
  8. Avoid processing or returning too much data. Narrow the results as early as possible in the procedure code.
  9. Use explicit transactions by using BEGIN/COMMIT TRANSACTION and keep transactions as short as possible. Longer transactions mean longer record locking and a greater potential for deadlock.
  10. Use the Transact-SQL TRY/CATCH feature for error handling inside a procedure. This not only creates less performance overhead, but it also makes error reporting more accurate with significantly less programming.
  11. Use the DEFAULT keyword on all table columns that are referenced by CREATE TABLE or ALTER TABLE Transact-SQL statements in the body of the procedure. This prevents passing NULL to columns that do not allow null values.
  12. Use NULL or NOT NULL for each column in a temporary table. The ANSI_DFLT_ON and ANSI_DFLT_OFF options control the way the Database Engine assigns the NULL or NOT NULL attributes to columns when these attributes are not specified in a CREATE TABLE or ALTER TABLE statement. 

Q106. What is SCHEMABINDING in stored procedure? If all the stored procedures are bounded to the schema by default, then why do we need to do it explicitly?

The SCHEMABINDING option specifies that the schema is bound to the database objects that it references. It ensures that tables that are referenced by a procedure cannot be dropped or altered.

In addition to function, WITH SCHEMABINDING can also be used with views and procedures, and there can be tangible benefits there that don't involve performance. Mainly these revolve around either preventing unauthorized or inadvertent changes or preventing unexpected results.

SCHEMABINDING is a little bit different in Stored procedures. Only natively compiled stored procedures can be schema bound. In fact, natively compiled stored procedures must be schema bound. 

You can’t create a natively compiled stored procedure without schema binding it. But if you try to schema bind a regular i.e non-natively compiled procedure, you’ll get an error.

CREATE PROCEDURE dbo.procGetUserDetails 
LANGUAGE = N'us_english'
FROM [dbo].[Employee]

In the above example along with the WITH SCHEMABINDING argument, I have also included NATIVE_COMPILATION, which indicates that the procedure is natively compiled. 

Also, notice the ATOMIC WITH block. This is required for natively compiled stored procedures. It specifies the transaction isolation level for the stored procedure.

Q107. How can you write a stored procedure which executes automatically when SQL Server restarts?

There are two different ways to execute a stored procedure:

  • The first and most common approach is for an application or user to call the procedure. 
  • The second approach is to set the procedure to run automatically when an instance of SQL Server starts. 

When a procedure is called by an application or user, the Transact-SQL EXECUTE or EXEC keyword is explicitly stated in the call. The procedure can be called and executed without the EXEC keyword if the procedure is the first statement in the Transact-SQL batch.

Some procedures can execute automatically when SQL Server starts. The procedures must be created by the system administrator in the master database and executed under the sysadmin fixed server role as a background process. The procedures cannot have any input or output parameters. 

Execute Stored Procedures Automatically:

Procedures marked for automatic execution are executed every time SQL Server starts and the master database is recovered during that startup process. A procedure that is automatically executed operates with the same permissions as members of the sysadmin fixed server role.

So only the system administrator (SA) can mark a procedure to execute automatically. In addition, the procedure must be in the master database, owned by sa, and cannot have input or output parameters.  Any error messages generated by the procedure are written to the SQL Server error log.  

There is no limit to the number of startup procedures you can have, but be aware that each consumes one worker thread while executing. If you must execute multiple procedures at startup but do not need to execute them in parallel, make one procedure the startup procedure and have that procedure call the other procedures. This uses only one worker thread.

Do not return any result sets from a procedure that is executed automatically. Because the procedure is being executed by SQL Server instead of an application or user, there is nowhere for the result sets to go.

Setting up procedures to execute automatically can be useful for performing database maintenance operations or for having procedures run continuously as background processes. 

Another use for automatic execution is to have the procedure perform system or maintenance tasks in tempdb, such as creating a global temporary table. This makes sure that such a temporary table will always exist when tempdb is re-created during SQL Server startup.

EXEC sp_procoption @ProcName = N'<procedure name>'   
    , @OptionName = 'startup'   
    , @OptionValue = 'on';

Q108. Is stored procedure names case-sensitive?

The calling database collation is used when matching system procedure names. For this reason, always use the exact case of system procedure names in procedure calls. 

EXEC SP_heLP; -- Will fail to resolve because SP_heLP does not equal sp_help  

To display the exact system procedure names, query the sys.system_objects and sys.system_parameters catalog views.

If a user-defined procedure has the same name as a system procedure, the user-defined procedure might not ever execute.

Q109. What is CLR stored procedure? What is the use of the CLR procedure?

CLR stored procedure is a special type of procedure that is based on the CLR (Common Language Runtime) in the .net framework. 

CLR integration of procedure was introduced with SQL Server 2008 and allows for the procedure to be coded in one of .NET languages like C#, Visual Basic, and F#.

Q110. What is the use of  EXECUTE AS clause in the stored procedure?  

By default, a session starts when a user logs in and ends when the user logs off. All operations during a session are subject to permission checks against that user. 

When an EXECUTE AS statement is run, the execution context of the session is switched to the specified login or user name. After the context switch, permissions are checked against the login and user security tokens for that account instead of the person calling the EXECUTE AS statement. 

In essence, the user or login account is impersonated for the duration of the session or module execution, or the context switch is explicitly reverted.

The EXECUTE AS clause is used to specify the security context in which a procedure can be executed. 


In the above example, the option CALLER specifies that the procedure can be executed in the context of the user that calls it.

To Be Continued Part-13...

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK  for regular updates.


Wednesday, August 10, 2022

Design Pattern Interview Questions And Answers List

Design Patterns Interview Questions and Answers List


In Software Industry the Design Patterns and Principles are always followed. So this is the most common topic for the interview. In this article, we will see the most frequently asked 80+ Design Patterns and Principles Interview Questions with Answers

Please visit our YouTube Channel for Interviews and other videos by below link:


I have already posted all the Design Patterns and Principles Interview Questions and Answers article series. Here we will see all the Design Patterns Interview Questions Summary and the particular part link so that you can walk through the answer to the particular interview question directly.

 Please read the important Interview Questions and Answers article series here: 

1. Architectural Patterns Interview Questions List 

Q01. What is Design Pattern and why Design Patterns are important to use? 
Q02. What is Design Framework? How it is different from the Design Pattern?
Q03. What is the difference between Design Pattern and Design Framework?
Q04. What is Design Principle? What is the difference between Design Patterns and Design Principles?
Q05. What is Architectural Pattern? What is the difference between Architectural Patterns and Design Patterns?
Q06. What is the N-Layer Architecture? Why layering your application is important?
Q07. What is N-Tire Architecture? What is the difference between N-Tire Architecture and N-Layer Architecture?
Q08. What is the MVC Pattern? How MVC is different from 3-Layer Architecture or 3-Tire Architecture? 

Q09. What is Monolithic Architecture? What are the advantages of using it?
Q10. What is Microservices Architecture? What is the difference between Microservices Architecture and Monolithic Architecture? 
Q11. What is Service-Oriented Architecture (SOA)? What are the advantages of SOA?
Q12. What is the Waterfall Model of software development? 
Q13. What is Agile Methodology? How it is different from the Traditional Waterfall process model?
Q14. What is the difference between the Agile Process Model and the Traditional Waterfall Process Model?
Q15. What is Cohesion?  How does it play a vital role in application design?
Q16. What is Coupling?  How does it play a vital role in software design?
Q17. What is the difference between Cohesion and Coupling? What is the relationship between them? 

2. Design Principles Interview Questions List 

Q18. What are the different Object-Oriented Design Principles?
Q19. What are the SOLID Design Principles?
Q20. What is the Single Responsibility Principle (SRP)?
Q21. What is the Open-Closed Principle (OCP)?
Q22. What is Liskov Substitution Principle (LSP)?
Q23. What is Interface Segregation Principle (ISP)?
Q24. What is the Dependency Inversion Principle (DIP)? 

Q25. What is Inversion of Control (IoC)? What is the difference between the Dependency Inversion Principle and IoC?
Q26. What is the IoC Container? What is the difference between IoC and IoC containers? 
Q27. What is Dependency Injection (DI)? What problems does Dependency Injection solve? How the DI is different from Inversion of Control?
Q28. What is the difference between Dependency Injection (DI) and Service Locator Patterns (SLP)?
Q29. What is GOD Class or GOD Object and why should we avoid it?
Q30. What is Anti-Pattern? Can you give me some pattern names that are considered anti-patterns?
Q31. What is Pseudocode? Why to use Pseudocode in the software industry?
Q32. What is Data Access Object (DAO) Pattern? 

3. Design Patterns Interview Questions List 

Q33. What is CQRS (Command and Query Responsibility Segregation) or CQS (Command Query Separation)  Architectural Pattern?
Q34. What is Domain-Driven Design (DDD) Pattern?
Q35. What is ORM Pattern? Why ORM is an anti-pattern?
Q36. What is the Unit of Work (UoW) Pattern? Why it is used in the Repository Pattern?
Q37. What is the ADO Dot Net? What is the limitation of this framework? 
Q38. What is the Entity Framework (EF)? What is the difference between ADO and Entity Framework?
Q39. What is the difference between LINQ-to-Entities and LINQ-to-Objects?
Q40. What is LINQ-To-SQL? What is the use of ADO.NET DataSet Designer?

Q41. What is Repository Pattern? What is the difference between the Repository Pattern and Entity Framework?
Q42. What is the difference between the Repository Pattern and the legacy Data Access Class (DAL) Pattern?
Q43. What is Service Locator Pattern (SLP)? When service locator pattern is used?
Q44. What is Intercepting Filter Pattern (IFP) or Intercepting Pattern (IP)? When can you use the Intercepting Pattern?
Q45. What is UML (Unified Modeling Language)? 
Q46. What are ERD and ERM? What is the difference between UML and ERD diagrams?
Q47. What is a Design Smell or Code Smell? 
Q48. What is a code rot problem or software rot?

4. GOF Creational Design Patterns Interview Questions List 

Q49. What is GoF Pattern? 
Q50. What are the different types of design patterns available in the software industry?
Q51. What are the Creational Design Patterns (CDP)? What are the different Creational Design Patterns?
Q52. What is Factory Design Pattern (FDP)? When to use the Factory Pattern?
Q53. Why do we use a factory class to instantiate a class when we can use a new operator directly?
Q54. What is Abstract Factory Design Pattern (AFDP)? When to use the Abstract Factory Creational Design Pattern?
Q55. What is the difference between Factory Pattern and Abstract Factory Design Pattern?
Q56. What is Builder Design Pattern (BDP)? When to use the Builder Creational Design Pattern?

Q57. What is Singleton Design Pattern (SDP)? What are the different types of Singleton?
Q58. When you should use Singleton? Why Singleton Pattern is considered an Anti-Pattern?
Q59. What is the difference between Static Class and Singleton Pattern?
Q60. Is it possible to create a clone of a singleton object? How do you prevent singleton object cloning?
Q61. What is the difference between Singleton Pattern and Factory Pattern?
Q62. What is Prototype Design Pattern (PDP)? When to use the Prototype Creational Design Pattern?
Q63. What is a Fluent Interface Design Pattern? What is the use of a Fluent Interface Pattern?
Q64. What is the difference between Singleton Pattern and Prototype Pattern?

5. GOF Structural Design Patterns Interview Questions List 

Q65. Why Singleton Classes are sealed? What is the difference between a Singleton Pattern and Singleton Object?
Q66. What are the Structural Design Patterns (SDP)? What are the different Structural Design Patterns?
Q67. What is Adapter Design Pattern (ADP)? What are the different types of Adapter Patterns?
Q68. What is Bridge Design Pattern (BDP)? What is the use of Bridge Pattern?
Q69. What is Composite Design Pattern (CDP) or Tree Pattern?
Q70. What is Decorator Design Pattern (DDP) or Wrapper Pattern? What is the difference between Decorator Pattern vs Inheritance?
Q71. What is Proxy Design Pattern (PDP)? What is the difference between Adapter vs Decorator vs Proxy:?
Q72. What is Façade Design Pattern (FDP)? What is the difference between Façade and Mediator?
Q73. What is Flyweight Design Pattern (FDP) or Cache Pattern?

6. GOF Behavioural Design Patterns Interview Questions List 

Q74. What are the Behavioral Design Patterns (BDP)? What are the different Behavioral Design Patterns?
Q75. What is Iterator Design Pattern (IDP)? When to use the Iterator Behavioral Design Pattern?
Q76. What is Observer Design Pattern (ODP) or Event-Subscriber Pattern?  When to use the Observer Behavioral Design Pattern?
Q77. What is Mediator Design Pattern (MDP) or Controller Pattern?  When to use the Mediator Behavioral Design Pattern?
Q78. What is Interpreter Design Pattern (IDP)?
Q79. What is Command Design Pattern (CDP) or Action Pattern?
Q80. What is Memento Design Pattern (MDP) or Snapshot Pattern?
Q81. What is State Design Pattern (SDP)?

Q82. What is Strategy Design Pattern (SDP) or Policy Pattern? When to use the Strategy Design Pattern?
Q83. What is Visitor Design Pattern (VDP)?
Q84. What is Template Design Pattern (TDP)?
Q85. What is the Chain of Responsibility Design Pattern (CoR) or Chain of Command Pattern?
Q86. What is the Null Object Pattern?
Q87. What is Circular Dependency and how can you resolve this issue?
Q88. What is the difference between Sprint and Scrum?

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.