SQL Server Interview Questions & Answers Book
SQL Server Interview Questions & Answers Book
All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.
The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or Dot
Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly or
indirectly by this book.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
• Initial Release 1.0 - 23rd Nov 2018
• Second Release 1.1 - 21st Dec 2018
• Third Release 1.2 - 4th Jan 2019
• Fourth Release 1.3 - 31st Jan 2019
1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), in Jan 2010. Dot Net Tricks came into existence
in form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET MVC, JavaScript,
Angular, Node.js and Visual Studio etc.
The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into the shape
in 2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of trust
in other technologies. This is what we are striving for.
We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in form of articles.
For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 16-weekend classes (2 months).
Hands-On Learning courses give you the confidence to code and equally helpful to work in real-life scenarios. This
course is composed of hands-on exercise using IDE or cloud labs so that you can practice each and everything by
yourself. You can learn to code at your own pace, time and place.
The detail about Hands-On Learning courses can be found here: https://www.scholarhat.com
Professionals who don’t have two months’ time and want to get skilled up in least possible time due to some new
project that their company has to take in very near future, we have designed Skill Bootcamps Concept, where you
will get trained on consecutive days in a fast-paced manner, where our full focus is going to be on hands-on
delivery of technological exercises.
Self-paced Courses
2
Self-paced courses give you the liberty to study at your own pace, time and place. We understand everyone has
Page
their own comfort zone, some of you can afford to dedicate 2 hours a day, some of you not. Keeping this thing in
mind, we created these self-paced courses. While creating these courses we have ensured that quality of courses
doesn’t get compromise at any parameter, and they also will be able to produce the same results as our other
course formats, given the fact you will be able to put your own honest effort.
Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing technology landscape. Dot Net Tricks offers customized training programs for new hires and experienced
employees through online and classroom mode. As a trusted and resourceful training partner, Dot Net Tricks helps
the corporate to achieve success with its industry-leading instructional design and customer training initiatives.
Learning Platform
We have a very robust technology platform to answer the needs of all our trainees, no matter which program they
enrolled in. We have a very self-intuitive Learning Management System (LMS), which help you in remain focused
and keeping an eye over your progress.
Apart from these, we also provide on-demand Skill bootcamps and personalized project consultation.
3
Page
Dedication
My mother Mrs Vriksha Devi and my wife Reshu Chauhan deserve to have their name on the cover as
much as I do for all their support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my articles at https://www.dotnettricks.com/mentors/shailendra-chauhan to
encourage me to write this book.
-Shailendra Chauhan
4
Page
Introduction
If you are looking for a book on SQL Server interview, you’ve come across the right book. This is the book which
will master you SQL Server fundamentals. This book will teach you the SQL Server from scratch so that you have
the confidence to give the answer of all the questions being asked in your interview.
This book is designed specifically to teach you the DBMS and RDBMS concepts along with SQL server features.
This book covers database concepts, SQL queries, SQL statements, functions, procedures, cursor, triggers and
exception handling.
So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being a consultant,
corporate trainer, and blogger, I have thorough knowledge and understandings of .NET technologies. My
inspiration and knowledge have also come from many years of my working experience and research over it.
So, the next question is who this book is for? This book is best suited for beginners and professionals. It is
intended for anyone who so far has not engaged seriously in SQL and SQL Server and would like to start a career
in Database. This book covers the mainly following topics.
This book is not only the SQL Server interview book but it is more than that. This book helps you to get an in-depth
knowledge of SQL Server with a simple and elegant way.
To get the latest information on SQL Server, I encourage you to follow the official Microsoft document website at
https://www.microsoft.com/en-us/sql-server/sql-server-2017.
He has changed many lives from his writings and unique training programs.
He has a number of most sought-after books to his name which have helped
job aspirants in cracking tough interviews with ease.
Moreover, and to his credit, he has delivered 1000+ training sessions to professionals worldwide in Microsoft
.NET technologies and other technologies including JavaScript, AngularJS, Node.js, React and NoSQL Databases.
In addition, he provides Instructor-led online training, hands-on workshop and corporate training programs.
Shailendra has a strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to world-renowned status, placing
him at the top of the list of most sought-after trainers.
“I always keep up with new technologies and learning new skills to deliver the best to my students,” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.
Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
6
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.
• [email protected]
• [email protected]
We are always happy to hear from our readers. Please provide your valuable feedback and comments!
You can follow us on YouTube, Facebook, Twitter, LinkedIn and Google Plus or subscribe to RSS feed.
7
Page
Table of Contents
SQL Server Interview Questions & Answers ................................................................... 1
Release History ....................................................................................................................................................1
About Dot Net Tricks ...........................................................................................................................................2
Dot Net Tricks Training Solutions .........................................................................................................................2
Dedication ...........................................................................................................................................................4
Introduction ........................................................................................................................................................5
About the Author ................................................................................................................................................6
How to Contact Us...............................................................................................................................................7
Q6. What are the differences between varchar and nvarchar? .................................................................... 23
Page
Q7. What are the differences between varchar(MAX) and text? .................................................................. 23
Q8. What is SQL key? ..................................................................................................................................... 23
Q9. What are different types of SQL Keys? .................................................................................................... 23
Q10. Can you define all the keys in a database table? .................................................................................... 24
Q11. What are the differences between Primary Key and Unique Key? ......................................................... 24
Q12. How to define Primary Key and Unique Key? ......................................................................................... 25
Q13. What is the difference between Primary Key and Foreign Key? ............................................................. 25
Q14. How to define Primary Key and Foreign Key? ......................................................................................... 25
Q15. What are SQL Commands? ...................................................................................................................... 26
Q16. What are different types of SQL Commands? ......................................................................................... 26
Q17. What are DDL Commands? ..................................................................................................................... 26
Q18. What are DML Commands?..................................................................................................................... 27
Q19. What are DQL Commands? ..................................................................................................................... 27
Q20. What are TCL Commands? ...................................................................................................................... 27
Q21. What are DCL Commands? ...................................................................................................................... 27
Q22. What is Grant and Revoke Commands? .................................................................................................. 27
Q23. What are SQL Constraints or SQL Integrity Constraints? ........................................................................ 27
Q24. What are different types of SQL Constraints or SQL Integrity Constraints? ........................................... 27
Q25. What is Database Table? ......................................................................................................................... 29
Q26. What is View? .......................................................................................................................................... 29
Q27. What is the need for a SQL view?............................................................................................................ 30
Q28. What are different types of SQL Server Views? ...................................................................................... 30
Q29. What is Simple View and Complex View? ............................................................................................... 31
Q30. What is a transaction? ............................................................................................................................. 31
Q31. Why use transaction in SQL Server? ........................................................................................................ 31
Q32. What are different types of transaction in SQL Server?.......................................................................... 31
Q33. What are implicit and explicit transactions in SQL Server? ..................................................................... 31
Q34. How to use an explicit transaction in SQL Server? .................................................................................. 32
Q2. Explain the life cycle of the cursor in SQL Server? .................................................................................. 64
Q3. What are different types of Cursor in SQL Server? ................................................................................. 65
Q4. What is Static Cursor in SQL Server? ....................................................................................................... 65
Q5. How to write a Static Cursor in SQL Server? ........................................................................................... 65
Q6. What are the limitations of a Static Cursor in SQL Server? ..................................................................... 66
Q7. What is Dynamic Cursor in SQL Server? .................................................................................................. 66
Q8. How to write a Dynamic Cursor in SQL Server? ...................................................................................... 66
Q9. What is Forward Only Cursor in SQL Server? .......................................................................................... 67
Q10. How to write a Forward only Cursor in SQL Server? ............................................................................... 67
Q11. What is Keyset-Driven Cursor in SQL Server?.......................................................................................... 68
Q12. How to write a Keyset-driven Cursor in SQL Server? .............................................................................. 69
Q13. What are SQL Server cursor alternatives?............................................................................................... 69
Q14. How XML data type works in SQL Server?............................................................................................... 70
Q15. What are the limitations of the XML data type in SQL Server?............................................................... 70
Q16. What are various ways for querying XML data? ..................................................................................... 70
Q17. What is an index? .................................................................................................................................... 72
Q18. What are the advantages of the index? .................................................................................................. 72
Q19. What are different types of indexes? ...................................................................................................... 72
Q20. What is a Clustered index? ...................................................................................................................... 72
Q21. What is a Non-Clustered index? .............................................................................................................. 72
Q22. What is full-text search in SQL Server? ................................................................................................... 73
References ..................................................................................................................... 74
12
Page
1
Introducing SQL Server
Q1. What is SQL Server?
Ans. Microsoft SQL Server is a Relational Database Management System (RDBMS) developed by Microsoft. It
is designed to run on a central server so that multiple users can access the same data simultaneously. Generally,
users access the database through an application.
Q3. What is the default running port for a default SQL Server instance?
Ans. The default running port number for the default instance of SQL Server is 1433. The named instances can
be configured on dynamic ports.
• Master
• TempDB
13
• Model
• MSDB
Page
• Resource DB
Q5. What is a master database in SQL Server?
Ans. The Master database contains the system level information like system configuration details, database
information, login account information. login user details for SQL Server. The following database tables are
generally used for checking all these details.
Select * from SYSCONFIGURES -- for System configuration
Primary data of Master database is stored in master.mdf file which default size is 11 MB and Master database log
are stored in masterlog.ldf file which default size is 1.25 MB.
For Example - #Student table gets created as a temporary table in the school database.
Use School
CREATE TABLE #Student
(
StudentID int
Name Varchar(50)
)
TempDB database is recreated every time when the instance of SQL Server has been restarted. Hence, every time
temporary objects will be removed from the tempDB database.
Primary data of the tempDB database is stored in tempDB.mdf file which default size is 8 MB and tempDB database
log is stored in templog.ldf file which default size is 0.5MB.
Primary data of the model database is stored in the model.mdf file which default size is 0.75 MB and model
database log is stored in modellog.ldf which default size is 0.75MB.
For Example- When you create a database maintenance plan for taking backup of a specific database on a daily
Page
basis, then this scheduled job will be stored in system-defined table “SYSJOBS” in MSDB database.
Primary data of Msdb database is stored in msdbdata.mdf file which default size is 12 MB and Msdb database log
are stored in msdblog.ldf which default size is 2.25MB.
Q12. Can you access or query remote SQL Server database from a Mac, Linux
or Ubuntu machine?
Ans. Yes, you can connect or query your remote SQL Server database from your Mac, Linus or Ubuntu
machines using Azure Data Studio tool.
Azure Data Studio offers a modern editor experience to connect with a remote SQL Server database. It helps us
to query and manage data across multiple sources with intellisense.
15
Page
2
Database Basics
Q1. What is the difference between DBMS and RDMS?
Ans. DBMS and RDBMS, both are used to store, manage and query the data. But both have some important
differences as listed below-
A good database design implements normalization practices to make a database system fast, efficient and to
produce the expected result.
Ans. We organize the data into database tables by using normal forms rules or conditions. Normal forms help
us to make a good database design. There are following normal forms:
Page
1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
4. BCNF
5. Fourth Normal Form (4NF)
6. Fifth Normal Form (5NF)
Generally, we organize the data up to third normal form. We rarely use the fourth and fifth normal form.
First Normal Form (1NF) - A database table is said to be in 1NF if it contains no repeating fields/columns. The
process of converting the UNF table into 1NF is as follows:
• Separate the repeating fields into the new database tables along with the key from a un-normalized
database table.
• The primary key of new database tables may be a composite key
• Remove the partial dependencies (A type of functional dependency where a field is only functionally
dependent on the part of primary key) of any non-key field.
• If field B depends on field A and vice versa. Also, for a given value of B, we have only one possible value
of A and vice versa, Then we put the field B into new database table where B will be the primary key and
also marked as a foreign key in the parent table.
18
Page
2NF of above 1NF tables is as follows:
Third Normal Form (3NF) - A database table is said to be in 3NF if it is in 2NF and all non-keys fields should be
dependent on primary key or We can also say a table to be in 3NF if it is in 2NF and no fields of the table is
transitively dependent on the primary key. The process of converting the table into 3NF is as follows:
• Remove the transitive dependencies (A type of functional dependency where a field is functionally dependent
on the Field that is not the primary key. Hence its value is determined, indirectly by the primary key).
• Make a separate table for transitive dependent Field.
19
Page
3NF of above 2NF tables is as follows:
Boyce Code Normal Form (BCNF) - A database table is said to be in BCNF if it is in 3NF and contains each and every
determinant as a candidate key. The process of converting the table into BCNF is as follows:
21
Page
Fifth Normal Form (5NF) - A database table is said to be in 5NF if it is in 4NF and contains no redundant values or
We can also say a table to be in 5NF if it is in 4NF and contains no join dependencies. The process of converting
the table into 5NF is as follows:
char - This is a fixed length characters data type. It takes one byte per character and used to store non-Unicode
characters.
Suppose, you declare a field with char(20) then it will allocate memory for 20 characters whether you are using
only 10 characters. Hence memory for 10 characters which is empty will be wasted.
22
nchar - This is like as char data type but it takes two bytes per character and used to store Unicode characters
Page
means multiple languages (like Hindi, Chinese etc.) characters in the database.
Q6. What are the differences between varchar and nvarchar?
Ans. There are following differences between varchar and nvarchar:
varchar - This is a variable length characters data type. It takes one byte per character and can store non-Unicode
characters (like English). This data type allocates the memory based on a number of characters inserted. Hence,
no wastage of memory.
nvarchar – This is like as char data type but it takes 2 bytes per character and used to store Unicode characters
means multiple languages (like Hindi, Chinese etc.) characters in the database.
The TEXT type always stores the data in a blob while the VARCHAR(MAX) type store the data directly into the table
row. When stored data size exceeds the 8000 characters in VARCHAR(MAX), it stores the data in a blob just like
TEXT type.
The TEXT is used when you do not require search on the value of a column and you don’t have any plan to use it
in the join. But VARCHAR (MAX) column can be used in join and you can do a search on the column value.
1. Super Key - A Super key is a set of one or more than one keys that can be used to identify a record uniquely
in a database table.
For Example: Primary key, Unique key, Alternate key are a subset of Super Keys.
2. Candidate Key - A Candidate key is a set of one or more fields/columns that can identify a record uniquely
in a database table. There can be multiple Candidate keys in one database table and each of them can
work as a Primary Key.
For Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields can
be work as Primary Key.
3. Primary Key - A Primary key is a set of one or more fields/columns in a database table that can identify a
record uniquely. It cannot accept null and duplicate values. A Candidate Key can become a Primary Key.
23
4. Alternate key - An Alternate key is a key that can work as a primary key if needed. Basically, it is a
Page
6. Unique Key - A Unique key is a set of one or more fields/columns of a database table that can identify a
record uniquely. It is like a Primary key but it can accept only one null value. It cannot have duplicate
values.
7. Foreign Key - A Foreign Key is a field/column in a database table that is Primary key in another database
table. Unlike, primary key it can accept multiple null values and duplicate values.
For Example: You can have a DeptID column in the Employee table which is pointing to the DeptID column
in a department table where it a primary key.
Q11. What are the differences between Primary Key and Unique Key?
Ans. In SQL Server, we have two keys which distinctively or uniquely identify a record in the database. Both the
keys seem identical, but actually, both are different in features and behaviours.
Q13. What is the difference between Primary Key and Foreign Key?
Ans. The difference between Primary Key and Foreign Key is given below-
(
EmpID int PRIMARY KEY, --define a primary key
Page
For Example:
--Here "TABLE" is a keyword that is used to create table "TABLE_NAME"
CREATE TABLE TABLE_NAME
(
COL1 VARCHAR(10),
COL2 VARCHAR(20),
);
Note
• Only with DDL commands you need to write keyword (like table, procedure, view, index, function) with
the syntax of the command.
• These commands are used only to create/modify the structure of the database object.
26
Page
Q18. What are DML Commands?
Ans. DML commands are used to store, modify, and delete data from database tables. The DML commands are
INSERT, UPDATE, and DELETE commands.
• Grant Command: This command is used to give permission to specific users on specific database objects
like table, view etc.
• Revoke Command: This command is used to take out permission from specific users on specific database
objects like table, view etc.
1. Column Level - These constraints are defined with the column definition inside a CREATE TABLE
statement.
2. Table Level - These constraints are defined after the table created using the ALTER TABLE statement.
Q24. What are different types of SQL Constraints or SQL Integrity Constraints?
Ans. In SQL Server, there are six types of SQL Constraints as given below:
1. Primary Key Constraints - A Primary key is defined as one or more fields/columns of a database table
that identify each record in a database table uniquely. It cannot accept null and duplicate values.
• Primary key constraint at column level
27
2. Unique Key Constraints - A Unique key is a set of one or more fields/columns of a database table that can
identify a record uniquely. It is like a Primary key but it can accept only one null value. It cannot have
duplicate values.
• Unique key constraint at the column level
3. Foreign Key Constraints - A Foreign Key is a field/column in a database table that is Primary key in another
database table. Unlike, primary key it can accept multiple null values and duplicate values.
• Foreign key constraint at column level
4. Not Null Constraints - This constraint ensures a field/column cannot accept a null value.
Page
5. Check Constraints - This constraint is used to define a business rule at a field/column in the database
table that each record in the database table must follow.
Ans. Views are virtual tables that are compiled at runtime. The data associated with views are not physically
Page
stored in the view, but it is stored in the base tables of the view. A view can be made over one or more database
tables. Generally, we put those columns in view that we need to retrieve/query again and again. Once you have
created the view, you can query view like as table. We can make an index, trigger on the view.
Syntax:
CREATE VIEW view_name
AS
select_statement[]
• We make views for security purpose since it restricts the user to view some columns/fields of the table(s).
• One more advantage of Views is, data abstraction since the end user is not aware of all the data present in
database table
1. System Defined Views- System defined Views are predefined Views that already exist in the Master database
of SQL Server. These are also used as template Views for all newly created databases. These system Views
will be automatically attached to any user-defined database.
2. User Defined Views - These types of view are defined by users. We have two types of user-defined views.
30
a. Simple View
b. Complex View
Page
Q29. What is Simple View and Complex View?
Ans. The simple view and complex views are given below:
• Simple View - When we create a view on a single table, it is called a simple view.
In a simple view, we can insert, update, and delete data. We can only insert data in a simple view if we have
a primary key and all not null fields in the view.
• Complex View - When we create a view on more than one table, it is called complex view.
We can only update data in the complex view. We can't insert, delete data in the complex view.
• Implicit Transaction
• Explicit Transaction
31
Ans. The implicit transaction and explicit transactions are explained as:
1. Implicit Transaction - Implicit transactions are maintained by SQL Server for each and every DDL (CREATE,
ALTER, DROP, TRUNCATE), DML (INSERT, UPDATE, DELETE) statements.
All these T-SQL statements run under the implicit transaction. If there is an error occurs within these
statements individually, SQL Server will roll back the complete statement.
2. Explicit Transaction - Explicit transactions are defined by programmers. In Explicit transaction, we include
the DML statements that need to be executed as a unit.
A SELECT statement does not modify data. Hence generally we don’t include only a Select statement in a
transaction.
For Example:
32
Page
3
SQL Queries
Q1. Write SQL Query to calculate running total, the total of a column and
row?
Ans. Suppose you have the following table in the database.
Suppose you want to reseed the Employee table ID field from 5 then the new records will be inserted with ID
6,7,8..and so on.
--Reseeding the identity
34
Q5. Write SQL queries to drop all tables, procedure, views and triggers in SQL
Server?
Ans. The queries are given below-
Close cur
Deallocate cur
Q6. Write SQL queries to get the nth highest and lowest salary of an
employee?
Ans. The queries are given below-
Q7. Write SQL query to get field name, data type and size of a database
table?
Ans. The query is given below-
36
Q8. Write a SQL query to remove duplicate records from a table in SQL
Server?
Ans. Suppose, you have following data in Employee table then query for removing duplicate records is given
below-
AS duplicateRecCount
FROM dbo.Employee
Page
)
--Now Delete Duplicate Records
DELETE FROM TempEmp
WHERE duplicateRecCount > 1
Q9. Write SQL query to create a comma-separated list from the column?
Ans. The query is given below-
Ans. To stop SQL Server for sending unwanted emails we required to clean the unsent mail from database
email queue. We can do this by running below queries.
-- To get number of unsent emails
select count(*) from msdb.dbo.sysmail_unsentitems;
Now, all the unexpected emails have been removed from the SQL Server database mail queue.
38
Page
4
SQL Statements
Q1. What are SQL Joins?
Ans. SQL joins are used to retrieve data from two or more data tables, based on a join condition. A join
condition is a relationship among some columns in the data tables that take part in SQL join.
• Inner Join
• Outer Join
• Cross Join
1. Inner Join - Inner join returns only those records/rows that match/exists in both the tables.
Syntax
2. Outer Join – There are three types of Outer join as given below-
• Left Outer Join - Left outer join returns all records/rows from the left table and from right table returns
only matched records. If there are no columns matching in the right table, it returns NULL values.
Syntax:
• Full Outer Join - Full outer join combines left outer join and right outer join. This join returns all
records/rows from both the tables. If there are no columns matching in both tables, it returns NULL
values.
Syntax:
3. Cross Join - Cross join is a Cartesian join means the Cartesian product of both the tables. This join does not
need any condition to join two tables. This join returns records/rows that are a multiplication of record
number from both the tables means each row on the left table will be related to each row of the right table.
Syntax:
Suppose, you have the following table emp and id is primary, supid is a foreign key on the same table emp.
Now, to get the supervisor name of each employee, you need to write the SQL query as given below-
Output:
41
Page
Q5. What is the difference between inner join and equi-join?
Ans. SQL join clause is used to retrieve data from two or more database tables.
Inner Join- This is the most used join in the SQL. This join returns only those records/rows that match/exists in
both the database tables.
For Example:
SELECT * FROM tblEmp JOIN tblDept
ON tblEmp.DeptID = tblDept.DeptID
In the join condition, you can also use other operators like <,>, <>.
Equi Join - Equi join is a special type of join in which we use only equality operator. Hence, when you make a query
for join using equality operator then that join query comes under Equi join.
For Example:
SELECT * FROM tblEmp JOIN tblDept
ON tblEmp.DeptID = tblDept.DeptID;
Note:
• Inner join can have equality (=) and other operators (like <,>, <>) in the join condition.
• Equi join only have equality (=) operator in the join condition.
• Equi join can be an Inner join, Left Outer join, Right Outer join
• The USING clause is not supported by SQL Server and Sybase. This is supported by Oracle and
42
MySQL.
Page
Q6. What is Natural Join?
Ans. Natural join is a type of equi join which occurs implicitly by comparing all the same names columns in both
tables. The join result has only one column for each pair of equally named columns.
For Example
--Run in Oracle and MySQL
SELECT * FROM tblEmp NATURAL JOIN tblDept
In the above join result, we have only one column "DeptID" for each pair of equally named columns.
Note
• In a Natural join, you can't see what columns from both the tables will be used in the join. In a Natural join,
you might not get the desired result what you are expecting.
• Natural join clause is not supported by SQL Server; it is supported by Oracle and MySQL.
Q7. How Group by and Having Clause are related to each other?
Ans. Group By - Group by clause is used for grouping the records of the database table(s). This clause creates
a single row for each group and this process is called aggregation. To use group by clause we have to use at least
one aggregate function in the Select statement. We can use group by clause without where clause.
For Example:
-- Group By clause without where the condition
SELECT st_Name, SUM(st_Marks) AS 'Total Marks'
FROM StudentMarks
GROUP BY st_Name;
Having Clause - This clause operates only on group rows of the table(s) and acts as a filter like as where clause.
We use having a clause to filter data that we get from the group by clause. To use having a clause, first we need
43
Note
SQL Injection arises since the fields available for user input allow SQL statements to pass through and query the
database directly.
For Example:
Now let’s look at the following query string in ASP.net. In this we are passing username from TextBox "txtUserID"
and userpwd from TextBox "txtpwd" to check user credential.
"SELECT * FROM tbluser WHERE userName = '"+ txtUserID.text +"' and userpwd = '"+
txtPwd.text +"'"
44
Now, the hacker will pass the following input to TextBoxes to inject sql attack. What will happen when the below
data goes as input?
Page
"SELECT * FROM tbluser WHERE userName = ';Drop table tblusers --' and userpwd = '123'";
Semicolon (;) in above statement will terminate the current SQL. So, "SELECT * FROM tbluser WHERE UserID = ''"
will become a separate statement and after Semicolon (;) it will start a new SQL statement "Drop table tblusers"
that will drop our table tbluser. Hence your user details table has been dropped and your database will be
unmanaged.
Q10. What are the recommended solutions to stop SQL Injection Attacks?
Ans. Some of the recommended solutions for SQL injection attacks are given below-
1. In C# or VB.NET Framework during building a SQL Statement, use the SqlParameter to define the
Parameter Name, type, and value instead of making a straight command like as above
2. In ASP.NET query specify that CommandType as Text or Stored Procedure.
3. When we use the Parameters Collection, we should use parameters the type and size will also be mention.
4. If we use a stored procedure, instead of directly building by using Exec command, use the sp_executesql
command.
5. Another way to stop SQL injection attacks is to filter the user input for SQL characters. Use the REPLACE
function to replace any apostrophe (single quotation mark to SQL) with an additional apostrophe. Within
a SQL string, two consecutive single quotation marks are treated as an instance of the apostrophe
character within the string.
45
Page
5
Functions, Procedures and
Exceptions
Q1. What is SQL function?
Ans. A function is a database object in SQL Server. Basically, it is a set of SQL statements that accept only input
parameters, perform actions and return the result. The function can return only a single value or a table. We can’t
use the function for Insert, Update and Delete records in the database table(s).
1. System Defined
2. User Defined
• Scalar Function - Scalar functions operate on a single value and return a single value. Below is the list
of some useful SQL Server Scalar functions.
convert(int, 15.56) This will convert the given float value to integer means 15.
• An aggregate Function- Aggregate function operates on a collection of values and returns a single
value. Below is the list of some useful SQL Server Aggregate functions.
• Scalar Function – A User-defined scalar function returns a single value. It can return any data type
value from a function.
• Inline Table-Valued Function – A User-defined inline table-valued function returns a table variable.
The returned table variable value should be derived from a single SELECT statement.
GO
--Calling the above-created function
Select * from fnGetEmployee()
47
Page
• Multi-Statement Table-Valued Function - A User-defined multi-statement table-valued function
returns a table variable. In this, a table variable must be declared explicitly and the return value can
be derived from multiple SQL statements.
1. System Defined Stored Procedure – These types of stored procedures are already defined within SQL
Page
Server. In fact, they are the part of sys schema of each database in SQL Server. This procedure starts with
the sp_ prefix. So, as a best practice, you should not use an sp_ prefix when naming a user-defined
procedure. Here is a list of some useful system defined procedure.
sp_rename It is used to rename a database object like stored procedure, views, table
etc.
sp_changeowner It is used to change the owner of a database object.
sp_help It provides details on any database object.
sp_helpdb It provides the details of the databases defined in the SQL Server.
sp_helptext It provides the text of a stored procedure reside in SQL Server
sp_depends It provides the details of all database objects that depend on the specific
database object.
2. Extended Stored Procedure – Extended procedures provide an interface to external programs for various
maintenance activities. These extended procedures start with the xp_ prefix and stored in Master
Database. Basically, these are used to call programs that reside on the server automatically from a stored
procedure or a trigger run by the server.
For Example- Below statements are used to log an event in the NT event log of the server without raising
an error on the client application.
3. Use Defined Stored Procedure - These procedures are created by the user for own actions. These can be
created in all system databases except the Resource database or in a user-defined database.
4. CLR Stored Procedure - CLR stored procedure is introduced with SQL Server 2008 which are based on the
CLR in .NET framework. They enable the procedure to be written in one of the .NET languages like C#,
Visual Basic and F#.
• We can nest stored procedures and managed code references in SQL Server up to 32 levels only. This is
also applicable for function, trigger and view.
• The current nesting level of the execution of a stored procedure is stored in the @@NESTLEVEL function.
• In SQL Server stored procedure nesting limit is up to 32 levels, but there is no limit on the number of
49
There are following differences between stored procedure and functions as given below –
Can return zero or n values. Must return a value but only one.
Can have input and output parameters. Can have only input parameters.
Cannot be called from function. Can be called from another function or a stored
procedure.
Allows SELECT as well as DML( INSERT/ UPDATE/ Allows only SELECT statement
DELETE) statements
Cannot be used anywhere in the WHERE/ Functions can be used anywhere in the WHERE/
HAVING/SELECT section of SQL statements HAVING/SELECT section of SQL statements
Try..Catch block can be used for exception handling Try..Catch block cannot be used for exception
handling
A transaction can be used A transaction cannot be used
The recompilation process of the stored procedure is like as compilation process and also reduces SQL Server
performance. Stored procedure with recompilation option was introduced in SQL Server 2005. We should
recompile the stored procedure in the following cases:
1. Changing to the schema (means adding/dropping columns, constraints, rules, index, trigger etc.) of the
tables or referenced table(s) or view(s).
2. Updating the statistics used by the execution plan of a stored procedure
1. Recompile option at the time of Creation - In this, we create a stored procedure with RECOMPILE option.
When we call this procedure than every time this procedure will be recompiled before executing.
@EmpID int,
@Name varchar(50),
@Salary int,
@Address varchar(100)
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
Insert into Employee(EmpID,Name,Salary,Address)
Values(@EmpID,@Name,@Salary,@Address);
set @flag=1;
commit TRANSACTION;
END TRY
BEGIN CATCH
rollback TRANSACTION;
set @flag=0;
END CATCH
END
GO
--Calling the procedure
Declare @flag bit
--Now Execute this procedure. Every time this procedure will be recompiled
EXEC usp_InsertEmployee @flag output,1,'Deepak',14000,'Noida'
if @flag=1
print 'Successfully inserted'
else
print 'There is some error'
2. Recompile option at the time of Execution- In this, we call a stored procedure with the RECOMPILE
option. Hence this stored procedure will be compiled only when we use the RECOMPILE option at the
time of calling. This is the best option for stored procedure recompilation.
BEGIN
BEGIN TRANSACTION
Page
BEGIN TRY
Insert into Employee(EmpID,Name,Salary,Address)
Values(@EmpID,@Name,@Salary,@Address);
set @flag=1;
commit TRANSACTION;
END TRY
BEGIN CATCH
rollback TRANSACTION;
set @flag=0;
END CATCH
END
GO
Note
• Creating the stored procedure by using "WITH RECOMPILE" option force the SQL Server to recompile the
stored procedure every time when it is called.
• Call the stored procedure by using "WITH RECOMPILE" option in the EXEC command.
• Altering the procedure will cause the SQL Server to create a new execution plan
• If SQL Server is restarted or stopped then all the execution plans will be flush from server cache and recreated
when the stored procedure is executed after restarting the server.
• The "Sp_recompile" system defined stored procedure can be called to refresh the query execution plan for
a particular stored procedure.
1. Statement-Level Exception
2. Batch-Level Exception
3. Parsing and Scope-Resolution Exception
52
Page
Q14. What is Statement-Level exception in SQL Server?
Ans. This type of exception aborts only the current running statement within a batch of T-SQL statements. The
rest of the T-SQL statements will execute successfully if they have no exceptions.
--Batch
SELECT POWER(4, 28)
PRINT 'This statement will execute'
If the exception occurs in the same scope of the batch, it behaves just like a batch-level exception. If the exception
occurs in a lower level of scope of the batch, it behaves just like statement-level exception.
Parsing Exception:
53
--Parsing Exception
SELECTEmpID, Name FROM Employee
Page
1. A TRY…CATCH block combination catches all the errors that have a severity between 11 and 19.
2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise
the CATCH block is ignored.
3. Each TRY block is associated with only one CATCH block and vice versa
4. TRY and CATCH blocks can’t be separated from the GO statement. We need to put both TRY and CATCH
blocks within the same batch.
5. TRY…CATCH blocks can be used with transactions. We check the number of open transactions by using the
@@TRANCOUNT function in SQL Server.
6. XACT_STATE function within the TRY…CATCH block can be used to check whether an open transaction is
committed or not. It will return -1 if the transaction is not committed else returns 1.
Q19. What are different error functions used in SQL Server for error handling?
Ans. There are some important functions for error handling in SQL Server as given below-
• ERROR_NUMBER() - This returns the error number and its value is same as for @@ERROR function.
• ERROR_LINE() - This returns the line number of T-SQL statement that causes an error.
• ERROR_SEVERITY() - This returns the severity level of the error.
• ERROR_STATE() - This returns the state number of the error.
• ERROR_PROCEDURE() - This returns the name of the stored procedure or trigger in which error occurred.
• ERROR_MESSAGE() - This returns the full text of error message.
Q21. What are the different ways to write case expression in SQL Server?
Ans. You can write Case expression in two ways as given below-
• Simple CASE expression - In this, an expression is compared w.r.t a set of simple expressions to find the
result. If the expression inside the WHEN clause is matched, the T-SQL in the THEN clause will be executed
and returned.
Syntax:
CASE expression
WHEN exp1 THEN result1
WHEN exp2 THEN result2
ELSE resultN
55
END
Page
• Searched CASE expressions - This expression evaluates a set of Boolean expressions to find the result. This
expression allows comparison operators, and logical operators AND/OR within each Boolean expression.
Syntax:
CASE
WHEN Boolean_expression1 THEN Result1
WHEN Boolean_expression2 THEN Result2
ELSE ResultN
END
For Example:
--Simple CASE expression:
SELECT FirstName, State=(CASE StateCode
WHEN 'MP' THEN 'Madhya Pradesh'
WHEN 'UP' THEN 'Uttar Pradesh'
WHEN 'DL' THEN 'Delhi'
ELSE NULL
END), PayRate
FROM dbo.Customer
56
Page
6
Triggers and Tables
Q1. What are triggers?
Ans. Triggers are a database object. Basically, these are a special type of stored procedure that is automatically
fired/executed when a DDL or DML command statement related to the trigger is executed.
Triggers are used to assess/evaluate data before or after data modification using DDL and DML statements. These
are also used to preserve data integrity, to control server operations, to audit a server and to implement business
logic or business rule.
Syntax:
• trigger_name - This is the name of the trigger. It should conform to the rules for identifiers in SQL Server.
• table|view - This is the table/view on which the trigger is to be created.
• ENCRYPTION - This option is optional. If this option is specified, the original text of the CREATE TRIGGER
statement will be encrypted.
• EXECUTE AS - This option is optional. This option specifies the security context under which the trigger is
executed.
• FOR/AFTER - FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only
keyword specified. AFTER triggers cannot be defined on views.
• INSTEAD OF - INSTEAD OF specifies that the trigger is Instead of Trigger.
• CREATE|ALTER|DROP|INSERT|UPDATE|DELETE - These keywords specify on which action the trigger
should be fired. One of these keywords or any combination of these keywords in any order can be used.
•
57
NOT FOR REPLICATION - Indicates that the trigger should not be executed when a replication process
modifies the table involved in the trigger.
Page
• AS - After this, we specify the actions and condition that the trigger performs.
• sql_statement - These are the trigger conditions and actions. The trigger actions specified in the T-SQL
statements.
• DDL Triggers
• DML Triggers
• CLR Triggers
• LogOn Triggers
1. After Trigger – This type of triggers is defined using FOR or AFTER clause. These triggers fire only after
successful execution of SQL Server statements on which they are associated.
For Example: If an after the trigger is associated with the insert operation on a database table, it will fire
after the successful record insertion in that database table. If the record insertion fails because of SQL
constraints like primary key, not null etc., it will not fire.
2. Instead of Trigger – This type of trigger is defined using INSTEAD OF clause. These triggers fire before
executing the SQL Server statements on which they are associated.
For Example: If an instead of trigger is associated with the insert operation on a database table, it will fire
before executing the insert statement on that database table. It will not wait for statement execution.
Ans. Logon triggers are fired a user tries to login into SQL Server. These do not fire if SQL Server authentication
fails. These triggers are helpful in auditing and controlling server sessions, such as tracking login activity or limit
Page
1. DML trigger can be composed of any T-SQL statements, except CREATE DATABASE, ALTER DATABASE,
DROP DATABASE, LOAD DATABASE, LOAD LOG, RECONFIGURE, RESTORE DATABASE, and RESTORE LOG
statements.
2. You cannot create triggers against system tables or dynamic management views. Moreover, the
TRUNCATE TABLE statement does not fire a trigger because this operation does not log individual row
deletions.
3. If you use the DATABASE option, the scope of your DDL trigger will be the current database. If you use the
ALL SERVER option, the scope of your DDL triggers to the current server.
4. AFTER triggers cannot be defined on views.
5. AFTER is the default, if FOR is the only keyword specified.
Q10. What are different ways for setting triggers firing order in SQL Server?
Ans. Sometimes we have multiple triggers on the same event(s). In that case, we can't predict the firing order
of triggers. Sometimes the firing order of trigger(s) is important for us to implement business logic. To solve this
issue, In SQL Server we have the option to set the firing order of triggers on the same event(s).
sp_settriggerorder @triggername='trg_name', @order='FIRST|LAST|NONE',
@stmttype='INSERT|UPDATE|DELETE|CREATE_INDEX,ALTER_INDEX',
@namespace='DATABASE|SERVER|NULL'
Q12. What are inserted and deleted logical tables in SQL Server?
Ans. The inserted and deleted logical tables are explained as:
Inserted Logical Table- Inserted table holds the recently inserted or updated values means new data values. Hence
newly added and updated records are inserted into the Inserted table.
Suppose we have Employee table as shown in fig. Now we need to create two triggers to see data within logical
tables Inserted and Deleted.
59
Page
CREATE TRIGGER trg_Emp_Ins
ON Employee
FOR INSERT
AS
begin
SELECT * FROM INSERTED -- show data in the Inserted logical table
SELECT * FROM DELETED -- show data in the Deleted logical table
End
Now insert a new record in the Employee table to see data within the Inserted logical table.
--Called Trigger trg_Emp_Ins automatically, when trying to insert data
INSERT INTO Employee(EmpID, Name, Salary) VALUES(3,'Avin',23000)
Deleted Logical Table - The Deleted table holds the recently deleted or updated values means old data values.
Hence old updated and deleted records are inserted into the Deleted table.
CREATE TRIGGER trg_Emp_Upd
ON Employee
FOR UPDATE
AS
begin
SELECT * FROM INSERTED -- show data in the INSERTED logical table
SELECT * FROM DELETED -- show data in the DELETED logical table
End
60
Now update the record in Employee table to see data within Inserted and Deleted logical tables.
Page
--Called Trigger trg_Emp_Upd automatically, when trying to update data
Update Employee set Salary=43000 where EmpID=3
Q13. When Inserted and Deleted Logical table are used in SQL Server?
Ans. Basically, logical tables are used by triggers for the following purpose:
• To test data manipulation errors and take suitable actions based on the errors.
• To find the difference between the state of a table before and after the data modification and take actions
based on that difference.
Except for triggers, when you use the OUTPUT clause in your query, logical tables are automatically created and
managed by SQL Server. OUTPUT clause also has access to Inserted and Deleted logical tables just like triggers.
1. Local Temp Table - Local temp tables are created using a single hash (“#”) symbol. These are accessible
within a session or connection for a single user i.e. it scoped to the current query window. These are
automatically removed when that user session has been closed.
2. Global Temp Table – Global temp tables are created using double hash (“##”) symbols. These are
accessible to all the SQL Server sessions or connections for all users. These can be created by any user and
removed automatically when all the SQL Server connections have been closed.
)
GO
Page
--Select data
Select * from @tblProducts
GO
--Next batch
Select * from @tblProducts --gives an error in next batch
Global - Global variables are system-defined variables and SQL Server automatically maintains the values of these
variables related to the server or a current user session. All global variables start with two @@ symbols.
1. Declare Cursor - A cursor is declared by defining the SQL statement that returns a result set.
2. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor.
3. Fetch - When a cursor is opened, records can be fetched from the cursor one by one to perform data
manipulation.
4. Close - After data manipulation, you should close the cursor explicitly.
5. Deallocate - Finally, you need to delete the cursor definition and released all the system resources
associated with the cursor.
Syntax
DECLARE cursor_name CURSOR
[LOCAL | GLOBAL] --define cursor scope
[FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
FOR select_statement --define SQL Select statement
FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
• Syntax to Open A Cursor- A Cursor can be opened locally or globally. By default, it is opened locally. The
basic syntax to open cursor is given below:
• Syntax to Fetch A Cursor- Fetch statement provides the many options to retrieve the rows from the
cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
64
Page
FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
FROM [GLOBAL] cursor_name
INTO @Variable_name[1,2,..n]
• Syntax to Close A Cursor- Close statement closed the cursor explicitly. The basic syntax to close cursor
is given below:
• Syntax to Deallocate A Cursor- Deallocate statement delete the cursor definition and free all the system
resources associated with the cursor. The basic syntax to close cursor is given below:
• Static Cursors
• Dynamic Cursors
• Forward Only Cursors
• Keyset-Driven Cursors
Go
Select * from Employee
There are three more types of Forward Only Cursors. Forward_Only KEYSET, FORWARD_ONLY STATIC and
FAST_FORWARD.
A FORWARD_ONLY STATIC Cursor is populated at the time of creation and cached the data to the cursor lifetime.
It is not sensitive to any changes to the data source.
Go
Select * from Employee
cursor is sensitive to any changes to the data source and supports update, delete operations. By default, keyset-
Page
Go
Select * from Employee
Ans. As we know, the cursors are required when we need to update records in a database table in singleton
fashion means row by row. A Cursor also impacts the performance of the SQL Server since it uses the SQL Server
Page
instance’s memory, reduce concurrency, decrease network bandwidth and lock resources.
You should avoid the use of a cursor. You can use cursor alternatives like as WHILE loop, Temporary tables and
Table variables. We should use cursor in that case when there is no option except cursor.
• Variable
• Field/Column in a table
• The parameter in the user-defined function (UDF) or stored procedure (SP)
• the return value from a UDF or SP
We can define XML data type field to NOT NULL or we can provide a default value to it.
Q15. What are the limitations of the XML data type in SQL Server?
Ans. There are following limitations of XML data types:
• We can’t directly compare an instance of the XML data type to another instance of the XML data type. For
equality comparisons, we first need to convert the XML type to a character type.
• We can’t use GROUP BY or ORDER BY with an XML data type column.
• We can’t use XML data type field as a primary key, Unique key and foreign key.
• We can’t define XML data type field with COLLATE keyword.
AUTO - It generates output with both elements and attributes features in combination with a subquery.
SELECT DeptName, EmpID
FROM Employee AS Emp JOIN Department AS Dept
ON Emp.DeptID= Dept.DeptID
FOR XML AUTO;
Output:
<Dept DeptName="IT">
<Emp EmpID="1" />
<Emp EmpID="2" />
</Dept>
<Dept DeptName="HR">
<Emp EmpID="3" />
</Dept>
<Dept DeptName="Technical">
70
</Dept>
EXPLICIT - It converts the row set that is the result of the query execution, into an XML document. This mode
provides more control over the format of the XML means in which format you want XML you need to define that
format in select query.
SELECT 1 tag,
NULL parent,
EmpID [employee!1!ID],
EmpName [employee!1!name],
NULL [order!2!date],
NULL [department!3!name]
FROM Employee
UNION ALL
SELECT 3, 1,
EmpID,
NULL,
NULL,
DeptName
FROM Employee e JOIN Department d
ON e.DeptID=d.DeptID
ORDER BY 3, 1
FOR XML EXPLICIT;
Output:
<employee ID="1" name="Shailendra">
<department name="IT" />
</employee>
<employee ID="2" name="Mohan">
<department name="IT" />
</employee>
<employee ID="3" name="Vipul">
<department name="HR" />
</employee>
<employee ID="4" name="Mrinal">
<department name="Technical" />
</employee>
<employee ID="5" name="Jitendra">
<department name="Technical" />
</employee>
RAW - It produces a single element or the optionally provided element name for each row in the query result set
that is returned by the select statement.
SELECT Emp.EmpID, Dept.DeptName
Employee as Emp JOIN Department as Dept
ON Emp.DeptID= Dept.DeptID
71
1. Clustered Index
2. Non-Clustered Index
You can think of a clustered index as a dictionary in alphabetical order, and a non-clustered index as a book's
index.
In SQL Server on a table, you can have max 999 non-clustered index having SQL Server 2012 & 20008 and max 249
non-clustered index having SQL Server 2005.
72
Page
Q22. What is full-text search in SQL Server?
Ans. It was introduced with SQL Server 2008. Full-Text search helps you to search records based on a word or
phrase. For this, you need to create a full-text index on a table or indexed view and only one full-text index is
allowed per table or view.
This feature works only with RTM (Ready to manufacture) version of SQL Server. It does not work with CTP
(Community Technology Preview) version of SQL Server.
73
Page
References
74
Page