Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

SQL - Questions - Answers V3

Uploaded by

faisal.mulla008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

SQL - Questions - Answers V3

Uploaded by

faisal.mulla008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

SQL INTERVIEW QUESTIONS

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. The commands are
CREATE, ALTER, DROP, RENAME, and TRUNCATE.
Data Manipulation Language (DML) - These SQL commands are used for storing,
retrieving, modifying, and deleting data.
These Data Manipulation Language 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, and SAVEPOINT.
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
- 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.
- Delete is a DML command.
- We can undo the delete operation by using ROLLBACK transaction command.
- This operation causes all DELETE Triggers to fire on a table.
Truncate
- TRUNCATE removes all rows from a table.
- The operation cannot be rolled back and no triggers will be fired.
- TRUCATE is a DDL command and it is faster.
Drop
- 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.Thatswhy 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.Thatswhy TRUNCATE is
faster.Once you Truncate you cann't get back the data.]

1|Page
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 Microsoft SQL
Server should take when a user attempts to delete or update a key to which an
existing foreign keys points.
- We have the following options when setting up Cascading referential
integrity constraint
A. No Action: This is the default behavior. No Action specifies that if an attempt is
made to delete or update a row with a key referenced by foreign keys in existing
rows in other tables, an error is raised and the DELETE or UPDATE is rolled back.
B. Cascade: Specifies that if an attempt is made to delete or update a row with a
key referenced by foreign keys in existing rows in other tables, all rows containing
those foreign keys are also deleted or updated.
C. Set NULL: Specifies that if an attempt is made to delete or update a row with a
key referenced by foreign keys in existing rows in other tables, all rows containing
those foreign keys are set to NULL.
D. Set Default: Specifies that if an attempt is made to delete or update a row with a
key referenced by foreign keys in existing rows in other tables, all rows containing
those foreign keys are set to default values.

Or

5. If I have a primary key foreign key relationship in two tables. Can I delete foreign
key table values if I am deleting primary key table values? If yes then how?

Employee Table
EId EName Did
1 a 2
2 b 1
3 c 1
4 d NULL
5 e 3
Department Table
Did Dname
1 HR
2 IT
3 Admin

2|Page
Delete from Department where Did = 1
What will happen on execution of this query?
- This query will give us the error of primary key foreign key relationship violation.
- Though we have option to use Cascading referential integrity where we can change
this behavior.
[If interviewer asks you to explain then we can explain the answer from Question. 4]

6. 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.
-
7. 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

8. 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('TableName') - returns the last identity value that is created for a
specific table across any session and any scope.

9. 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)

10. 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 process of organizing data to minimize data
redundancy, which in turn ensures data consistency.
- There are 6 different forms of normalizations from First Normal Form thru Sixth
Normal Formmost of the databases are normalized till Normal form 3.
- A table is said to be in 1NF, if
1. The data in each column should be atomic. No multiple values, separated

3|Page
by comma.
2. The table does not contain any repeating column groups
3. Identify each record uniquely using primary key.
- A table is said to be in 2NF, if
1. The table meets all the conditions of 1NF
2. Move redundant data to a separate table
3. Create relationship between these tables using foreign keys.
- A table is said to be in 3NF, if the table
1. Meets all the conditions of 1NF and 2NF
2. Does not contain columns (attributes) that are not fully dependent upon
the primary key.

11. Difference between Where and Having clause?


- 1. WHERE clause can be used with - Select, Insert, 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.

12. 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–This joins returns only the matching rows from both the tables.
Left Outer Join - This joins returns matching rows from both the tables and non
matching rows from the left table.
Right Outer Join - This joins returns matching rows from both the tables and non
matching rows from the right table.
Full Outer Join - This joins returns all the rows from both the tables as well as all non
matching rows.
Cross Join – This join returns Cartesian product of the tables involved in the join.

13. 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.

4|Page
- 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

5|Page
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

14. What are different ways to replace NULL values?


- We can replace NULL value using 3 different options :
A. Using ISNULL function(refer Question No 13 for query)
B. Using case statement(refer Question No 13 for query)
C. Using Coalesce() function - COALESCE() returns the first Non NULL value.
[Please prepare for the syntax also]
15. 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, Data types, and the order of the
columns in the select statements should be same.
- UNION removes duplicate rows, whereas UNION ALL does not.
- When we use UNION, to remove the duplicate rows, sql server has to to do a distinct
sort, which is time consuming. For this reason, UNION ALL is much faster than
UNION.

16. 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.

17. 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 :
1. Non Correlated SubQuery :
- Sub query is executed first and only once. The sub query results are then used by the
outer query.
- A non-correlated subquery can be executed independently of the outer query.

2. Correlated SubQuery :
- If the subquery depends on the outer query for its values, then that sub query is
called as a correlated subquery.
- Correlated subqueries get executed, once for every row that is selected by the outer
query.
- Corelated subquery, cannot be executed independently of the outer query.

18. What are stored procedures? Explain its advantages?

6|Page
- 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.

19. Write SQL statement to call a Stored Procedures with Output parameter.
- Let’s say there is stored procedure spGetTotalCountOfEmployees with
@TotalCount output parameter. We can call this procedure as :
Declare @TotalEmployees int
Execute spGetTotalCountOfEmployees @TotalEmployees Output
Select @TotalEmployees

20. What is difference between Output Parameter and Return values in Stored
Procedures?
- Using return values, we can only return integers, and that too, only one integer.
- It is not possible, to return more than one value using return values, whereas output
parameters, can return any datatype and an SP can have more than one output
parameters.
- 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.

7|Page
- 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 CURRENT_TIMESTAMP, RAND()

23. What id RAND() function? What if you pass it a parameter e.g. RAND(1) ?
- Rand() function is a Non-deterministic function, 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.
The function body is not enclosed between BEGIN and END block. 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 specify the structure of the table that
gets returned

8|Page
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 columnsname list)
AS
BEGIN
--Insert into @Table
RETURN
END
26. What is difference between Inline Table Valued Function and MultiStatement 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?


- 1. Stored Procedure support deferred name resolution whereas functions do not
support deffered name resolution.
2. User Defined Function can be used in a select statement where as you cannot use

9|Page
a stored procedure in a select statement.
3. UDF's cannot return Image, Text where as a StoredProcedure can return any
datatype.
4. In general, User Defined Functions are used for computations whereas Stored
Procedures are used for performing business logic.
5. UDF should return a value whereas Stored Procedure need not.
6. User Defined Functions accept lesser number of input parameters than Stored
Procedures. UDF can have upto 1023 input parameters whereas aStored
Procedure can have upto 21000 input parameters.
7. Temporary Tables cannot be used in a UDF where as a StoredProcedure can use
Temporary Tables.
8. UDF cannot Execute Dynamic SQL where as a Stored Procedure can execute
Dynamic SQL
9. User Defined Function does not support error handling whereas Stored
Procedure supports error handling. RAISEERROR or @@ERROR are not allowed
in UDFs.

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


- Temporary tables are very similar to the permanent tables. Permanent tables get
created in the database you specify, and remain in the database permanently, until
you delete (drop) them. On the other hand, 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 2 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) NOTNULL,
City varchar(30) NOTNULL
);

INSERTINTO @userData
SELECT name, city FROM Employees

10 | P a g e
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?
- 1. Table variable is created in the memory where as a temporary table is created in
the TempDB. But, if there is a memory pressure, the pages belonging to a table
variable may be pushed out to tempdb.
2. Table variables cannot be involved in transactions, logging or locking. This makes
table variable faster than a temporary table.
3. You can pass table variable as parameter to functions and stored procedures,
where as you cannot do the same with temporary table.
4. 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 @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

11 | P a g e
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 nonclustered 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
nonclustered 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 :

12 | P a g e
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.
- A standard or Non-indexed view is just a stored SQL query. 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 be used as a mechanism to implement row and column level security.
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.

3. Views can be used to present only aggregated data and hide detailed data.

13 | P a g e
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 kind 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.

14 | P a g e
- 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
Insert contains the newly inserted data.
Instead of INSERTED table is always empty and the DELETED table
Delete contains the rows deleted
Instead of DELETED table contains OLD data (before update), and inserted
Update table 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 RAISEERROR 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?

15 | P a g e
- 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)

16 | P a g e
Rank and Dense_Rank functions

- Returns a rank starting at 1 based on the ordering of rows imposed by the ORDER BY
clause
- ORDER BY clause is required
- PARTITION BY clause is optional
- When the data is partitioned, rank is reset to 1 when the partition changes
- Difference between Rank and Dense_Rank functions
- Rank function skips ranking(s) if there is a tie where as Dense_Rank will not.

Difference between RANK, DENSE_RANK and ROW_NUMBER functions


- ROW_NUMBER : Returns an increasing unique number for each row starting at 1,
even if there are duplicates.
- RANK : Returns an increasing unique number for each row starting at 1. When there
are duplicates, same rank is assigned to all the duplicate rows, but the next row after
the duplicate rows will have the rank it would have been assigned if there had been
no duplicates. So RANK function skips rankings if there are duplicates.
- DENSE_RANK : Returns an increasing unique number for each row starting at 1.
When there are duplicates, same rank is assigned to all the duplicate rows but the
DENSE_RANK function will not skip any ranks. This means the next row after the
duplicate rows will have the next rank in the sequence.

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.

Basic guidelines followed while designing database. (Google it. Or I will provide you
the list of basic guidelines.)

Queries – Please note, below are the questions will be asked based on a given sample table.
They will not always ask you to use direct concept but you have to think of the concept how
to achieve the given output.

47. How to delete duplicates rows from table.


withcte1
as
(
selectName,
ROW_NUMBER()over (partitionbyNameorderbyName)AsRowNumber
fromsample1
)
deletefromcte1
whereRowNumber>=2
48. How to find nth highest salary from employees table (explain different ways).

17 | P a g e
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.

18 | P a g e
- 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
2 HR
3 ADMIN
4 NETWORK

EId Ename Did


1 a 1
2 b 1
3 c 2
4 d NULL
5 e 3
O/P :
6 f 3
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

19 | P a g e
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 or
der 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.

selectd.DepartmentName,COUNT(e.ID)asEmployeeCount

20 | P a g e
from[dbo].[tblEmployee]erightjoin[dbo].[tblDepartment]d
one.DepartmentId=d.Id
groupbyd.DepartmentName

Fetch IT department employee count.

selectd.DepartmentName,COUNT(e.ID)asEmployeeCount
from[dbo].[tblEmployee]erightjoin[dbo].[tblDepartment]d
one.DepartmentId=d.Id
groupbyd.DepartmentName
havingd.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 :

21 | P a g e
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

22 | P a g e

You might also like