You are on page 1of 26

SQL Interview Question-Answer

1. What are different types of SQL Commands? Or Explain DDL, DML, TCL Commands.
- There are different commands which we use to communicate with the database to perform
specific tasks.
Data Definition Language (DDL) –
These SQL commands are used for creating, modifying, and dropping the structure of
database objects. (i.e. affects on schema or structure)
These commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
Data Manipulation Language (DML) –
These SQL commands are used for storing, retrieving, modifying, and deleting data.
(i.e. affects on data)
These commands are SELECT, INSERT, UPDATE, and DELETE.
Transaction Control Language (TCL) –
These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK.
Data Control Language (DCL) –
These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

2. Difference between Delete, Truncate and Drop commands?


Delete
- Delete is a DML command.
- The DELETE command is used to remove rows from a table.
- A WHERE clause can be used to only remove some rows if no WHERE condition is specified, all
rows will be removed.
- We can undo the delete operation by using ROLLBACK transaction command.
- This operation causes all DELETE Triggers to fire on a table.

Truncate
- TRUCATE is a DDL command and it is faster.
- TRUNCATE removes all rows from a table.
- The operation cannot be rolled back and no triggers will be fired.
- Truncate command also reset identity.

Drop
- Drop is a DDL command.
- The DROP command removes a table from the database.
- All the tables' rows, indexes and privileges will also be removed.
- No DML triggers will be fired.
- The Drop operation cannot be rolled back.

[Reason why Truncate is faster ? :When you type DELETE, all the data get copied into the Rollback
Tablespace first then delete operation get performed. That’s why when you type ROLLBACK after
deleting a table ,you can get back the data(The system get it for you from the Rollback Tablespace). All
this process take time. But when you type TRUNCATE, it removes data directly without copying it into
the Rollback Tablespace. That’s why TRUNCATE is faster. Once you Truncate you can't get back the
data.]

3. What is difference between Primary key and Unique key?


- Both unique key and Primary key are used to enforce uniqueness in the column records.
- We can find 2 differences in both the keys :
I. We can have a single Primary across the table whereas we can have multiple Unique Key
across the table.
II. Primary Key does not allow NULL value whereas Unique key allows a single NULL value.

4. What is cascading referential integrity?


- Cascading referential integrity constraint allows to define the actions that MS SQL Server should
take when a user try to delete or update records from primary key table and there is dependent
records from foreign key table.
- We have the following options when setting up Cascading referential integrity constraint
A. No Action:
This is the default behavior.
It will not allow to delete or update record from primary key table.
B. Cascade:
It will delete or update records from primary key table as well as from foreign key table.
C. Set NULL:
It will delete or update records from primary key table and set null value in foreign key
table.
D. Set Default:
It will delete or update records from primary key table and set default value in foreign key
table.
5. What is composite key in SQL?
- A composite key is a combination of two or more columns in a table that can be used to
uniquely identify each row in the table when the columns are combined uniqueness is
guaranteed, but when it taken individually it does not guarantee uniqueness.
- Sometimes more than one attributes are needed to uniquely identify an entity.
- A primary key that is made by the combination of more than one attribute is known as a
composite key.

6. Can we insert identity column value explicitly? If yes, then how?


- Yes. We can explicitly insert identity value whenever required.
- We can use Identity_Insert to achieve this.

SET IDENTITY_INSERT tblName ON

7. What are different way to get last generated identity column value?
- There are three ways to fetch last generated identity column value.
SCOPE_IDENTITY() –
Returns the last identity value that is created in the same session and in the same scope.
@@IDENTITY –
Returns the last identity value that is created in the same session and across any scope.
IDENT_CURRENT('tblName') –
Returns the last identity value that is created for a specific table across any session and any
scope.

8. What will be the value of identity column value if all rows deleted from the table? Will it reset
to default values automatically? If No then, How to reset identity column seed and increment
value to default values?
- If all rows get deleted from table but still we able to see last generated identity value.
- We can reset this identity column value to default value by using DBCC CHECKIDENT command.

DBCC CHECKIDENT(tblName, RESEED, 0)

9. What is Normalization in SQL? Why do we need of Normalization? What are different forms of
Normalization? Explain 1st , 2nd and 3rd Normal form.
- Database normalization is the step by step process to design a better database.
- Remove duplication (redundancy)
1NF
1. The data in each column should be atomic. (There should not be comma separated values).
2. The table does not contain any repeating column groups.
3. Every record should identify uniquely (i.e. every record should have primary key).

2NF
1. The table satisfy all the conditions of 1NF.
2. Identify groups and split into multiple tables.
3. Create relationship between these tables using foreign keys.

3NF
1. The table satisfy all the conditions of 1NF and 2NF.
2. Remove all columns (attributes) that are not fully dependent upon the primary key.

10. Difference between Where and Having clause?


1. WHERE clause can be used with – Select and Update statements, where as HAVING clause can
only be used with the Select statement.
2. WHERE filters rows before aggregation (GROUPING) whereas HAVING filters groups after the
aggregations are performed.
3. Aggregate functions cannot be used in the WHERE clause, unless it is in a sub query contained
in a HAVING clause whereas aggregate functions can be used in HAVING clause.

11. What all different types of joins available in SQL? Explain them.
- Basically there are 3 types of joins available in SQL.
1. Inner Join
2. Outer Join which again classified to 3 subtypes
A. Left Outer Join
B. Right Outer Join
C. Full Outer Join
3. Cross Join

Inner Join –
Inner joins returns only the matching rows from both the tables (i.e. Common records from both
tables).

Left Outer Join –


Left outer join returns matching rows from both the tables as well as non-matching rows from
the left table. (i.e. Common records from both tables and uncommon records from left table).
Right Outer Join –
Right outer join returns matching rows from both the tables as well as non-matching rows from
the right table. (i.e. Common records from both tables and uncommon records from right table).
Full Outer Join –
Full outer join returns all the rows from both the tables as well as all non-matching rows.
(i.e. Common and Uncommon records from both tables)

Cross Join –
Cross join returns Cartesian product of the tables involved in the join.

12. What is self join? Can you write a query using self join with one scenario?
- Joining a table with itself is called as SELF JOIN.
- SELF JOIN is not a different type of JOIN.
- It can be classified under any type of JOIN - INNER, OUTER or CROSS Joins.

- Output should be :

- Select E.Name as Employee, M.Name as Manager


from tblEmployee E
Left Join tblEmployee M
On E.ManagerId = M.EmployeeId

- Output by replacing NULL with ‘No Manager’ :


SELECT E.Name as Employee, ISNULL(M.Name,'No Manager') as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

- Or

SELECT E.Name as Employee, CASE WHEN M.Name IS NULL THEN 'No Manager'
ELSE M.Name END as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

- Or

SELECT E.Name as Employee, COALESCE(M.Name, 'No Manager') as Manager


FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

13. What are different ways to replace NULL values?


- We can replace NULL value using 3 different options :
A. Using ISNULL function (refer Question No 12 for query)
B. Using case statement(refer Question No 12 for query)
C. Using Coalesce() function - COALESCE() returns the first Non NULL value.
[Please prepare for the syntax also]
14. What is difference between Union and Union ALL ?
- UNION and UNION ALL operators in SQL Server, are used to combine the result-set of two or
more SELECT queries.
- For UNION and UNION ALL to work, the Number, the Data types, and the order of the columns
in the select statements should be same.
- UNION removes duplicate rows, whereas UNION ALL does not.
- UNION ALL is much faster than UNION because when we use UNION it removes the duplicate
rows and a distinct sort, which is time consuming.

15. Difference between Join and Union?


- JOINS and UNIONS are different things.
- UNION combines the result-set of two or more select queries into a single result-set which
includes all the rows from all the queries in the union, whereas JOINS, retrieve data from two or
more tables based on logical relationships between the tables.
- In short, UNION combines rows from 2 or more tables, where JOINS combine columns from 2 or
more table.

16. What is a sub query? What are its various types? Explain Correlated and Non Correlated Sub
query?
- A subquery is simply a select statement, that returns a single value and can be nested inside
a SELECT, UPDATE, INSERT, or DELETE statement.
- Subqueries are always enclosed in parenthesis and are also called as inner queries, and the
query containing the subquery is called as outer query.
- There are two types of subqueries :

Non Correlated Sub Query :

- Outer query depends on inner query.


- Inner query runs first.
- Inner query executes once.

Correlated Sub Query :

- Inner query depends on outer query.


- Outer query runs first.
- Inner query runs multiple times till the records are there in outer query.
17. What are stored procedures? Explain its advantages?
- A stored procedure is group of T-SQL (Transact SQL) statements.
- If you have a situation, where you write the same query over and over again, you can save that
specific query as a stored procedure and call it just by it's name.

Advantages :
1. Execution plan retention and reusability - Stored Procedures are compiled and their
execution plan is cached and used again, when the same SP is executed again. Although
adhoc queries also create and reuse plan, the plan is reused only when the query is textual
match and the datatypes are matching with the previous call. Any change in the datatype or
you have an extra space in the query then, a new plan is created.

2. Reduces network traffic - You only need to send, EXECUTE SP_Name statement, over the
network, instead of the entire batch of adhoc SQL code.

3. Code reusability and better maintainability - A stored procedure can be reused with
multiple applications. If the logic has to change, we only have one place to change, where as
if it is inline sql, and if you have to use it in multiple applications, we end up with multiple
copies of this inline sql. If the logic has to change, we have to change at all the places, which
makes it harder maintaining inline sql.

4. Better Security - A database user can be granted access to an SP and prevent them from
executing direct "select" statements against a table. This is fine grain access control which
will help control what data a user has access to.

5. Avoids SQL Injection attack - SP's prevent sql injection attack.

18. Write SQL statement to call a Stored Procedures with Return value.
- Let’s say there is stored procedure usp_PersonIdByName .
- We can call this procedure as :

Declare @Id int


Execute @Id = usp_PersonNameById ‘Aniket’
Print @Id
19. Write SQL statement to call a Stored Procedures with Output parameter.
- Let’s say there is stored procedure usp_PersonNameById with @Name output parameter. We
can call this procedure as :

Declare @Name varchar(50)


Execute usp_PersonNameById 2, @Name Out
Print @Name

20. What is difference between Output Parameter and Return values in Stored Procedures?
- Using return values, we can only return one value of type integer.
- Whereas output parameters, can return multiple values of any type.
- We always prefer, using output parameters, over RETURN values.
- In general, RETURN values are used to indicate success or failure of stored procedure, especially
when we are dealing with nested stored procedures. Return a value of 0, indicates success, and
any nonzero value indicates failure.

21. What is difference between Cast and Convert functions?


- To convert one data type to another, CAST and CONVERT functions can be used.
- CONVERT() function has an optional style parameter, whereas CAST() function lacks this
capability.
- Convert provides more flexibility than Cast. For example, it's possible to control how you want
DateTime datatypes to be converted using styles with convert function.
- Cast is based on ANSI standard and Convert is specific to SQL Server. So, if portability is a
concern and if you want to use the script with other database applications, use Cast().

22. What are deterministic and non-deterministic functions in SQL? Please list down some non
deterministic functions?
- Deterministic functions always return the same result any time they are called with a specific set
of input values and given the same state of the database.
Examples: Sum(), AVG(), Square(), Power() and Count()
- All aggregate functions are deterministic functions.
- Nondeterministic functions may return different results each time they are called with a specific
set of input values even if the database state that they access remains the same.
Examples: GetDate() and RAND()
23. What id RAND() function? What if you pass it a parameter e.g. RAND(1) ?
- Rand() function is a Non-deterministic function i.e. every time called gives new value between
0 and 1.
- But if you provide the seed value, the function becomes deterministic, as the same value gets
returned for the same seed value.

24. What are functions in SQL? What are different types of functions? Explain.
- Functions are block of SQL statement which are used to perform some computational logic.
- There are 3 different types of functions are available in SQL :
1. Scalar Function :
Scalar functions may or may not have parameters, but always return a single (scalar) value.
The returned value can be of any data type except text, ntext, image, cursor, and
timestamp.

2. Inline Table Valued Function :


An Inline Table Valued function, return a table.
Inline table valued function body, cannot have BEGIN and END block.
The structure of the table that gets returned, is determined by the SELECT statement with in
the function.
Inline Table Valued functions can be used to achieve the functionality of parameterized
views.
The table returned by the table valued function, can also be used in joins with other tables.

3. Multi Statement Table Valued Function :


Multi statement table valued functions are very similar to Inline Table valued functions, with
a few differences.
Multi-statement table valued function, we customize schema of returned value.
Inline Table Valued function cannot have BEGIN and END block, where as the multi-
statement function can have.

25. Write down syntax for functions ? (Note : Interviewer can ask you to write syntax for any of
these UDF’s)
- Scalar Function :

CREATE FUNCTION Function_Name(@Parameter1 DataType, @Parameter2


DataType,..@Parametern Datatype)
RETURNS Return_Datatype
AS
BEGIN
Function Body
Return Return_Datatype
END

- Inline Table Valued Function :


CREATE FUNCTION Function_Name(@Param1 DataType, @Param2 DataType...,
@ParamN DataType)
RETURNS TABLE
AS
RETURN (Select_Statement)

- Multi Statement Table Valued Function :


CREATE FUNCTION Function_Name(@Param1 DataType, @Param2 DataType...,
@ParamN DataType)
RETURNS @Table TABLE (Specify columns name list)
AS
BEGIN
--Insert into @Table
RETURN
END

26. What is difference between Inline Table Valued Function and Multi Statement Table Valued
Function?
- 1. In an Inline Table Valued function, the RETURNS clause cannot contain the structure of the
table, the function returns. Whereas, with the multi-statement table valued function, we specify
the structure of the table that gets returned
2. Inline Table Valued function cannot have BEGIN and END block, whereas the multi-statement
function can have.
3. Inline Table valued functions are better for performance, than multi-statement table valued
functions. If the given task, can be achieved using an inline table valued function, always prefer
to use them, over multi-statement table valued functions.
4. It's possible to update the underlying table, using an inline table valued function, but not
possible using multi-statement table valued function.
27. What are differences between Stored Procedures and Functions?
- Store procedures are used for business logic (Insert, Update, Delete on Records) whereas
Functions are used for computational logic(Calculations).
- Store procedures can not call in select statement whereas Functions can call in select statement.
- We can do error handling in Store procedures whereas we can’t do error handling in Functions.
- We can implement transaction in Store procedures whereas we can’t implement transaction in
Functions.
- We can create temporary tables inside Store procedure whereas we can’t create temporary
tables inside Functions.
- We need not to write return statement in Store Procedure whereas it is compulsory to write
return statement inside Function.
- Store procedure can call Store procedure, Store procedure can call Function whereas Function
can call Function but Function can not call Store procedure.

28. What are temporary tables ? What are different types.


- Temporary tables are very similar to the permanent tables.
- Temporary tables get created in the TempDB and are automatically deleted, when they are no
longer used.
- In SQL Server, there are 2 types of Temporary tables –
Local Temporary tables and Global Temporary tables.

Difference Between Local and Global Temporary Tables:


1. Local Temp tables are prefixed with single pound (#) symbol, whereas global temp tables are
prefixed with double pound (##) symbols.
2. SQL Server appends some random numbers at the end of the local temp table name, where
this is not done for global temp table names.
3. Local temporary tables are only visible to that session of the SQL Server which has created it,
whereas Global temporary tables are visible to all the SQL server sessions
4. Local temporary tables are automatically dropped, when the session that created the
temporary tables is closed, whereas Global temporary tables are destroyed when the last
connection that is referencing the global temp table is closed.

29. What are table variables?


- Table variable is a special data type that can be used to store a result set for processing at a later
time.
- table is primarily used for temporary storage of a set of rows returned as the result set of a
table-valued function.
- Functions and variables can be declared to be of type table. table variables can be used in
functions, stored procedures.
- Syntax if interviewer ask to write :
DECLARE @userData TABLE(
name varchar(30) NOT NULL,
City varchar(30) NOT NULL
);

INSERT INTO @userData


SELECT name, city FROM Employees

30. What is CTE in SQL? Can you write a syntax to create a CTE?
- A CTE is a temporary result set, that can be referenced within a SELECT, INSERT, UPDATE, or
DELETE statement, that immediately follows the CTE.
Syntax :
WITH cte_name (Column1, Column2, ..)
AS
( CTE_query )

[Note : There can be some queries asked by interviewer where he can confuse with creation of CTE then
some other query and then a query using CTE table. Please remember cte scope is only till next immediate
statement.]

31. What are differences between Temporary tables, Table Variables and CTE?
- Temporary tables can be stored in TempDB whereas Table variables can be stored in memory
but if there is a memory pressure table variables can be stored in TempDB.
- Temporary tables participates in transaction whereas Table variables does not participate in
transaction this makes table variable faster than a temporary table.
- You can not pass Temporary table as parameter whereas you can pass Table variable as
parameter to store procedure and function.
- A temporary table can have indexes, whereas a table variable can only have a primary index. If
speed is an issue Table variables can be faster, but if there are a lot of records, or there is a need
to search the temporary table based on a clustered index, then a Temporary Table would be
better. If you have less than 100 rows generally use a table variable. Otherwise use a temporary
table. This is because SQL Server won't create statistics on table variables.

32. What is difference between INSERT INTO and SELECT INTO statements?
- Both the statements are use to copy data into the table.
- For insert into statement it is mandatory to create the table and then fire insert into query
whereas for SELECT INTO statement table creation is not needed this query automatic generates
the table and copy the data.

Syntax for INSERT INTO :

- Insert into tblName values(col1Value, col2Value,…)


Or
-
INSERT INTO @targetTblName
SELECT col1, col2 FROM sourceTblName
[We need to create @targetTblName with required columns before firing this query otherwise it will going to
through error.]

Syntax for SELECT INTO :


SELECT col1, col2 INTO targetTblName FROM sourceTblName
[This query automatically generates targetTblName with copied columns and data.]

33. What are Indexes? Types of Indexes? Advantages and Disadvantages of Indexes?
- Indexes are used by queries to find data from tables quickly.
- Indexes are created on tables and views.
- The existence of the right indexes, can drastically improve the performance of the query.
- If there is no index to help the query, then the query engine, checks every row in the table
from the beginning to the end. This is called as Table Scan. Table scan is bad for performance.
- There are 2 types indexes in SQL :
1. Clustered Index:
- A clustered index determines the physical order of data in a table.
- For this reason, a table can have only one clustered index.
2. Non Clustered Index:
- The data is stored in one place, the index in another place.
- The index will have pointers to the storage location of the data. Since, the non clustered index is
stored separately from the actual data, a table can have more than one non clustered index.

Difference between Clustered and NonClustered Index:


1. Only one clustered index per table, where as you can have more than one non clustered
index
2. Clustered index is faster than a non clustered index, because, the non-clustered index has to
refer back to the table, if the selected column is not present in the index.
3. Clustered index determines the storage order of rows in the table, and hence doesn't
require additional disk space, but whereas a Non Clustered index is stored separately from the
table, additional storage space is required.

Disadvantages of Indexes:
Additional Disk Space: Clustered Index does not, require any additional storage. Every Non-
Clustered index requires additional space as it is stored separately from the table. The amount
of space required will depend on the size of the table, and the number and types of columns
used in the index.
Insert Update and Delete statements can become slow: When DML (Data Manipulation
Language) statements (INSERT, UPDATE, DELETE) modifies data in a table, the data in all the
indexes also needs to be updated. Indexes can help, to search and locate the rows, that we want
to delete, but too many indexes to update can actually hurt the performance of data
modifications.

[Note : On the top of this Interviewer may ask you to write a syntax for creating an Index.]

34. What is Covering Index?


- If all the columns that we have requested in the SELECT clause of query, are present in the
index, then there is no need to look up in the table again. The requested columns data can
simply be returned from the index.

A clustered index, always covers a query, since it contains all of the data in a table. A composite
index is an index on two or more columns. Both clustered and non clustered indexes can be
composite indexes. To a certain extent, a composite index, can cover a query.

35. Scenario : Interviewer may give you a table and a query and ask you for on which column
should I create a Clustered Index and Why?
Let’s say there is a Employee table with Id Column as a Primary Key :

We have below query in SP which is very slow :


SELECT Id, Name, Salary, Gender from Employee Where Salary BETWEEN 2500 AND 50000
- This query has more focus on Salary column so we should have something over Salary column
which will help this query to execute faster.
- Firstly we can go ahead and create a non clustered index on Salary Column and we will check
the results. If this works then we are good but if this fails then we have to go with creating
Clustered Index on Salary by removing Clustered Index from Primary Key Id Column. Which will
definitely helps this query to run faster.
36. What are Views? Indexed View? Advantages of Views?
- A view is nothing more than a saved SQL query.
- A view can also be considered as a virtual table.
- When we try to retrieve data from the view, the data is actually retrieved from the underlying
base tables. So, a view is just a virtual table it does not store any data, by default.
- However, when we create an index, on a view, the view gets materialized. This means, the view
is now, capable of storing data. In SQL server, we call them Indexed views.

Advantages of using views:

1. Views can be used to reduce the complexity of the database schema, for non IT users. For
example the view can hides the complexity of joins. Non-IT users, finds it easy to query the
view, rather than writing complex joins.
2. Views can provide row and column level security.
3. Views can be used to present only aggregated data and hide detailed data.

Row Level Security:


For example, I want an end user, to have access only to IT Department employees. If I grant
him access to the underlying tblEmployees and tblDepartments tables, he will be able to
see, every department employees. To achieve this, I can create a view, which returns only IT
Department employees, and grant the user access to the view and not to the underlying
table.

Column Level Security:


Salary is confidential information and I want to prevent access to that column. To achieve
this, we can create a view, which excludes the Salary column, and then grant the end user
access to these views, rather than the base tables.

37. Can we update underlying base tables through View? [Tricky question] Depending on your
answer he can ask you Single/Multiple base tables?
- Yes. We can update the base tables through a view if there is single underlying base table.
- For a view based on multiple base tables we can use instead of trigger to correctly update the
base table values.

38. What are Triggers? Different types of Triggers?


- A trigger is a special type of stored procedure that automatically executes when an event occurs
in the database server.
- There are different types of triggers :
1. DML Triggers which are again divided into Instead Of Triggers and After Triggers
2. DDL Triggers
3. Logon Triggers.
DML Triggers :
- DML stands for Data Manipulation Language.
- INSERT, UPDATE, and DELETE statements are DML statements.
- DML triggers are fired, whenever data is modified using INSERT, UPDATE, and DELETE events.
- DML triggers can be again classified into 2 types.
1. After triggers (Sometimes called as FOR triggers)
2. Instead of triggers

After triggers, as the name says, fires after the triggering action. The INSERT, UPDATE, and
DELETE statements, causes an after trigger to fire after the respective statements complete
execution.

On other hand, as the name says, INSTEAD of triggers, fires instead of the triggering action. The
INSERT, UPDATE, and DELETE statements, can cause an INSTEAD OF trigger to fire INSTEAD OF
the respective statement execution.

DDl Triggers :
- DDL triggers fire in response to DDL events - CREATE, ALTER, and DROP (Table, Function, Index,
Stored Procedure etc...).
- DDL Triggers again classified into 2 categories :
- Database Triggers : DDL Triggers specific to database.
- Server Scoped Trigger : When you create a server scoped DDL trigger, it will fire in response to
the DDL events happening in all of the databases on that server.

Use of DDL triggers :


- If you want to execute some code in response to a specific DDL event
- To prevent certain changes to your database schema
- Audit the changes that the users are making to the database structure

Logon Triggers :
- As the name implies Logon triggers fire in response to a LOGON event. Logon triggers fire after
the authentication phase of logging in finishes, but before the user session is actually
established.
- Logon triggers can be used for
1. Tracking login activity
2. Restricting logins to SQL Server
3. Limiting the number of session for a specific user
39. What are different magical/special tables available in Triggers?
- There are 2 magical tables available while working with triggers:
1. INSERTED Table
2. DELETED Table

Trigger INSERTED or DELETED?


Instead of DELETED table is always empty and the INSERTED table contains the
Insert newly inserted data.
Instead of INSERTED table is always empty and the DELETED table contains the
Delete rows deleted
Instead of DELETED table contains OLD data (before update), and inserted table
Update contains NEW data(Updated data)

40. Can I save activities of user on my database? If yes then how?


- Yes. We can save all activities of a user on a specific database or on all databases from a server.
- We can use DLL Trigger on a database or on a server to log the activities of user in a particular
table
[Note : Interviewer may ask you to write a syntax for creating database or server scoped DDL Trigger.]

41. Can we limit connections for a particular user? If yes then how?
- Yes. We can limit the connections for a particular user.
- We can use Logon Triggers to achieve this.
- [Note : Interviewer may extend his question by asking how to create that trigger. Remember the syntax of creating
LOGON Trigger.]

42. How Error handling done in SQL? Have you done error handling in your project?
- We use Try Catch block just like C# language to catch and handle the exceptions in SQL.
- We cannot use try catch blocks in functions.
- If we have to through error to calling application then we use RAISERROR function in catch
block.
- Also we specify ROLLBACK command in catch block when we are dealing with transactions.
- RAISEERROR Function is use to throw exception directly to the calling application.
Syntax of RAISEERROR Function is
RAISERROR('Error Message', ErrorSeverity, ErrorState)
- Severity and State are integers. In most cases, when you are returning custom errors, the
severity level is 16, which indicates general errors that can be corrected by the user.
- ErrorState is also an integer between 1 and 255. RAISERROR only generates errors with state
from 1 through 127.
43. What are transactions in SQL? What all commands used in Transaction?
- A transaction is a group of commands that change the data stored in a database.
- A transaction is treated as a single unit.
- A transaction ensures that, either all of the commands succeed, or none of them. If one of the
commands in the transaction fails, all of the commands fail, and any data that was modified in
the database is rolled back. In this way, transactions maintain the integrity of data in a database.
Transaction processing follows these steps:
1. Begin a transaction.
2. Process database commands.
3. Check for errors.
If errors occurred,
rollback the transaction,
else,
commit the transaction

- We use Commit command to commit the changes permanently to database and Rollback
command to rollback the changes on any error while working with transactions.

44. What are Cursors in SQL? Can you tell me what all steps are followed while using Cursors?
- If there is ever a need to process the rows, on a row-by-row basis, then cursors are your choice.
Cursors are very bad for performance, and should be avoided always. Most of the time, cursors
can be very easily replaced using joins.
There are different types of cursors in sql server as listed below.
1. Forward-Only
2. Static
3. Keyset
4. Dynamic

We use below steps while using the cursors :


- Declare the cursor
- Open statement
- Fetch the row from the result set into the variable
- @@Fetch_Status to check if result set still has rows
- Release the row set Deallocate the resources associated with the cursors.

[Note : If interviewer ask where did u use cursors in your project? Ans : I have never came across situation where I can
implement cursors in my project. Again they are bad over performance.]
45. What are Row_Number(), Rank(), Dense_Rank() functions?

Row_Number function

- Returns the sequential number of a row starting at 1


- ORDER BY clause is required
- PARTITION BY clause is optional
- When the data is partitioned, row number is reset to 1 when the partition changes

Syntax : ROW_NUMBER() OVER (ORDER BY Col1, Col2)

Rank function

- Rank function skips ranking(s) if there is a tie


- ORDER BY clause is required
- PARTITION BY clause is optional

Syntax : Rank() OVER (ORDER BY Col1, Col2)

Dense_Rank functions

- Dense_Rank function does not skips ranking(s) if there is a tie


- ORDER BY clause is required
- PARTITION BY clause is optional

Syntax : Dense_Rank() OVER (ORDER BY Col1, Col2)

46. What is Pivot and UnPivot in SQL?


- Pivot is a sql server operator that can be used to turn unique values from one column,
into multiple columns in the output, there by effectively rotating a table.
- UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued
expression into column values.
- In short, PIVOT operator turns ROWS into COLUMNS, whereas UNPIVOT turns COLUMNS into
ROWS.

47. How to delete duplicates rows from table.


with cte1
as
(
select Name,
ROW_NUMBER() over (partition by Name order by Name) As RowNumber
from sample1
)
delete from cte1
where RowNumber >=2
48. How to find nth highest salary from employees table (explain different ways).

1st way using SubQuery :

SELECT TOP 1 SALARY


FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY

2nd way using CTE :

WITH RESULT AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT TOP 1 SALARY
FROM RESULT
WHERE DENSERANK = N

[Please note we can use Row_Number() function over Dense_Rank() but if there are duplicates then Dense_Rank()
function gives correct output.]
49. Self Join query. Employee table will be given having EmployeeId and ManagerId columns and
ask you to fetch Employee Name and Manager Name.

Write a query which gives the following result.

- SELECT E.Name as Employee, ISNULL(M.Name,'No Manager') as Manager


FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

50. Advanced join queries? i.e. Finding just left table data or just right table data or uncommon
data from both the tables.

Did Dname
1 IT EId Ename Did
2 HR 1 a 1
3 ADMIN 2 b 1
4 NETWORK 3 c 2
4 d NULL
5 e 3
6 f 3

O/P :
Eid Ename
4 D

SELECT EId, EName


FROM tblEmployee E
LEFT JOIN tblDepartment D
ON E.DId = D.Id
WHERE D.DId IS NULL

O/P :

Eid Ename Did Dname


NULL NULL 4 NETWORK

SELECT EId, EName, D.Did, DName


FROM tblEmployee E
LEFT JOIN tblDepartment D
ON E.DId = D.Id
WHERE E.DId IS NULL

51. Convert rows into to the columns. (Pivot query)

Countries table in this example

- Write a sql query to transpose rows to columns. The output should be as shown
below.
Select Country, City1, City2, City3
From
(
Select Country, City,
'City'+
cast(row_number() over(partition by Country order by Country)
as varchar(10)) ColumnSequence
from Countries
) Temp
pivot
(
max(City)
for ColumnSequence in (City1, City2, City3)
) Piv

52. Query using Group by and aggregate functions. For example, 2 tables Employee and
Department and they can ask you to fetch Department Name With Employee Count, Or City
column with Employee Count.
-

Did Dname EId Ename Did


1 IT 1 a 1
2 HR 2 b 1
3 ADMIN 3 c 2
4 NETWORK 4 d NULL
5 e 3
6 f 3

Write a query to fetch department name and employee count if employee are not there in that
department it should give 0 count.

select d.DepartmentName, COUNT(e.ID) as EmployeeCount


from [dbo].[tblEmployee] e right join [dbo].[tblDepartment] d
on e.DepartmentId = d.Id
group by d.DepartmentName

Fetch IT department employee count.

select d.DepartmentName, COUNT(e.ID) as EmployeeCount


from [dbo].[tblEmployee] e right join [dbo].[tblDepartment] d
on e.DepartmentId = d.Id
group by d.DepartmentName
having d.DepartmentName = 'IT'

[Understand the above queries same queries can be asked with different table like Product and
ProductSales or Employee and Job Tables]

53. Find domain name from Email Id column, also find the Domain Name with Employee Count.
(Use Substring, CharIndex, Group By )

Write a query to find out total number of emails, by domain. The result of the query
should be as shown below.

Query
Select SUBSTRING(Email, CHARINDEX('@', Email) + 1,
LEN(Email) - CHARINDEX('@', Email)) as EmailDomain,
COUNT(Email) as Total
from tblEmployee1
Group By SUBSTRING(Email, CHARINDEX('@', Email) + 1,
LEN(Email) - CHARINDEX('@', Email))
Advanced Questions :

54. Table Hints in SQL


55. Isolation Level in SQL and its Types
56. Deadlocks
57. How to Handle Deadlocks
58. Profiler in SQL
59. Query Execution Plan
60. Few functions introduced in SQL 2012

You might also like