top 15 sql server interview questions with answers

Q. What is sub query and its properties?
A. A sub-query is a query which can be nested inside a main query like Select, Update, Insert or Delete statements. This can be used when expression is allowed. Properties of sub query can be defined as

  • A sub query should not have order by clause.
  • A sub query should be placed in the right hand side of the comparison operator of the main query.
  • A sub query should be enclosed in parenthesis because it needs to be executed first before the main query.
  • More than one sub query can be included.

Q. What are the types of sub query?
A. There are three types of sub query –

  • Single row sub query which returns only one row.
  • Multiple row sub query which returns multiple rows.
  • Multiple column sub query which returns multiple columns to the main query. With that sub query result, Main query will be executed.

Q. What are the differences between local and global temporary tables?
A. Local temporary tables are visible when there is a connection, and are deleted when the connection is closed.

CREATE TABLE #<tablename>

Global temporary tables are visible to all users, and are deleted when the connection that created it is closed.

CREATE TABLE ##<tablename>

Q. What is COALESCE in SQL Server?
A. COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments. Lets suppose we have d2c_tblStudents table and having following data:

what-is-coalesce-in-sql-server

 

SELECT coalesce(studentName,studentClass,studentAddress) FROM d2c_tblStudents

output of above query will be “student1”. If we change above query as follow

SELECT coalesce(studentAddress,studentName,studentClass) FROM d2c_tblStudents

output will be remain same as previous one.

Q. What is a Trigger? How many types of triggers?
A. Triggers are used to execute a batch of SQL code when insert or update or delete commands are executed against a table. Triggers are automatically triggered or executed when the data is modified. It can be executed automatically on insert, delete and update operations.

There are four types of triggers and they are:
• Insert
• Delete
• Update
• Instead of

Q. What is an IDENTITY column in insert statements?
A. IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.

Q. What is the difference between UNION and UNION ALL?
A. UNION: To select related information from two tables UNION command is used. It is similar to JOIN command.
UNION All: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It will not remove duplicate rows, instead it will retrieve all rows from all tables.

Q. What are the differences between Stored Procedure and the dynamic SQL?
A. Stored Procedure is a set of statements which is stored in a compiled form. Dynamic SQL is a set of statements that dynamically constructed at run time and it will not be stored in a Database and it simply execute during run time.

Q. What are Magic Tables in SQL Server?
A. Insert and Delete tables are created when the trigger is fired for any DML command. Those tables are called Magic Tables in SQL Server. These magic tables are used inside the triggers for data transaction.

Q. What is the difference between COMMIT and ROLLBACK?
A. Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed. Every statement between BEGIN and ROLLBACK are reverted to the state when the ROLLBACK was executed.

Q. What is the difference between varchar and nvarchar types?
A. Varchar and nvarchar are same but the only difference is that nvarhcar can be used to store Unicode characters for multiple languages and it also takes more space when compared with varchar.

Q. What is SQL injection?
A. SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives.
Even parameters can be manipulated by the skilled and experienced attackers

Q. What are the methods used to protect against SQL injection attack?
A. Following are the methods used to protect against SQL injection attack:

  • Use Parameters for Stored Procedures.
  • Filtering input parameters.
  • Use Parameter collection with Dynamic SQL.
  • In like clause, user escape characters.

Q. What is Filtered Index?
A. Filtered Index is used to filter some portion of rows in a table to improve query performance, index maintenance and reduces index storage costs. When the index is created with WHERE clause, then it is called Filtered Index.

Q. Explain the difference between DELETE , TRUNCATE and DROP commands?
A. Following are the differences

  • Once delete operation is performed, Commit and Rollback can be performed to retrieve data.
  • Once the truncate statement is executed, Commit and Rollback statement cannot be performed. Where condition can be used along with delete statement but it can’t be used with truncate statement.
  • Drop command is used to drop the table or keys like primary,foreign from a table.

Access Values from All asp.net TextBoxes using jQuery

Let suppose we want to access values from all ASP.NET Textboxes on a Button click. Empty Textboxes should be ignored.

JQuery Section:

$(function () {
$('input[id$=btnAll]').click(function (e) {
e.preventDefault();
$("#para").text('')
.append($("input:text").map(function () {
return $(this).val() || null;
}).get().join("
"));
});
});

Explanation:
To achieve this requirement,$.map() is an extremely useful function which saves us from writing many steps. This function transforms an array into another array by using a filter function and then allows us to access individual items of the array and modify them.
In the code shown above, on the button (btnAll) click, the postback is prevented using e.preventDefault().The content of the paragraph is reset ($(“#para”).text(”)) and we then use a Selector to match all input elements of type text (input:text). The $.map() method iterates through all the textboxes on the page and invokes a filter function to select the non-empty textboxes. The results are appended to a paragraph (para) and displayed individually using a line break (<br/>).

Complete code

$(function () {
$('input[id$=btnAll]').click(function (e) {
e.preventDefault();
$("#para").text('')
.append($("input:text").map(function () {
return $(this).val() || null;
}).get().join("
"));
});
});

<asp:TextBox ID=”txtBox1″ runat=”server” Text=”Text Box 1″ /><br />
<asp:TextBox ID=”txtBox2″ runat=”server” Text=”Text Box 2″/><br />
<asp:TextBox ID=”txtBox3″ runat=”server” Text=”Text Box 3″/><br />
<asp:TextBox ID=”txtBox4″ runat=”server” Text=”Text Box 4″ /><br />
<asp:Button ID=”btnAll” runat=”server” Text=”Display All” ToolTip=”Click to display text from all boxes” />
<br/><p id=”para”></p>

Output

access-values-from-all-textboxes-using-jquery

 

How .NET Program Execute

Using dotnet we can create different types of applications. A few of the common types of .NET applications include Web, Windows, Console and Mobile Applications. Irrespective of the type of the application, when you execute any .NET application the following happens

1. The .NET application gets compiled into Intermediate language (IL). IL is also referred as Common Intermediate language (CIL) and Microsoft Intermediate language (MSIL).

So, in .NET the application execution consists of 2 steps
1. Language compiler, compiles the Source Code into Intermediate Language (IL)
2. JIT compiler in CLR converts, the IL into native code which can then be run on the underlying operating system.

dot-net-program-execution

Since, a .NET assembly is in Intermedaite Language format and not native code, .NET assemblies are portable to any platform, as long as the target platform has the Common Language Runtime (CLR). The target platform’s CLR converts the Intermedaite Language into native code that the underlying operating system can understand. Intermediate Languge is also called as managed code. This is because CLR manages the code that runs inside it.

The native code is not stored permanently anywhere, after we close the program the native code is thrown awaya. When we execute the program again, the native code gets generated again.

.NET program is similar to java program execution. In java we have byte codes and JVM (Java Virtual Machine), where as in .NET we Intermediate Language and CLR (Common Language Runtime)

top 5 c# interview question with answer

1. What is Managed or Unmanaged Code?

Managed Code
“The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any language that is written in .NET Framework is managed code”.

Unmanaged Code
The code, which is developed outside .NET framework is known as unmanaged code.

“Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low – level functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code”.

2. What is Boxing and Unboxing?
Boxing and Unboxing both are used for type conversion but have some difference:

Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.

Example:
private void boxing()
{
int _iLocal = 170;
object _obj = _iLocal;//boxing
Console.WriteLine(_obj);
}

Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.

Example:
private void unboxing()
{
object _obj = 170;
int _iLocal = (int)_obj;//unboxing
Console.WriteLine(_iLocal);
}

3. What is the difference between a struct and a class in C#?

Class and struct both are the user defined data type but have some major difference:

Struct 

  • The struct is value type in C# and it inherits from System.Value Type.
  • Struct is usually used for smaller amounts of data.
  • Struct can’t be inherited to other type.
  • A structure can’t be abstract.
  • No need to create object by new keyword.
  • Do not have permission to create any default constructor.

Class

  • The class is reference type in C# and it inherits from the System.Object Type.
  • Classes are usually used for large amounts of data.
  • Classes can be inherited to other class.
  • A class can be abstract type.
  • We can’t use an object of a class with using new keyword.
  • We can create a default constructor.

4. What is the difference between Interface and Abstract Class?

Their are some differences between Abstract Class and Interface which are listed below:

  • A class can implement any number of interfaces but a subclass can at most use only one abstract class.
  • In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don’t need to use that.
  • An abstract class can declare or use any variables while an interface is not allowed to do so.
  • An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
  • An abstract class use constructor while in an interface we don’t have any type of constructor
  • In an abstract class all data member or functions are private by default while in interface all are public, we can’t change them manually.
  • An abstract class can’t be used for multiple inheritance while interface can be used as multiple inheritance.

5.What is the difference between string and StringBuilder in c#?
StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:

String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:

private void stringFun()
{
string str = string.Empty;
str += "Welcome";// creata a new string instance rather then using old one
str += " to desire2code.com";
Console.WriteLine(str);
}

Point to remember:

  • It’s an immutable object that hold string value.
  • Performance wise string is slow because it’s create a new instance to override or change the previous value.
  • String belongs to System namespace.

Stringbuilder is mutable object which also hold the string value, mutable means once we create a System.Text.Stringbuilder object we can use this object for any operation like insert value in existing string with insert functions also replace or append without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System.String. Let’s have an example to understand System.Text.Stringbuilder like:

private void stringBuilderFun()
{
StringBuilder str = new StringBuilder("");
str.Append("Welcome");// Will use it's old instance
str.Append(" to desire2code.com");
Console.WriteLine(str);
}

Point to remember:

  • StringBuilder is a mutable object.
  • Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
  • StringBuilder belongs to System.Text.Stringbuilder namespace.

create and run a console application

To create and run a console application

  • Start Visual Studio.
  • On the menu bar, choose File, New, Project.
  • The New Project dialog box opens.
  • Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
  • The new project appears in Solution Explorer.
  • If Program.cs isn’t open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.
  • Replace the contents of Program.cs with the following code.


// “Welcome 2 Desire2Code.com” program in C#.
using System;
namespace Desire2Code
{
class Welcome
{
static void Main()
{
Console.WriteLine(“Welcome 2 Desire2Code.com”);
// Keep the console window open in debug mode.
Console.WriteLine(“Press any key to exit.”);
Console.ReadKey();
}
}
}

Choose the F5 key to run the project. A Command Prompt window appears that contains the line Welcome 2 Desire2Code.com