SQL Practice Qts
SQL Practice Qts
Here our step by step SQL Server Interview Questions/ TSQL Queries asked during
interview.
Set-1: Sql Server Basic Interview Query
Tables:-
5. Write a query for combine FirstName and LastName and display it as "Name" (also
include white space between first name & last name)
ANS:
MS SQL Server: SELECT FirstName +' '+ LastName AS [Name] FROM EmployeeDetail
Oracle: SELECT FirstName ||' '|| LastName AS [Name] FROM EmployeeDetail
MySQL:
SELECT CONCAT(FirstName ,' ', LastName) AS [Name] FROM EmployeeDetail
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
7. Get all employee detail from EmployeeDetail table whose "FirstName" start with
latter 'a'.
ANS:
MS SQL Server: SELECT * FROM EmployeeDetail WHERE FirstName like 'a%'
Oracle: SELECT * FROM EmployeeDetail WHERE FirstName like 'a%'
MySQL: SELECT * FROM EmployeeDetail WHERE FirstName like 'a%'
8. Get all employee details from EmployeeDetail table whose "FirstName" contains
'k'
ANS:
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
9. Get all employee details from EmployeeDetail table whose "FirstName" end with
'h'
ANS:
MS SQL Server: SELECT * FROM EmployeeDetail WHERE FirstName like '%h'
Oracle: SELECT * FROM EmployeeDetail WHERE FirstName like '%h'
MySQL: SELECT * FROM EmployeeDetail WHERE FirstName like '%h'
10. Get all employee detail from EmployeeDetail table whose "FirstName" start with
any single character between 'a-p'
ANS:
MS SQL Server: SELECT * FROM EmployeeDetail WHERE FirstName like '[a-p]%'
Oracle: SELECT * FROM EmployeeDetail WHERE FirstName like '[a-p]%'
MySQL: SELECT * FROM EmployeeDetail WHERE FirstName like '[a-p]%'
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
Questions Answers
11). Get all employee detail from EmployeeDetail table whose "FirstName" not start
with any single character between 'a-p'
Ans: SELECT * FROM [EmployeeDetail] WHERE FirstName like '[^a-p]%'
12). Get all employee detail from EmployeeDetail table whose "Gender" end with 'le'
and contain 4 letters. The Underscore(_) Wildcard Character represents any single
character.
Ans: SELECT * FROM [EmployeeDetail] WHERE Gender like ' le' --there are two "_"
13). Get all employee detail from EmployeeDetail table whose "FirstName" start with
'A' and contain 5 letters.
Ans: SELECT * FROM [EmployeeDetail] WHERE FirstName like 'A ' --there are four "_"
14). Get all employee detail from EmployeeDetail table whose "FirstName"
containing '%'. ex:-"Vik%as".
Ans: SELECT * FROM [EmployeeDetail] WHERE FirstName like '%[%]%'
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--According to our table it would return 0 rows, because no name containg '%'
18). Show "JoiningDate" in "dd mmm yyyy" format, ex- "15 Feb 2013"
Ans: SELECT CONVERT(VARCHAR(20),JoiningDate,106) FROM [EmployeeDetail]
26). Get the first name, current date, joiningdate and diff between current date and
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
27). Get all employee details from EmployeeDetail table whose joining year is 2013.
Ans: SELECT * FROM [EmployeeDetail] WHERE DATEPART(YYYY,JoiningDate) = '2013'
28). Get all employee details from EmployeeDetail table whose joining month is
Jan(1).
Ans: SELECT * FROM [EmployeeDetail] WHERE DATEPART(MM,JoiningDate) = '1'
29). Get all employee details from EmployeeDetail table whose joining date between
"2013-01-01" and "2013-12-01".
Ans: SELECT * FROM [EmployeeDetail] WHERE JoiningDate BETWEEN '2013-01-
01' AND '2013-12-01'
32. Select all employee detail with First name "Vikas","Ashish", and "Nikhil".
Ans: SELECT * FROM [EmployeeDetail] WHERE FirstName IN('Vikas','Ashish','Nikhil')
33. Select all employee detail with First name not in "Vikas","Ashish", and "Nikhil".
Ans: SELECT * FROM [EmployeeDetail] WHERE FirstName NOT IN('Vikas','Ashish','Nikhil')
34. Select first name from "EmployeeDetail" table after removing white spaces from
right side
Ans: SELECT RTRIM(FirstName) AS [FirstName] FROM [EmployeeDetail]
35. Select first name from "EmployeeDetail" table after removing white spaces from
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
left side
Ans: SELECT LTRIM(FirstName) AS [FirstName] FROM [EmployeeDetail]
36. Display first name and Gender as M/F.(if male then M, if Female then F)
Ans: SELECT FirstName, CASE WHEN Gender = 'Male' THEN 'M'
WHEN Gender = 'Female' THEN 'F' END AS [Gender]
FROM [EmployeeDetail]
37. Select first name from "EmployeeDetail" table prifixed with "Hello "
Ans: SELECT 'Hello ' + FirstName FROM [EmployeeDetail]
38. Get employee details from "EmployeeDetail" table whose Salary greater than
600000
Ans: SELECT * FROM [EmployeeDetail] WHERE Salary > 600000
39. Get employee details from "EmployeeDetail" table whose Salary less than 700000
Ans: SELECT * FROM [EmployeeDetail] WHERE Salary < 700000
40. Get employee details from "EmployeeDetail" table whose Salary between 500000
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
than 600000
Ans: SELECT * FROM [EmployeeDetail] WHERE Salary BETWEEN 500000 AND 600000
QUESTIONS ANSWERS
42. Write the query to get the department and department wise total(sum) salary
from "EmployeeDetail" table.
Ans: SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department
43. Write the query to get the department and department wise total(sum) salary,
display it in ascending order according to salary.
Ans: SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY SUM(Salary) ASC
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
44. Write the query to get the department and department wise total(sum) salary,
display it in descending order according to salary.
Ans: SELECT Department, SUM(Salary) AS [Total Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY SUM(Salary) DESC
45. Write the query to get the department, total no. of departments, total(sum) salary
with respect to department from "EmployeeDetail" table.
Ans: SELECT Department, COUNT(*) AS [Dept Counts], SUM(Salary) AS [Total
Salary] FROM[EmployeeDetail]
GROUP BY Department
46. Get department wise average salary from "EmployeeDetail" table order by salary
ascending
Ans: SELECT Department, AVG(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY AVG(Salary) ASC
47
. Get department wise maximum salary from "EmployeeDetail" table order by salary
ascending
Ans: SELECT Department, MAX(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY MAX(Salary) ASC
48. Get department wise minimum salary from "EmployeeDetail" table order by
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
salary ascending
Ans: SELECT Department, MIN(Salary) AS [Average Salary] FROM [EmployeeDetail]
GROUP BY Department ORDER BY MIN(Salary) ASC
--
USE OF HAVING
49. Write down the query to fetch Project name assign to more than one Employee
Ans: Select ProjectName,Count(*) [NoofEmp] from [ProjectDetail] GROUP BY ProjectNa
meHAVING COUNT(*)>1
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
51. Get employee name, project name order by firstname from "EmployeeDetail" and
"ProjectDetail" for those employee which have assigned project already.
Ans: SELECT FirstName,ProjectName FROM [EmployeeDetail] A INNER JOIN [ProjectDeta
il]B ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
52.Get employee name, project name order by firstname from "EmployeeDetail" and
"ProjectDetail" for all employee even they have not assigned project.
Ans: SELECT FirstName,ProjectName FROM [EmployeeDetail] A LEFT OUTER JOIN[Projec
tDetail] B ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName
54. Get all project name even they have not matching any employeeid, in left table,
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
55. Get complete record (employeename, project name) from both tables
([EmployeeDetail],[ProjectDetail]), if no match found in any table then show NULL.
Ans: SELECT FirstName,ProjectName FROM [EmployeeDetail] A FULL OUTER JOIN[Projec
tDetail] B ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName
56. Write a query to find out the employeename who has not assigned any project,
and display "-No Project Assigned"( tables :- [EmployeeDetail],[ProjectDetail]).
Ans: SELECT FirstName, ISNULL(ProjectName,'-No Project
Assigned') AS [ProjectName]FROM [EmployeeDetail] A LEFT OUTER JOIN [ProjectDetail]
B ON A.EmployeeID =B.EmployeeDetailID
WHERE ProjectName IS NULL
57. Write a query to find out the project name which is not assigned to any employee(
tables :- [EmployeeDetail],[ProjectDetail]).
Ans: SELECT ProjectName FROM [EmployeeDetail] A RIGHT OUTER JOIN [ProjectDetail]
B ONA.EmployeeID = B.EmployeeDetailID
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
58. Write down the query to fetch EmployeeName & Project who has assign more
than one project.
Ans: Select EmployeeID, FirstName, ProjectName from [EmployeeDetail] E INNER JOIN[P
rojectDetail] P
ON E.EmployeeID = P.EmployeeDetailID
WHERE EmployeeID IN (SELECT EmployeeDetailID FROM [ProjectDetail] GROUP BYEmpl
oyeeDetailID HAVING COUNT(*) >1 )
59. Write down the query to fetch ProjectName on which more than one employee
are working along with EmployeeName.
Ans: Select P.ProjectName, E.FName from ProjectDetails P INNER JOIN EmployeeDetails
E
on p.EmployeId = E.Id where P.ProjectName in(select ProjectName from ProjectDetailsgr
oup by ProjectName having COUNT(1)>1)
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
SELECT T1.ID, T2.ID FROM TBL_1 T1 INNER JOIN TBL_2 T2 ON T1.ID = T2.ID
--ANS:
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--61. What would the output of the following query(LEFT OUTER JOIN)
SELECT T1.ID, T2.ID FROM TBL_1 T1 LEFT OUTER JOIN TBL_2 T2 ON T1.ID = T2.ID
--ANS: Output would be same as 60th Question
--62. What will be the output of the following query(LEFT OUTER JOIN)
SELECT T1.ID, T2.ID FROM TBL_1 T1 LEFT OUTER JOIN TBL_2 T2 ON T1.ID = T2.ID
--ANS: Output would be same as 60th Question
--63. What would the output of the following query(RIGHT OUTER JOIN)
SELECT T1.ID, T2.ID FROM TBL_1 T1 RIGHT OUTER JOIN TBL_2 T2 ON T1.ID = T2.ID
--ANS: Output would be same as 60th Question
--64. What would be the output of the following query(FULL OUTER JOIN)
SELECT T1.ID, T2.ID FROM TBL_1 T1 FULL OUTER JOIN TBL_2 T2 ON T1.ID = T2.ID
--ANS: Output would be same as 60th Question
--65. What would be the output of the following query(CROSS JOIN)
--66. What would be the output of the following query.(Related Tables : Table_1,Table_2)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID = B.ID
--ANS:
--67. What would be the output of the following query.(Related Tables : Table_1,Table_2)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID = B.ID AND A.[Name] = B.[Name]
--ANS:
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--68. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH AND)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID = B.ID AND A.[Name] = B.[Name]
--ANS:
--69. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH OR)
SELECT A.[ID], A.[Name],B.[ID], B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID = B.ID OR A.[Name] = B.[Name]
--ANS:
--70. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH NOT EQUAL !=)
SELECT A.[ID], A.[Name],B.[ID], B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID != B.ID
--ANS:
--71. Click on the Page no 2 below for continue reading ( for 71st and more such Query)
--71. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH NOT)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON NOT(A.ID = B.ID)
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--ANS:
--72. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH IN)
SELECT A.[ID], A.[Name],B.[ID], B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON A.ID IN(1)
--ANS:
--73. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(INNER JOIN WITH NOT)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A INNER JOIN [Table_2] B
ON NOT(A.ID = B.ID)
--ANS:
--74. What would be the output of the following query.(Related Tables : Table_1,Table_2)
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--75. Write down the query to fatch record from Table_1 which not exist in Table_2(based on ID column)
--ANS:
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A LEFT OUTER JOIN [Table_2] B
ON A.ID = B.ID WHERE B.[ID] IS NULL
--76. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--(LEFT OUTER JOIN WITH !=)
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A LEFT OUTER JOIN [Table_2] B
ON A.ID != B.ID
--ANS:
--77. Write down the query to fatch record from Table_2 which not exist in Table_1(based on ID column)
--ANS:
SELECT A.[ID] ,A.[Name],B.[ID] ,B.[Name] FROM [Table_1] A RIGHT OUTER JOIN [Table_2] B
ON A.ID = B.ID WHERE A.[ID] IS NULL
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--79. Write down the query to create employee table with Identity column([EmployeeID])
--ANS:
CREATE TABLE EmployeeDetail( [EmployeeID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY, [FirstName]NV
ARCHAR(50) NULL,
[LastName] NVARCHAR(50) NULL, [Salary] DECIMAL(10, 2) NULL, [JoiningDate] DATETIME NULL,[Depar
tment] NVARCHAR(20) NULL,
[Gender] VARCHAR(10) NULL)
--80. Write down the query to create employee table with primary key (EmployeeID)
--ANS:
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
CREATE TABLE EmployeeDetail( [EmployeeID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
[FirstName] NVARCHAR(50) NULL,[LastName] NVARCHAR(50) NULL, [Salary] DECIMAL(10, 2) NULL,[Join
ingDate] DATETIME NULL, [Department] NVARCHAR(20) NULL,
[Gender] VARCHAR(10) NULL)
--82. How to set primary key and foreignkey relationship using query(set EmployeeID column of
ProjectDetail table as a foreignkey)
--ANS:
ALTER TABLE ProjectDetail
ADD CONSTRAINT fk_EmployeeDetailID_Eid FOREIGN KEY(EmployeeDetailID)REFERENCESEmployeeDetail
(EmployeeID)
83). SELECT 15
--output of this query would be.
A). Throw error
B). 15
C). 0
D). 1
84).SELECT $
--output of this query would be.
A). Throw error
B). $
C). 1
D). 0.00
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
85).SELECT COUNT(*)
--output of this query would be.
A). Throw error
B). 0
C). 1
D). *
86). SELECT COUNT('7')
--output of this query would be.
A). Throw error
B). 7
C). 0
D). 1
87). SELECT 'VIKAS' + 1
--output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1
88).SELECT 'VIKAS' + '1'
--output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1
89).SELECT (SELECT 'VIKAS')
--output of this query would be.
A). Throw error
B). 'VIKAS'
C). VIKAS
D). VIKAS1
--100. Write down the query to print first letter of a Name in Upper Case and all other letter in Lower
Case.(EmployDetail table)
ANS:
SELECT UPPER(SUBSTRING(FirstName,1,1))+LOWER(SUBSTRING(FirstName,2,LEN(FirstName)-
1)) AS [FirstName]
Output:-
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
--101. Write down the query to display all employee name in one cell seprated by ',' ex:-"Vikas, nikita,
Ashish, Nikhil , anish"(EmployDetail table)
ANS:
Solution 1:
SELECT STUFF(( SELECT ', ' + E.FirstName FROM [EmployeeDetail] AS E FOR XML PATH('')), 1, 2, '') AS [All
Emp Name]
Output:-
Solution 2:
--102. Write down the query to get ProjectName and respective EmployeeName(firstname) which are
working on the project,
--if more then one employee working on same project, then it should be in same cell seprated by comma
--for example :- Task Tracker : Vikas, Ashish
ANS:
SELECT ProjectName, STUFF((SELECT ', ' + FirstName FROM EmployeeDetail
E1 INNER JOIN [ProjectDetail] P1 ON E1.EmployeeID = P1.EmployeeDetailID
WHERE P1.ProjectName = P2.ProjectName FOR XML PATH('')),1,2,'' ) AS [Employee
Name] FROM EmployeeDetail E2
INNER JOIN [ProjectDetail] P2 ON E2.EmployeeID = P2.EmployeeDetailID
GROUP BY ProjectName
Output:-
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
Options:
DATATYPE DESCRIPTION
bigint Integer data from -2^63 to 2^63-1
binary Fixed-length binary data with a maximum length of 8,000 bytes
bit Integer data with either a 1 or 0 value (often for a true or false reading)
char Fixed-length non-unicode character data with a maximum length of 8,000 characters
cursor A reference to a cursor
datetime Date and time data from January 1, 1753, through December 31, 9999, with an accuracy o
3.33 milliseconds (but use datetime2 instead)
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
decimal Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1 (same as 'num
float (decimal(9,2)) = max value 9999999.99)
image Floating precision number data from -1.79E + 308 through 1.79E + 308
int Variable-length binary data with a maximum length of 2^31 - 1 bytes
money Integer data from -2^31 through 2^31 - 1 (-2 billion to 2 billion approx)
nchar Monetary data values from -2^63 through 2^63 - 1
ntext Fixed-length Unicode data with a maximum length of 4,000 characters
numeric Variable-length Unicode data with a maximum length of 2^30 - 1 characters (Deprecated
nvarchar don't use!)
real Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1 (same as 'deci
Variable-length Unicode data with a maximum length of 4,000 characters
Floating precision number data from -3.40E + 38 through 3.40E + 38
smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one
minute
smallint Integer data from -2^15 through 2^15 - 1 (-32000 to 32000 approx)
smallmoney Monetary data values from -214,748.3648 to +214,748.3647
sql_variant A data type that stores values of various data types, except text, ntext, timestamp, and
table sql_variant
text A special data type used to store a result set for later processing
timestamp Variable-length data with a maximum length of 2^31 - 1 characters (Deprecated - don't u
tinyint A database-wide unique number that gets updated every time a row gets updated
Integer data from 0 to 255
uniqueidentifier A globally unique identifier
varbinary Variable-length binary data with a maximum length of 8,000 bytes
varchar Variable-length non-unicode data with a maximum of 8,000 characters
date holds date
time holds time
datetime2 Date and time data from January 1, 1753, through December 31, 9999, with an accuracy
about 100 nanoseconds, plus more compactly stored
datetimeoffset takes international time into account in reading
xml for storing or even parsing raw xml data
What are the two types of character data SQL Server supports?
Ans: Regular and Unicode
Syntax?
In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to
rowversion. It basically means that every time a row is changed, this value is increased. This
is done with a database counter, i.e. two different rows that where updated in the same
transaction have the same row version.
3).Write a query to create a clone of existing table without using Create Command.
Ans: SELECT * INTO <NewTable> FROM <ExistingTable> WHERE 1=2
SELECT TOP 0 * INTO <NewTable> FROM <ExistingTable>
4). Table Tbl1 has 100 rows, Table Tbl2 has 0 rows so number of rows returned by the
below query?
SELECT Tbl1.* from Tbl1, Tbl2;
Ans : No row will be retun by this query
5). Write a query to print 1 to 100 in sql server without using loops?
Ans: Use Recursive common table expression:
;WITH CTE
AS
(
SELECT 1 [Sequence]
UNION ALL
SELECT [Sequence] + 1 FROM CTE WHERE [Sequence] <100
)
SELECT * FROM CTE
Using Loop:
DECLARE @i INT
SET @i = 0
WHILE (@i < 100)
BEGIN
SELECT @i = @i + 1
PRINT @i
END
9).For 5/2, I want resut as 2.5, How you will do that in SQL Server?
SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float)
10). You have two tables with blank value in both table as shown in below image,
Then what would be the output of the following Query based on the tables shown in
image?
SELECT T1.*, T2.* FROM Table1 T1 INNER JOIN Table2 T2
ON T1.Name = T2.Name
Ans: Output of the above query would be as below, Inner join will join both blank values
3). Will Non-Clustered Index used every time by SQL Server Engine? (HCL/Unitedhealth
Group)
4). What are different part of a SQL Page?
Indexed Views
Partitioned Views
System Views
Click here for more detail
8). How you will encrypt a view, so that people can utilize view to run reports, but
can't see the underlying code?
Ans: We can encrypt our view by using WITH ENCRYPTION keyword
Ex:
Create View vEmployeeDetail
WITH ENCRYPTION
AS
Select EmpID, Sum(Amount) as Total From Emp Group by EmpID
9). If you are going to change or drop a table, but you don't know how many
views/proc etc are depend on this particular table, then how you will you find
dependencies?
Ans: To check dependencies there is a system-supplied stored procedure, sp_depends,
which will list all dependent objects for the object name you pass in.
10). What is the purpose of the WITH SCHEMABINDING clause and where can it be
used?
Ans: WITH SCHEMABINDING can be used in Views and T-SQL Functions.
Objects that are schema bound can have their definition changed, but objects that are
referenced by schema bound objects cannot have their definition changed.
Schema binding effectively states that the meta-data which is created at object creation
time can then be relied upon to be accurate at all times, and use of sp_refreshsqlmodule is
not necessary. Schema binding can also significantly increase the performance of user
defined functions in SQL Server 2005 and above. However, caution should be applied, as
this is definitely not always the case.
AS
SELECT FirstName,LastName FROM [Person].[Person]
Lest Start :
What is an Index?
Indexes of SQL Server are similar to the indexes in books. They help SQL Server retrieve the
data quicker. Index is a database object, which can be created on one or more columns.
When creating the index will read the column(s) and forms a relevant data structure to
minimize the number of data comparisons. The index will improve the performance of data
retrieval and adds some overhead on data modification such as create, delete and modify.
So it depends on how much data retrieval can be performed on table versus how much of
DML (Insert, Delete and Update) operations.
How many clustered indexes there can be in one table?
Only one.
How many non-clustered indexes there can be in one table?
For SQL Server 2005: 249 Nonclustered Index
For SQL Server 2008: 999 Nonclustered Index
What is clustered table?
A table having clustered index also called as clustered table.
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
Types of Indexes?
SQL Server has two major types of indexes:
Clustered
Non-Clustered
What is Clustered index?
A clustered index sorts and stores the data rows of the table or view in order based on the
clustered index key. The clustered index is implemented as a B-tree index structure that
supports fast retrieval of the rows, based on their clustered index key values.
What is Non-Clustered index?
A nonclustered index can be defined on a table or view with a clustered index or on a heap.
Each index row in the nonclustered index contains the nonclustered key value and a row
locator. This locator points to the data row in the clustered index or heap having the key
value. The rows in the index are stored in the order of the index key values, but the data
rows are not guaranteed to be in any particular order unless a clustered index is created on
the table.
For understand deeply follow the link
http://blog.sqlauthority.com/2013/02/10/sql-server-primary-key-and-nonclustered-index-
in-simple-words/
Write the T-Sql statement/syntex for create and index?
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Difference Between Unique Index vs Unique Constraint?
Unique Index and Unique Constraint are the same. They achieve same goal. SQL
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
Extended Procedure
User Defined Stored Procedure
CLR Stored Procedure
click here for more detail
4).What is the difference between a user defined function and a Stored procedure?
Ans: Click here for answer
Ans: Yes. Because Transact-SQL supports recursion, you can write stored procedures that
call themselves. You can nest stored procedures and managed code references up to 32
levels.
7).Have you ever created or used recursive stored procedure? Give example?
Ans: I created a recursive stored procedure for calculating the factorial of a number.
CREATE PROCEDURE [dbo].[Factorial_ap]
( @Number Integer,@RetVal Integer OUTPUT )
AS
DECLARE @In Integer
DECLARE @Out Integer
IF @Number != 1
BEGIN
SELECT @In = @Number – 1
EXEC Factorial_ap @In, @Out OUTPUT
SELECT @RetVal = @Number * @Out
END
ELSE
BEGIN
SELECT @RetVal = 1
END
RETURN
GO
Reduce network usage between clients and servers – stored procedures perform
intermediate processing on the database server reducing unnecessary data transfer
across the network
Improved security – database administrator can control the users who access the
stored procedure
Reduced development cost and increased reliability
Stored procedures are tunable to improve the performance. When same stored
procedure executed again, it can use the previously cached execution plans
Separate or abstract server side functions from the client side
Stored procedures can encapsulate logic. You can change stored procedure code
without affecting clients.
Access
to other database objects in a secure and uniform way
Can
prevent SQL injection attacks
Unit testable
Encapsulation of business logic – less chances to data become corrupted through
faulty client programs.
9). What are the disadvantages of using a Stored Procedures?
Ans: Following are the main disadvantage of using a SP
13).What is the difference between stored procedure and view in SQL Server?
Ans: Views : They are the virtual table which consists of one or more rows and columns
from different real tables of the Database. It is the template of rows and columns of
multiple tables. You cannot pass any parameters here.
Stored Procedures : They are a collection of pre-executed sql Statements where you can
send the parameters as input and retrieve the output data.
Summery difference of Stored procedure and View:
Stored Procedure:
1. Accept parameters
2. Can not be used as a building block in large query.
3.Can contain several statement like if, else, loop etc.
4.Can perform modification to one or several tables.
5.Can not be used as the target for Insert, update, delete queries.
6.We can use view inside stored procedure.
Views:
1. Does not accepts parameters
2. Can be used as a building block in large query.
3.Can contain only one single Select query.
4. Can not perform modification to any table.
5. Can be used (sometimes) as the target for Insert, update, delete queries.
6.We can't use stored procedure inside view.
14). How do we recompile a stored procedure at run time?
Ans: By adding the WITH RECOMPILE hint when creating or executing the stored procedure.
SELECT 1/0
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
19). Can we use multiple select statements in a Stored Procedure SQL Server?
Ans: Yes, we can use multiple select statements in a SP.
20). Can we create Stored Procedure without "Begin" and "End" refer the below
image and try to answers?
Ans: No, Stored procedures are not allowed to return the NULL value.
If you will try to return null value the you will get message as shown in the above
screenshot.
Table var doesn't have to be memory-resident. Its pages can be moved to tempdb if
memory is low
Rollback doesn't affect table vars
Table vars don't participate in transactions or locking
Any DML operations done on table variables are not logged
No statistics are maintained on table variables
* Query Store
* Live Query Statistics
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
Ans : JSON
Q 6 : Why JSON is becoming important than XML, even for MS SQL Server?
Ans : One of the biggest reasons JSON is becoming more important than XML is that XML has
to be parsed with an XML parser, while JSON can be parsed by a standard JavaScript function.
And it is very light-weight, this makes it easier and faster than working with XML.
Q 7 : What do you understand by Temporal data support, a new freature introduce in
SQL Server 2016?
Ans : SQL Server 2016 introduces support for temporal tables as a database feature that
provides built-in support for provide information about data stored in the table at any point in
time rather than only the data that is correct at the current moment in time. Temporal is a
database feature that was introduced in ANSI SQL 2011 and is now supported in SQL Server
2016
Q 8 : What is Row-Level Security, in SQL Server 2016(new feature)?
Ans : Row-Level Security (RLS) enables developers and DBAs to control access to rows in a
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
database table. Using RLS, you can store data for different customers, departments, or
tenants in the same table, while restricting access to rows based on a query’s execution
context. For example, you could filter rows returned by “SELECT * FROM myTable” according
to the identity of the logged-in user or the value of a session-scoped variable like
CONTEXT_INFO.
Q 9 : What are the difference between SQL Server 2014 and 2016?
Q 11 : SQL Server 2016 came with new way to drop object if exist, Explain it.(DROP IF
EXIST)
Q 12 : What are the benefits/advantages of this release(SQL Server 2016)? Can you
summarize?
Ans:
# Enhanced in-memory performance provides up to 30x faster transactions, more than 100x
faster queries than disk-based relational databases and real-time operational analytics.
# New Always Encrypted technology helps protect your data at rest and in motion, on-
premises and in the cloud, with master keys sitting with the application, without application
changes.
#Stretch Database technology keeps more of your customer’s historical data at your
fingertips by transparently stretching your warm and cold OLTP data to Microsoft Azure in a
secure manner without application changes.
#Built-in advanced analytics provide the scalability and performance benefits of building
and running your advanced analytics algorithms directly in the core SQL Server
transactional database.
#Business insights through rich visualizations on mobile devices with native apps for
Windows, iOS and Android.
#Simplify management of relational and non-relational data by querying both with T-SQL
using PolyBase.
#Faster hybrid backups, high availability and disaster recovery scenarios to back up and
restore your on-premises databases to Microsoft Azure and place your SQL Server
AlwaysOn secondaries in Azure.
2). How many (maximum) no. of columns can be created in a MS SQL Table?
Ans: Max Columns per 'nonwide' table: 1,024
Max Columns per 'wide' table: 30,000
3). What is the difference between Wide and Nonwide tables in SQL Server?
Ans: 1) Wide table can contain 30,000 columns, Non-wide table(basic table) can contain
only 1024 columns.
2) Wide Tables are considered to be denormalized tables, Non-wide tables are considered
to be Normalized tables.
3) Wide tables are used in OLAP systems, Narrow tables are used in OLTP system.
4) Wide table is new feature in SQL Server 2008. To over come the problem of having only
1024 columns in Narrow tables.
5) Wide tables don't work with transactional or merge replication, but Non-wide can work.
4). Maximum how many rows can be in the SQL Server tables?
Ans: According to Microsoft specification:
Rows per table: Limited by available storage
But there are some cases where SQL Server will prevent you from adding more rows
If you have an IDENTITY column and you hit the end of the range for the data type,
e.g. 255 for TINYINT, 2,147,483,647 for INT, some ungodly number th
9 - possibly the number of inches to the sun and back - for BIGINT, etc. When you try to
insert the next row, you'll get error message 815 about overflowing the type.
If you have a heap with a non-unique index, or a clustered index that is not unique,
you won't be able to store more than 2 * 2,147,483,647 unique index key
combinations. When you try to insert (2 * 2,147,483,647) + 1 rows with a value of 1 in
an INT column that is the only column in a clustered index, you will get error
message 666 about exhausting the uniqueifier. This is because the uniqueifier (which
helps SQL Server identify a row when there is no true key) is only 4 bytes, which
means it can't exceed the capacity of an INT (it does use both positive and negative,
unlike IDENTITY unless configure it as such, which is why you get double). Now why
you would ever do this, <shrug>... but you could.
In the VLDB space, a database can only be 524,272 terabytes. Again a very edge case,
but if you have a humongous data warehouse then obviously at some point the
number of rows - depending on row size - will put you near this limit.
5). What is the maximum size of a varchar(max) variable?
Ans: Maximum size for a varchar(max) is 2GB, or looked up a more exact figure (2^31-1, or
2147483647).
VARCHAR(MAX) uses the normal datapages until the content actually fills 8k of data
as varchar(8000). When overflow happens, data is stored as old TEXT, IMAGE and a
pointer is replacing the old content.
Columns that are of the large object (LOB) data types ntext, text, varchar(max),
nvarchar(max), varbinary(max), xml, or image cannot be specified as key columns for
an index
VARCHAR(MAX) has some ambiguity, if the size of the cell is < 8000 chars, it will be
treated as Row data. If it's greater, it will be treated as a LOB for storage purposes.
You can know this by querying RBAR.
7). How can i query my sql server to only get the size of database?
Ans: Use "YourDatabaseName"
exec sp_spaceused
8).What would be the LEN and DATALENGTH of NULL value in SQL Server?
Ans: Both above function will return NULL as the length of NULL.
Intent
Shared
Update
Exclusive
Schema
Bulk Update
2). What are the different types of BACKUPs available in SQL Server 2005?
Ans: In SQL Server 2005 Backup Types are
Full
Transaction Log
Differential
Partial
Differential Partial
File and Filegroup
Copy Only Database Backups
3). What are Data files?
Ans:This is the physical storage for all of the data on disk. Pages are read into the buffer
cache when users request data for viewing or modification. After data has been modified in
memory (the buffer cache), it is written back to the data file during the checkpoint process.
Read committed
Read uncommitted
Repeatable read
Serializable
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
8). What database does SQL Server use for temporary tables?
Ans: TempDB
Full
Simple
Bulk Logged
15). What the difference between UNION and UNIONALL?
Ans: Union will remove the duplicate rows from the result set while Union all does'nt.
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
replace multiple character with multiple character respectively. It will return an error if
characters and translations have different lengths.
In below example we are using traditional REPLACE function, and for same task we will use
TRANSLATE function lets see the difference.
http://www.interviewquestionspdf.com/2014/12/sql-server-interview-questions-
and.html
Now all SQL Server Interview Questions and answers at one place. Here we come with all Sql
server questions asked during SQL Interview. This is not matter if you are a fresher or
Experienced (DBA), these questions for all, From very simple to very complex. And Soon we
come with answers as well as PDF.
So now you don't need to visit here and there for Sql
Server Interview Interview/Telephonic Interview
PART 1 : SQL SERVER INTERVIEW QUESTIONS ANSWERS
9). How to strip all non-alphabetic characters from string in SQL Server?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
11). Suppose that you have a table with AreaID but for that column you forgot set Identity.
later you got it. Now you want to set identity without effecting the current records, and you
only enabled Identity with seed 1. Then what would be the next value for AreaID in our
below table example?
11.1). How to pass an array(or a table variable) into a SQL Server stored procedure?
17). How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
18). What is Collation?
21). What is the difference between ROW_NUMBER and Ranking function in SQL SERVER?
22). Difference between Where clause and Having clause in SQL Server?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
25). In Linq Query why from clause come first as select statement ?
31). What is the difference between table and view in sql server?
38). What is the difference between a DDL trigger and a DML trigger?
40). Which TCP/IP port does SQL Server run on? How can it be changed?
43). What are the difference between clustered and a non-clustered index?
50). What will be the result of this query. select * from TableName order by 1 .Will this query
throw an error?
50.1). How to get specific string/Date from a string in SQL Server using TSQL?
51). What are the different index configurations a table can have?
52). What are the different types of BACKUPs avaialabe in SQL Server 2005?
55). What's the difference between a primary key and a unique key?
63). What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
65). What database does SQL Server use for temporary tables?
67). What are the authentication modes in SQL Server? How can it be changed?
68). Which command using Query Analyzer will give you the version of SQL server and
operating system?
69). What is service Broker?
72). What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
74). .........?
75). Can a stored procedure call itself or recursive stored procedure? How much level SP
nesting is possible?
76). What is Log Shipping?
77). Name 3 ways to get an accurate count of the number of records in a table?
78). What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of
having it OFF?
79). What is the difference between a Local and a Global temporary table?
80). What is the STUFF function and how does it differ from the REPLACE function?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
81). What is the difference between TEMP tables and Variable Tables?
83). What are the different Index configurations a table can have?
87). What are Statistics? How can you find it in SQL Server?
88). How you can remove time part of datetime in SQL Server?
93). What is the difference between INSTEAD OF TRIGGER and AFTER Trigger?
111). What is a table called, if it has neither Cluster nor Non-cluster Index? What is it used
for?
112). Can SQL Servers linked to other servers like Oracle?
118). ..?
123). How do you check collation and compatibility level for a database?
126). When I delete data from a table, Does SQL Server reduce the size of table?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
150). How do you find list of schema names and table names from the database?
156). What are the different types of System database inside SQL Server?
164). What are the new data types introduced in SQL Server 2012?
169). Can we write Sub Queries into Simple Select Using join and CTE?
175). How do you copy data from one table to another table?
179). How do you stop a log file from growing too big?
182). What are the main performance differences between varchar and nvarchar SQL Server
data types?
183). What is the difference between varchar and nvarchar?
184). How do I insert multiple rows WITHOUT repeating the “INSERT INTO dbo.Blah” part of
the statement?
185). What is the difference between Index Seek and Index Scan?
192). How do you copy tables, schemas, and views from one sql server to another SQL
Server?
193). Where are SQL Server user names and passwords stored in?
198). How many maximum Identity columns we can have in a single table?
209). What is the difference between data mirroring and log shipping?
210). What are the different backup options within SQL Server?
212). How to add NOT NULL constraint on existing column? Write query
219). How to execute Dynamic SQL? 220). Can we use Variable table in Dynamic SQL? 221).
How to execute queries stored in a table? 222). How can you capture the length of column
when it is text, image and ntext data type? 223). Is it possible to import data using TSQL?
224). How can you prevent TSQL code from running on a Production server? 225). Define
Unique Key? 226). What is the use of SP_Helptext , SP_HelpIndex stored procedure? 227).
Can we change order of triggers? 228). What do you understand by Joins in SQL Server? 229).
How to disable Auto Commit in SQL Server? 230). Can we recover deleted data? 231). How to
delete Top 100 records from a table? 232). How to delete two tables using one Drop
command? 233). Can I create CTE in Trigger? 234). Can we create Variable table in Trigger?
235). Can we use cursors in Trigger? 236). Can we call Stored Procedure in Trigger? 236). Can
we call Stored Procedure in Trigger? 236.1). Can we call Stored Procedure in a View? 237).
Can I create Triggers on TEMP table? 238). Can we use PRINT Command in Triggers? 239).
How Triggers are fired? 240). Why do we use DECLARE for cursor and Variable table?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
242). How to copy data using Bulk copy when columns data type doesn’t match?
245). Can we perform DML & DDL operation on Inserted and Deleted tables?
260). Can we store Image, MP3 and binary data in SQL Server?
264). How to delete Duplicate records? 265). How to find employees hired in last
month? 266). How to find all rows that contains only numeric data? 267). How to find
primary key name if not given by the user for a particular column? 268). Can we add
two columns using ALTER command? 269). How to get row number without
ROW_NUMBER function? 270). What is Partitioned View? 271). What is the difference
between UNIQUE Key and Primary Key? 272). How to find who deleted/ dropped from
Transaction log? 273). Can we ALTER two columns using ALTER command? 274). How
to clean Buffer in SQL Server? 275). How to clear Execution Plan cache? 276). How
can we check for existence of any object in database? 277). What is meant by differed
name resolution in SQL Server? 278). How to find Organization Employee Hierarchy
using SQL? 279). How does a recursive CTE works? 280). What is Auditing inside SQL
Server? 281). What is the difference between GETDATE() and SYSDATETIME()? 282).
How do you check if Automatic Statistic Update is enabled for a database? 283). What
are the limitations of view? 284). How to find department with highest number of
ONUPDATE? 286). What are the uses of System tables? 287). What are WAIT Types?
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
292). Sql server difference between update lock and exclusive lock?
293). Sql server difference between windows authentication and sql server authentication?
297). Sql server difference between shrink database and shrink files?
307). What is the difference between SQL Server standard and web edition?
316). Write down the query to get the list of tables changed with in the database in last 5
days?
317). Write a query to insert your name 1000 times without Using While Loop in SQL
Server?
318). SQL Server 2016 came with new way to drop object if exist, Explain it.(DROP IF EXIST)
319). Can you drop the database on which you are using/working currently, in same
session?
320). Write down the T-SQL Script to print then number from 1 to 10?
321). What is the difference between Wide and Nonwide tables in SQL Server?
324). What is the difference between DateTime and DateTimeOffset data types in SQL
Server?
325). What is Slot Array in Sql Server? How it is related to Database Page?
326). What is the extension for trace file in SQL Server Profiler?
327). How to pass an array(or a table variable) into a SQL Server stored procedure?
331). Name any three standard trace templates provided by SQL Server Profiler?
333). How to strip all non-alphabetic characters from string in SQL Server?
336). Name the SQL Server functions used to encrypt and decrypt password?
341). What is the difference between Master, MSDB,TempDB and Model Databases?
342). What is the main rule of first normal form? second form ? third form?
343). What is the difference between Data files and Log Files in Sql Server?
344). How you will select all records using TOP keyword in SQL Statement, even you don't
know the count of table?
345). How you will change the font size/style in SQL Server?
GO 2
355). What will execute first tell the order of every keyword used in below
query?(Wipro/Sapient)
358). How you will replace "A" with "B" and "B" with "A" in following string "ABAB"?(HCL)
360). What would be the output of following script. (asked in TCS with more nested
question)
SQL INTERVIEWS PDF Disha Mukherjee
CREDITS::-- Vikas (interviewquestions.pdf) 2023
361). How to Generate Sequence without using Ranking functions in SQL Server?