100% found this document useful (1 vote)
458 views

Index Algorithim

The document discusses SQL Server interview questions related to new features in SQL Server 2017 such as adaptive query processing, string functions like CONCAT_WS and TRANSLATE, and support for Python. It also provides sample T-SQL statements.

Uploaded by

GaganDeepSingh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
458 views

Index Algorithim

The document discusses SQL Server interview questions related to new features in SQL Server 2017 such as adaptive query processing, string functions like CONCAT_WS and TRANSLATE, and support for Python. It also provides sample T-SQL statements.

Uploaded by

GaganDeepSingh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

SQL Server 2017 Interview Questions with Answers

2-3 minutes

Here we come with latest SQL Server interview questions which is related to latest SQL Server 2017 that’s why
all questions are also latest if you are looking for latest then this is the place. :)

Let’s check your knowledge.

What do you understand by Adaptive query processing launched in SQL Server 2017?
SQL Server 2017 and Azure SQL Database introduce a new generation of query processing improvements that
will adapt optimization strategies to your application workload’s runtime conditions.

Name all three Adaptive query processing features?


In SQL Server 2017 and Azure SQL Database there are three adaptive query processing features by which you
can improve your query performance:
Batch mode memory grant feedback.
Batch mode adaptive join.
Interleaved execution.

Write T-SQL statement to enable adaptive query processing?


You can make workloads automatically

adaptive query processing by enabling compatibility level 140 for the database. You can set this using Transact-
SQL. For example:
ALTER DATABASE [WideWorldImportersDW] SET COMPATIBILITY_LEVEL = 140;

Name the new string function which is very useful to generate csv file from a table?
CONCAT_WS is new function launched in SQL Server 2017 its takes a variable number of arguments and
concatenates them into a single string using the first argument as separator. It requires a separator and a
minimum of two arguments.
It is very helpful in generate comma or pipe separated csv file content.
Example:

What do you understand by TRANSLATE in SQL Server 2017?


TRANSLATE is a new string function launched in SQL Server 2017, It is very helpful to 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 let’s see the difference.
What is the use of new TRIM function?
It Removes the space character char(32) or other specified characters from the start or end of a string.

Is SQL Server 2017 support Python?


Yes

SQL SERVER QUERY INTERVIEW QUESTIONS


- ANSWERS WITH EXAMPLE FOR FRESHER:
SET-1 SOLUTION
4-5 minutes

SQL SERVER/Oracle/MySQL INTERVIEW QUERY SET: 1 WITH ANSWERS/SOLUTION

Here I come with more than 100 SQL Server queries for Database/.NET/SQL Server developers, soon you will
get more than 100 SQL query set in pdf/eBook format. So keep visiting this page.
This is for both fresher and experienced developers which would be helpful for Interview preparation.
First try to answer these queries and put comment. After that see the answers of each query in solution set.
Download as PDF

Tables: -
MS SQL/Oracle/MySQL INTERVIEW QUERY FOR FRESHER SET: 1 SOLUTION

1. Write a query to get all employee detail from "EmployeeDetail" table

ANS:
MS SQL Server: SELECT * FROM EmployeeDetail

Oracle: SELECT * FROM EmployeeDetail

MySQL: SELECT * FROM EmployeeDetail

2. Write a query to get only "FirstName" column from "EmployeeDetail" table


ANS:
MS SQL Server: SELECT FirstName FROM EmployeeDetail

Oracle: SELECT FirstName FROM EmployeeDetail

MySQL: SELECT FirstName FROM EmployeeDetail

3. Write a query to get FirstName in upper case as "First Name".


ANS:
MS SQL Server: SELECT UPPER(FirstName) AS [First Name] FROM EmployeeDetail
Oracle: SELECT UPPER(FirstName) AS [First Name] FROM EmployeeDetail
MySQL: SELECT UPPER(FirstName) AS [First Name] FROM EmployeeDetail
4. Write a query to get FirstName in lower case as "First Name".
ANS:
MS SQL Server: SELECT LOWER(FirstName) AS [First Name] FROM EmployeeDetail
Oracle: SELECT LOWER(FirstName) AS [First Name] FROM EmployeeDetail
MySQL: SELECT LOWER(FirstName) AS [First Name] FROM EmployeeDetail

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

6. Select employee detail whose name is "Vikas"


ANS:
MS SQL Server: SELECT * FROM EmployeeDetail WHERE FirstName = 'Vikas'

Oracle: SELECT * FROM EmployeeDetail WHERE FirstName = 'Vikas'

MySQL: SELECT * FROM EmployeeDetail WHERE FirstName = 'Vikas'


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:
MS SQL Server: SELECT * FROM EmployeeDetail WHERE FirstName like '%k%'

Oracle: SELECT * FROM EmployeeDetail WHERE FirstName like '%k%'

MySQL: SELECT * FROM EmployeeDetail WHERE FirstName like '%k%'

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 SERVER INTERVIEW QUERY WITH
EXAMPLE 4 FRESHER AND EXP: SET-2 WITH
SOLUTION
3 minutes

Hey this is Set 2 of SQL Query series, this set is for 0-2 years experienced developers, if you have more than 2
years exp. then don't think that this set not for you here you can remind may things, if you think that you can
answer every query here then try and leave comment honestly and after that check your answer in Solution set.
This is question set only.
To see the solution follow the link which exist in the end of this post. If you want Sql server query interview
question pdf then waits for some days, we will soon come with pdf. which will contain more than 100 sql server
query with solution.

So let’s try this set.

SQL SERVER QUERY INTERVIEW QUESTION SET: 2

Related Tables:-

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 '%[%]%'

--According to our table it would return 0 rows, because no name containg '%'

15). Get all unique "Department" from EmployeeDetail table.


Ans: SELECT DISTINCT(Department) FROM [EmployeeDetail]

16). Get the highest "Salary" from EmployeeDetail table.


Ans: SELECT MAX(Salary) FROM [EmployeeDetail]

17). Get the lowest "Salary" from EmployeeDetail table.


Ans: SELECT MIN(Salary) FROM [EmployeeDetail]

***SQL SERVER DATE RELATED INTERVIEW QUERY***

18). Show "JoiningDate" in "dd mmm yyyy" format, ex- "15 Feb 2013"
Ans: SELECT CONVERT(VARCHAR(20),JoiningDate,106) FROM [EmployeeDetail]
19). Show "JoiningDate" in "yyyy/mm/dd" format, ex- "2013/02/15"
Ans: SELECT CONVERT(VARCHAR(20),JoiningDate,111) FROM [EmployeeDetail]

20). Show only time part of the "JoiningDate".


Ans: SELECT CONVERT(VARCHAR(20),JoiningDate,108) FROM [EmployeeDetail]

DATETIME : SQL SERVER QUERIES


INTERVIEW FOR EXPERIENCED 2-3 YEARS
WITH EXAMPLE : SET-3
2-3 minutes

SQL DATETIME QUERIES INTERVIEW QUESTIONS WITH ANSWERS

TOP 10 DATETIME RELATED INTERVIEW QUERIES

If you think this set contain easy question then you can start with Set 9 (tricky queries)and be continue.

This is the 3rd set(21-30) of SQL INTERVIEW QUERIES SET, This set is for experienced developers, it's
containing datetime related interview question with answers, So test your sql skill by answers following queries
by yourself first.
So let’s take it as a SQL Queries Quiz

Related Table: -
***SQL DATETIME RELATED QUERIES***

21). Get only Year part of "JoiningDate".


Ans: SELECT DATEPART(YEAR, JoiningDate) FROM [EmployeeDetail]

22). Get only Month part of "JoiningDate".


Ans: SELECT DATEPART(MONTH,JoiningDate) FROM [EmployeeDetail]

23). Get system date.


Ans: SELECT GETDATE()

24). Get UTC date.


Ans: SELECT GETUTCDATE()

25). Get the first name, current date, joiningdate and diff between current date and joining date in
months.
Ans: SELECT FirstName, GETDATE() [Current Date], JoiningDate,
DATEDIFF(MM,JoiningDate,GETDATE()) AS [Total Months] FROM [EmployeeDetail]

26). Get the first name, current date, joiningdate and diff between current date and joining date in days.
Ans: SELECT FirstName, GETDATE() [Current Date], JoiningDate,
DATEDIFF(DD,JoiningDate,GETDATE()) AS [Total Months] FROM [EmployeeDetail]

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'

30). Get how many employee exist in "EmployeeDetail" table.


Ans: SELECT COUNT(*) FROM [EmployeeDetail]

SALARY: SQL INTERVIEW QUERIES


EXAMPLES FOR FRESHER AND EXPRINCED
SET-4
2-3 minutes

Hey this is 4th set of SQL Interview Queries series, this set containing IN, NOT IN and Salary related SQL
queries which is asked most frequently in every sql server interview, so this set containing most important
salary related interview queries with example.

So let’s start SQL Quiz. SET-4 (31-41)


Related Tables:-

31. Select only one/top 1 record from "EmployeeDetail" table.


Ans: SELECT TOP 1 * FROM [EmployeeDetail]

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 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 than 600000
Ans: SELECT * FROM [EmployeeDetail] WHERE Salary BETWEEN 500000 AND 600000

41. Select second highest salary from "EmployeeDetail" table.


Ans: SELECT TOP 1 Salary FROM

(SELECT TOP 2 Salary FROM [EmployeeDetail] ORDER BY Salary DESC) T ORDER BY Salary ASC

GROUP BY: SQL INTERVIEW QUERIES


QUESTIONS AND ANSWERS WITH EXAMPLE
FOR EXPERIENCED SET-5
3 minutes

SQL GROUP BY & HAVING INTERVIEW QUERIES


This is 5th post related to SQL interview queries with examples. In this post we will discuss most important
SQL server queries, which is related to "Group by" keyword. Group by related queries is most frequently asked
in all interview. This post contains questions for both fresher and experienced developers.
About GROUP BY:-
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or
more columns.

Related Table:

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


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 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 ProjectName HAVING
COUNT(*)>1

JOIN: SQL JOIN QUERIES INTERVIEW


QUESTIONS AND ANSWERS PDF SET-6
4-5 minutes

MS SQL SERVER JOINS RELATED INTERVIEW QUERIES

Here we come with latest/new sql server joins queries, as you know joins related queries/questions are most
frequently asked in any database related interview to puzzle developers. So this set of interview question
contains basic joins related interview question which can be asked in any company interview, And Company
like TCS/HCL/Infosys/Nagarro mostly asked following type of queries. So before attend interview be preparing
for it. This set of question is for experienced developers(2-3 years).
Upcoming set will contain more complex joins related interview questions which you will face time.
I promise you will be surprise to see next set of join queries, because you will face it first time.
At last you will be able to download all query in pdf format. So start from basic.

Related Tables:

SQL JOINS RELATED INTERVIEW QUERIES

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 [ProjectDetail] B ON
A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName
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 [ProjectDetail] B ON
A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName

53(35.1) Get employee name, project name order by firstname from "EmployeeDetail" and
"ProjectDetail" for all employee if project is not assigned then display "-No Project Assigned".
Ans: SELECT FirstName, ISNULL(ProjectName,'-No Project Assigned')
FROM [EmployeeDetail] A LEFT OUTER JOIN [ProjectDetail] B ON A.EmployeeID = B.EmployeeDetailID
ORDER BY FirstName

54. Get all project name even they have not matching any employeeid, in left table, order by firstname
from "EmployeeDetail" and "ProjectDetail".
Ans: SELECT FirstName,ProjectName FROM [EmployeeDetail] A RIGHT OUTER JOIN [ProjectDetail] B
ON A.EmployeeID = B.EmployeeDetailID ORDER BY FirstName
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 [ProjectDetail] 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 ON
A.EmployeeID = B.EmployeeDetailID WHERE FirstName IS NULL

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 [ProjectDetail] P ON E.EmployeeID = P.EmployeeDetailID
WHERE EmployeeID IN (SELECT EmployeeDetailID FROM [ProjectDetail] GROUP BY EmployeeDetailID
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 ProjectDetails group by ProjectName
having COUNT(1)>1)

COMPLEX/Tricky JOINS: SQL SERVER JOINS


QUERIES INTERVIEW QUESTIONS AND
ANSWERS EXAMPLES FOR EXPERIENCED
SET-7
4-5 minutes

LETS START

--60. What would be the output of the following query (INNER JOIN)

SELECT T1.ID, T2.ID FROM TBL_1 T1 INNER JOIN TBL_2 T2 ON T1.ID = T2.ID

--ANS:

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

SELECT T1.ID, T2.ID FROM TBL_1 T1 CROSS JOIN TBL_2 T2

--ANS: Output would be same as 60th Question

--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:

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

--(LEFT OUTER JOIN)

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:

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

DDL: MS SQL SERVER QUERIES INTERVIEW


QUESTIONS FOR EXPERIENCED DEVELOPER
SET-8
2 minutes

DDL RELATED SQL SERVER INTERVIEW QUERIES

This set contains most frequently asked ddl related interview queries, It contains query related to Identity
column, Primary key and foreign key.

So let’s start: SQL DDL RELATED QUERIES

--78. Write down the query to create employee table with Identity column([EmployeeID])
--ANS:

CREATE TABLE EmployeeDetail( [EmployeeID] INT IDENTITY(1,1) NOT NULL, [FirstName]


VARCHAR(50) NULL,[LastName] NVARCHAR(50) NULL, [Salary] DECIMAL(10, 2) NULL,
[JoiningDate] DATETIME NULL, [Department] NVARCHAR(20) NULL,[Gender] VARCHAR(10) NULL)

--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] NVARCHAR(50) NULL,[LastName] NVARCHAR(50) NULL, [Salary] DECIMAL(10, 2)
NULL, [JoiningDate] DATETIME NULL, [Department] NVARCHAR(20) NULL,[Gender] VARCHAR(10)
NULL)

--80. Write down the query to create employee table with primary key (EmployeeID)
--ANS:

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, [JoiningDate] DATETIME NULL, [Department] NVARCHAR(20) NULL,[Gender] VARCHAR(10)
NULL)

--81. How to set Primary key using Alter command


--ANS:

ALTER TABLE EmployeeDetail ADD PRIMARY KEY (P_EmployeeID)


--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)REFERENCES EmployeeDetail(EmployeeID)

SELECT QUERIES: Small Tricky SQL SERVER


Queries Interview Questions and Answers SET-9
4-5 minutes

SET-9

Objective Type: Small Tricky SQL SERVER Queries Interview Questions and Answers for experienced
and fresher

Hey here I come with tricky sql query which are frequently asked in sql/database interview for puzzle sql
developer. This would be best for you to go through following sql server interview queries before attend
interview. This series contain 17th Objective type Interview Questions (Sql server query), all query seems easy
but it would be complex situation when you face these query in Interview time.

So following query seems very easy but play roll of complex/tricky sql query.

So let’s start(see answers in end of this post)

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

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

90).SELECT SELECT 'VIKAS'

--output of this query would be.

A). Throw error

B). 'VIKAS'

C). VIKAS

D). VIKAS1

91). SELECT * FROM 'Country'

--output of this query would be.

A). Throw error

B). Select all data from country table

C). Country

D). Throw error

92). SELECT * FROM Country , EmployeeDetail

--output of this query would be.

A). Throw error

B). Output will be cross join of both tables

C). Output will be inner join

D). Output will be only Country table data

93). SELECT COUNT(*) + COUNT(*)

--output of this query would be.

A). Throw error

B). 0

C). 1

D). 2

94). SELECT 'VIKAS' FROM Country

--output of this query would be.

A). Throw error


B). Display one time "VIKAS"

C). Display "VIKAS" as many rows in Country table

D). Will select country table data

95).SELECT SUM(1+2*3)

--output of this query would be.

A). Throw error

B). 9

C). 7

D). 6

96). SELECT MAX(1+2*3)

--output of this query would be.

A). Throw error

B). 3

C). 7

D). 6

97).SELECT MAX(1,3,4)

--output of this query would be.

A).Throw error

B). 1

C). 3

D). 4

98).SELECT MAX('VIKAS')

--output of this query would be.

A).Throw error

B). 1

C). 2

D). VIKAS

99).Select Count(SELECT CountryID FROM Country)


--output of this query would be.

A).Throw error

B). Will display count of country table

C). 0

--output of this query would be.

A). Throw error

B). 1

C). 2

D). 11

101). SELECT '1' + 1

--output of this query would be.

A). Throw error

B). 1

C). 2

D). 11

102). SELECT NULL + 5

--output of this query would be.

A). Throw error

B). NULL

C). 5

D). 0

103). SELECT NULL + '1'

--output of this query would be.

A). Throw error

B). NULL

C). 1

D). 0

104). SELECT 1 WHERE NULL = NULL


--output of this query would be.

A). Throw error

B). NULL

C). 1

D). NOTHING WILL RETURN BY This (0 rows will be returned by this) because the condition is false

105). SELECT SUM(1)

--output of this query would be.

A). Throw error

B). NULL

C). 1

D). 0

106). SELECT SUM('1')

--output of this query would be.

A). Throw error

B). NULL

C). 1

D). 0

107). SELECT SUM(NULL)

--output of this query would be.

A). Throw error

B). NULL

C). 1

D). 0

108). SELECT 6/0

--output of this query would be.

A). Throw error(Divide by zero error encountered.)

B). NULL

C). 1
D). 0

109). SELECT 0/0

--output of this query would be.

A). Throw error(Divide by zero error encountered.)

B). NULL

C). 1

D). 0

110). SELECT 0/9

--output of this query would be.

A). Throw error (Divide by zero error encountered.)

B). NULL

C). 1

D). 0

Click here for be continue

ANSWERS:

110) D 109) A 108) A 107) A 106) A 105) C 104) D 103) B 102) B 101) C 100) C 99) A 98) D 97) A 96) C

95) C 94) C 93) D 92) B 91) A 90) A 89) C 88) D 87) A 86) D 85) C 84) D 83) B

MS SQL SERVER TRICKY/COMPLEX


INTERVIEW QUERIES QUESTIONS ANSWERS:
PDF SET-10
3-4 minutes

MOST COMPLEX/TRICKY MS SQL SERVER (2005-08-12) QUERIES INTERVIEW QUESTIONS


SET-10

This set contains most Tricky/complex MS SQL Server queries interview questions for experienced developers.
If you think you are expert in sql, then go through this set and check that you are right or not.
This set contains most puzzled/complex interview queries so that this set is for experienced developers, even
DBA can also try this set to check their join concept, so if you have more than 5 years of exp. then this is for
you. Try it, .PDF will be available soon.

Related Tables:

--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:-
--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:-
AND THE VERY VERY COMPLEX QUERY HERE

--103: You have a table(FuelDetail) with ID, Fuel, And Date columns.

--Fuel column is containing fuel quantity at a particular time when car start traveling. So we need to find out
that when the driver fill Petrol in his/her car.

--By FuelDetail Table image on the top of this post, you can understand the query.

--Car start driving at 10 Am on 25th April with petrol (10 liter)

--at 11 AM Petrol was 9 liters

--at 12 AM petrol was 8 liters

--at 2 PM (14) petrol was 12 liters...

--This means that he/she fill the petrol at 25th April 2014 at 2PM

--Next time he fill petrol at 7PM 25th April 2014

--and Next time he fill petrol at 11PM 25th April 2014

ANS:

Solution 1:

SELECT c1.fuel AS [Fuel quantity Now],c1.[Date],c.fuel AS [Fuel quantity Before],c.[Date]

FROM FuelDetail c

JOIN

FuelDetail c1 ON c1.[Date] =(SELECT MIN([Date]) FROM FuelDetail WHERE [Date]>c.[Date] )

WHERE c1.fuel>c.fuel

Solution 2:(by Eduardo Ramires) see in comment section

Select FD.ID, FD.Fuel, FD.Date,FD1.Fuel [Fuel Quantity Before],FD1.Date

from FuelDetail FD inner join FuelDetail FD1 on FD1.ID = (FD.ID-1)

and FD1.Fuel < FD.Fuel

Output will be:


COMPLEX / DIFFICULT SQL QUERIES
EXAMPLES FOR INTERVIEW SET-8.4
2 minutes

Here we again come with the hard/tricky sql server interview queries examples for sql server Interview
preparations. Following is query is based on sql joins, these query will improve your join concept, and you can
evaluate yourself by answering these queries.
So first try to answer every query without see the answer, then compare the answers.

If you have not read our previous set of complex sql interview queries then first go through following link,
Click here for read previous set of queries

HARD/TRICKY/COMPLEX SQL JOIN QUERIES EXAMPLES

104) . What would be the out-put of the following Sql query?

SELECT A.A FROM (SELECT 1 A, 2 B) A

JOIN (SELECT 1 A,1 B)B ON A.A = B.B

Options:

105). What would be the out-put of the following Sql query?

SELECT B.A FROM (SELECT 1 A) A

JOIN (SELECT 1 A, 2 B)B ON A.A = B.A

Options:
106). What would be the out-put of the following Sql query?

SELECT B.A FROM (SELECT 1 A) A

JOIN (SELECT 1 A, 2 B)B ON A.A = B.B

Options:

107). What would be the out-put of the following Sql query?

SELECT * FROM (SELECT 1 A UNION ALL SELECT 2 B) A

JOIN (SELECT 1 A,2 B UNION ALL SELECT 1 A, 1 B)B ON A.A = B.B

Options:

108). What would be the out-put of the following Sql query?

SELECT * FROM (SELECT 1 A UNION ALL SELECT 2 B) A

JOIN (SELECT 1 A,2 B)B ON A.A = B.B

Options:

SQL SERVER DATA TYPES INTERVIEW


QUESTIONS ANSWERS FOR FRESHER AND
EXPERIENCED
6-7 minutes
http://www.interviewquestionspdf.com/2015/08/sql-server-data-types-interview.html

SQL SERVER DATATYPES INTERVIEW QUESTIONS

What do you understand by Data-types in sql server?

Ans: SQL Server data types defines the characteristic of the data that is stored in a column. Each column,
variable and expression has related data type in SQL.

How you should choose data type for particular column when you create a table?

Ans: The data type should be chosen based on the information you wish to store. for example, you would not
use an integer data type for storing employee name.

What is the very useful datatype introduced in SQL Server 2016?

Ans: JSON datatype

What are the two types of character data SQL Server supports?

Ans: Regular and Unicode

What are the Regular character data types?

Ans: Char and VarChar

What are the Unicode character data types?

Ans: NChar and NVarChar

How are literal strings expressed with Regular character column?

Ans: Single quote 'text'.

How are literal strings expressed with Unicode character column?

Ans: Must Start with N'text'.

What can you define with variable length character data types?

Ans: VARCHAR(MAX)

How large is VARCHAR(MAX)?

Ans: 8000 Bytes in line.

Name any five date and time data types?

Ans: 1.) DATETIME 2.) SMALLDATETIME 3.) DATE 4.) TIME 5.) DATETIME2 6.) DATETIMEOFFSET

What does the PARSE function do?

Ans: Parse a value as a requested type and indicate a culture. Syntax? PARSE ('date' AS datatype USING
culture)
What happens when you only want to work with time in a DATETIME data type?

Ans: SQL Server stores the date as Jan 1 1900.

What do you understand by Timestamp, Difference between Datetime and Timestamp datatypes?

Ans: Datetime: Datetime is a datatype. Timestamp: Timestamp is a data type that exposes automatically
generated binary numbers, which are guaranteed to be unique within a database. timestamp is used typically as
a mechanism for version-stamping table rows. The storage size is 8 bytes.

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.

What do you understand by rowversion datatype, have you ever used rowversion?

Ans: Rowversion is a data type that exposes automatically generated, unique binary numbers within a database.
rowversion is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The
rowversion data type is just an incrementing number and does not preserve a date or a time.

Timestamp is the synonym for the rowversion data type and is subject to the behavior of data type synonyms. In
DDL statements, use rowversion instead of timestamp wherever possible.

Example:

CREATE TABLE ExampleTable2 (PriKey int PRIMARY KEY, VerCol rowversion);

OR

CREATE TABLE ExampleTable1 (PriKey int PRIMARY KEY, VerCol timestamp);

How many columns a table can, with timestamp column?

Ans: A table can contain only one timestamp column.

What are the differences between Datetime and Datetime2 datatypes?

Following are the difference between these two datatypes

DateTime DateTime2[(n)]
1 - Min
1753-01-01 00:00:00 0001-01-01 00:00:00
Value
2 - Max
9999-12-31 23:59:59.997 9999-12-31 23:59:59.9999999
Value
8 bytes is required to store the Depends on the millisecond precision; 6 to 8 bytes are required to
3 - Size
value store the value
4 - Syntax S

DATETIME

DECLARE @CurrentDate DATETIME

Syntax is DATETIME2 [ (Fractional Seconds Precision) ],


with a default value of 7 for the fractional seconds precision.
DECLARE @CurrentDateTime DATETIME2(7)

5 - Accuracy Accuracy is up to 0.00333 second Accuracy is up to 100 nanoseconds 6 - Time range Time
range is between 00:00:00 through 23:59:59.997 Time range is between 00:00:00 through 23:59:59.9999999 7-
Current Date and Time function SELECT GETDATE()
2015-08-26 22:56:34.670 SELECT SYSDATETIME()
2015-08-26 22:56:34.6736314 8 - Addition or subtraction Addition or subtraction to numbers is directly
allowed.
Ex
SELECT GETDATE() + 1 Addition or subtraction to numbers is not directly allowed. The function
DATEADD should be used
Ex SELECT DATEADD(DAY,1,SYSDATETIME())

But SELECT SYSDATETIME() +1 will throw error

9 - Precision No precision or scale can be specified Precision or scale is from 0 to 7 digits.


Ex: Datetime2(6) 10 - Availablity Available from SQL Server 2000 and onwards Available only from SQL
Server 2008 and onwards

What are the differences between Datetime and DateTimeOffset datatypes?

Following are the difference between these two datatypes

DateTime DateTimeOffset[(n)]
1 - Min 0001-01-01 00:00:00 +05:30
1753-01-01 00:00:00
Value This datatype also display time zone.
2 - Max
9999-12-31 23:59:59.997 9999-12-31 23:59:59.9999999 +05:30
Value
3 - Time
zone offset Time zone not supported -14:00 through +14:00
range
Depends on the millisecond precision; 8 to 10 bytes are
4 - Size 8 bytes is required to store the value
required to store the value
Syntax is DATETIMEOFFSET [ (Fractional Seconds
Syntax is simply DATETIME Precision) ],
with a default value of 7 for the fractional seconds
5 - Syntax
DECLARE @CurrentDate DATETI precision.
ME
DECLARE @CurrentDateTime DATETIMEOFFSET(5)
6
Accuracy is up to 0.00333 second Accuracy is up to 100 nanoseconds
- Accuracy
7 - Time Time range is between 00:00:00 Time range is between 00:00:00 through
range through 23:59:59.997 23:59:59.9999999
8- Current
SELECT SYSDATETIMEOFFSET()
Date and SELECT GETDATE()
Time 2015-08-26 22:56:34.670
2015-08-27 00:11:04.3897800 +05:30
function
Addition or subtraction to numbers is not directly allowed.
The function DATEADD should be used
9 Addition or subtraction to numbers is
Ex SELECT DATEADD(DAY,1,SYSDATETIMEOFFSE
- Addition directly allowed.
T())
or Ex
subtraction SELECT GETDATE() + 1
But SELECT SYSDATETIMEOFFSET() +1 will throw
error
10 Precision or scale is from 0 to 7 digits.
No precision or scale can be specified
- Precision Ex: DATETIMEOFFSET(5)
11
Available from SQL Server 2000 and
- Availablit Available only from SQL Server 2008 and onwards
onwards
y

Let’s suppose today is 27th Aug 2015, What will happend when we run this following script?

Is this script through error or not?

Ans: it will add 2 days in current date time and according to date specified it will display 29th Aug 2015 with
current time.

What is User-defined data type in SQL Server?

Ans: User-defined data types also know as Alias types are based on the system data types in Microsoft® SQL
Server™ 2000. User-defined data types can be used when several tables must store the same type of data in a
column and you must ensure that these columns have exactly the same data type, length, and nullability. For
example, a user-defined data type called postal_code could be created based on the char data type.

Can we use User-defined data type in table variable?

Ans: No

Can you alter user-defined data types?

Ans: No, If you want to change it then first you need to drop it, and then you need to re-create with your
changes.

User-defined data types are located in your databaes node under?

Ans: Programmability > Types > User-Defined Data TYpes

What is SWITCHOFFSET function?

Ans: SWITCHOFFSET function is used to convert the time from one time zone to another time zone, and it
will work for date time offset fields(DatetimeOffset datatype).

Syntex: SWITCHOFFSET ( DATETIMEOFFSET, time_zone )

What is SPARSE data option introduced in SQL Server 2008, when to use it?

Ans: The sparse data option is a new SQL Server 2008 feature for tields you expect to be predominantly null.
Using the sparse data option, you can instruct SQL Server to not have nulls consume space in sparsely
populated fields.
SPARSE column are better at managing NULL and ZERO values in SQL Server. It does not take any space in
database at all. If column is created with SPARSE clause with it and it contains ZERO or NULL it will be take
lesser space then regular column (without SPARSE clause).

We can use this option when we sure that our column will contain mostly null values(or zero) etc.

Example : Create table Employee(ID INT, Name Varchar(20) NULL, Salary Money NULL, BonusAmount
Money SPARSE NULL)

What are the Advantages and Disadvantages of SPARSE column?

Ans: Advantages of SPARSE column are:

-INSERT, UPDATE, and DELETE statements can reference the sparse columns by name. SPARSE column
can work as one XML column as well.

-SPARSE column can take advantage of filtered Indexes, where data are filled in the row.

-SPARSE column saves lots of database space when there are zero or null values in database.

Disadvantages of SPARSE column are:

-SPARSE column does not have IDENTITY or ROWGUIDCOL property.

-SPARSE column can not be applied on text, ntext, image, timestamp, geometry, geography or user defined
datatypes.

-SPARSE column can not have default value or rule or computed column.

-Clustered index or a unique primary key index can not be applied SPARSE column. SPARSE column can not
be part of clustered index key.

-Table containing SPARSE column can have maximum size of 8018 bytes instead of regular 8060 bytes.

-A table operation which involves SPARSE column takes performance hit over regular column.

Ref: http://blog.sqlauthority.com/2008/07/14/sql-server-2008-introduction-to-sparse-columns-part-2/

Does SPARSE cluse use with the Geography or Geometry data types?

Ans: No, Sparse cannot be used for every data type. It can't be used with Geography or Geometry data types as
well as old LOB types(text, ntext, image).

Can a primary key be a sparsed column?

Ans: No

What is the only data type avaliable in SQL Server which can store GPS data that has been defined by
the OGC()?

Ans: Geography data type

What is the function which returns the closest path between two Geography points in meters?

Ans: STDistance()
What is the difference between Varchar() and Nvarchar() datatypes?(Most Imp)

What would be the output of the following script?

DECLARE @Name VARCHAR(20)

SET @Name = 'विकास अहलाित'

SELECT @Name

Ans: Output would be "????? ??????"

What would be the output of the following script?

DECLARE @Name NVARCHAR(20)

SET @Name = 'विकास अहलाित'

SELECT @Name

Ans: Output would be "????? ??????"

How will you print or save name as 'विकास अहलाित'?

Ans: To save Unicode character we need to take data type nvarchar and string must be with "N", otherwise you
will lost the even you have Nvarchar data type you can see in the above question

DECLARE @Name NVARCHAR(20)

SET @Name = N'विकास अहलाित'

SELECT @Name

Output would be: विकास अहलाित

SQL Server View Related Interview Questions


Answers
3-4 minutes

MS SQL SERVER VIEW RELATED INTERVIEW QUESTIONS ANSWERS

1). What do you understand by View in SQL Server?


Ans: A view is a virtual table whose contents are defined by a query. or a view is a stored SELECT statement
that works like a virtual table.
2). What are the types of view?
Ans:

 Indexed Views
 Partitioned Views
 System Views

Below are the types of View in SQL Server

 Indexed Views:An indexed view is a view that has been materialized. This means the view definition
has been computed and the resulting data stored just like a table. You index a view by creating a unique
clustered index on it. Indexed views can dramatically improve the performance of some types of
queries. Indexed views work best for queries that aggregate many rows. They are not well-suited for
underlying data sets that are frequently updated.
 Partitioned Views:A partitioned view joins horizontally partitioned data from a set of member tables
across one or more servers. This makes the data appear as if from one table. A view that joins member
tables on the same instance of SQL Server is a local partitioned view.
 System Views:System views expose catalog metadata. You can use system views to return information
about the instance of SQL Server or the objects defined in the instance. For example, you can query the
sys.databases catalog view to return information about the user-defined databases available in the
instance.

3). How many column a view can contain?


Ans: 1024

4). The tables that makes up a view are called as?


Ans: Base tables

5). Can you create a view by using temporary table?


Ans: No

6). Can you create a view by using another view(nesting views)?


Ans: Yes! you can build view on other views and nest them up to 32 levels, Basing a view on another view is
known as nesting views.

7). What are the limitations of a View?

This article is quite related to View Limitation in SQL Server 2008. Although it's one of the core features of SQL Server,
there are many limitations associated with it.

A few that I have encountered are listed below:

1. You can't create a parameterized view, in other words you can't create a view with a parameter.
For example:

CreateView vw_OrdersNorthwind
@OrderID int
As
select CustomerID,ShipCity,ShipCountryfrom orders orderby OrderID desc
go

Error: It will give you an incorrect syntax error.

2. Views are not based on temporary tables, if we try to create one then it gives us a massage.

An example is as follows:
Step 1: Temp table creation

createtable ##MobileDetails
( ID int NOTNull ,MobileNamenvarchar(50),CompanyName nvarchar (50))

Step 2: Insert a few records into the TempTable:

insertinto ##MobileDetailsvalues (1,'Galaxy S2','Samsung')


insertinto ##MobileDetailsvalues (1,'Nokia Lumia','Nokia')
insertinto ##MobileDetailsvalues (1,'IPhone5','IPhone');
insertinto ##MobileDetailsvalues (1,'Blackberry Z10','Blackberry');

Step 3: Creation of a view on the TempTable.

createview vw_onTempTable
as
select MobileName,CompanyNamefrom ##MobileDetails
go

An error prompted by the SQL Server after running the preceding command.

Msg 4508, Level 16, State 1, Procedure vw_onTempTable, Line 3


Views or functions are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.

3. You can't use an order by clause at the time of view creation. Kindly have a look at an example below:

Let's run the following command in the query editor of SQLServer:

CreateView vw_OrdersNorthwind
As
select OrderID,CustomerID,ShipCity,ShipCountryfrom orders orderby OrderID desc
go

It issues the error:

Msg 1033, Level 15, State 1, Procedure vw_OrdersNorthwind, Line 3


The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions,
unless TOP or FOR XML is also specified.

It clearly specifies to use TOP or FOR XML in your TSQL.

Now I make some changes in the preceding query and run it again.

CreateView vw_OrdersNorthwind
As
selecttop 100 OrderID,CustomerID,ShipCity,ShipCountryfrom orders orderby OrderID desc
go

Now select the records from the View and run this query.

Select* from vw_OrdersNorthwind


4. All the tables referenced by the view must be in the same database as the view.
5. An indexed view must be created with the SCHEMABINDING option. This option prohibits the schema of the base
tables from being changed, for example adding or dropping a column.
6. If you add any new column to a table tehn it would not be reflected in the View untill you won't run the

EXEC sp_refreshview 'ViewName'.

Don't use Select *, just use a select specific columnnames


It's a best practice to create a view with SCHEMABINDING using this, the base table will not be modified.

7. You can't use count (*) in a view creation query, for example:

CreateView vw_OrdersNorthwind
As
--select OrderID,CustomerID,ShipCity,ShipCountry from orders
selectcount(*) from orders
go

It also forces you to supply any column value.

Msg 4511, Level 16, State 1, Procedure vw_OrdersNorthwind, Line 4


Create View or Function failed because no column name was specified for column 1.

Workaround of this issue is use the following syntax:

CreateView vw_OrdersNorthwind
As
--select OrderID,CustomerID,ShipCity,ShipCountry from orders
select count(*) As Total from orders
go

select * from vw_OrdersNorthwind

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.

11). Can we use WITH SCHEMABINDING in Stored Procedures?


Ans: WITH SCHEMABINDING can't be used in Stored Procedures.

12). Will below script correct or not? If not what is wrong with it?

CREATE VIEW vProduct_WithSchemabinding

WITH SCHEMABINDING

AS

SELECT * FROM [Person].[Person]

Ans: If we are using WITH SCHEMABINDING then we can't use "Select *";
This will throw "Syntax '*' is not allowed in schema-bound objects." error

Correct:

CREATE VIEW vProduct_WithSchemabinding

WITH SCHEMABINDING

AS

SELECT FirstName,LastName FROM [Person].[Person]

13). Is view store data physically apart from table or not?


Ans: A view is just a macro, it has no persistent storage.The underlying table data is stored in the MDF file. But
its not always true, Creating a clustered index on the view materializes its data on disk, giving the view a
physical dimension, as opposed to its normal virtual role.

14). What are the purpose of creating view?


Ans: View is used for the following purposes:
a) Security
b) Faster Response
c) Complex Query solve

MS SQL SERVER INDEX INTERVIEW


QUESTIONS AND ANSWERS FOR
EXPERIENCED AND FRESHER
6-7 minutes

This is the new set of MS SQL Server index related interview questions-answers, In every sql server
interview/.net interview you must face questions related to speed up query? or what is index? etc.
So set of questions will clear your doubt about index. This set is for both experienced as well as fresher ms sql
server users,

First you can see the SQL Server index video tutorial by Shivprasad Koirala
https://www.youtube.com/watch?v=rtmeNwn4mEg
Then go-through following questions-answers series

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.

Disadvantages of the Indexes?


Inserts and updates takes longer time with clustered index.
It takes some disk space to create Non-Clustered index

How many columns can we include in non-clustered index?


Max 16 columns can be combined to make a single composite index key, with a cap that the max size of the
combined values is 900 bytes.

Why Use an Index?


Use of SQL server indexes provide many facilities such as:
* Rapid access of information
* Efficient access of information
* Enforcement of uniqueness constraints

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 Performance is same for both.

What is the difference between a Clustered and Non-Clustered Index?


Clustered Index
1.There can be only one Clustered index for a table
2.Usually made on the primary key
3.The leaf nodes of a clustered index contain the data pages.
4. A clustered index actually describes the order in which records are physically stored on the disk, hence the
reason you can only have one.

Non-Clustered Index
1.There can be only 249/999(2005/2008) Non-Clustered index for a table
2.Usually made on the any key
3.The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index
rows
4.A Non-Clustered Index defines a logical order that does not match the physical order on disk.

Is Clustered index store the table data in sorted order?


Yes!
When you create an index on a column or number of columns in MS SQL Server, you can specify that the
index on each column be either ascending or descending.
Generally which index perform faster Clustered or Non-Clustered?
Generally it is faster to read from a clustered index if you want to get back all the columns. You do not have to
go first to the index and then to the table.
But not it’s not always true, have a look on the following article
http://www.mssqltips.com/sqlservertip/3041/when-sql-server-nonclustered-indexes-are-faster-than-clustered-
indexes/

What is Fill Factor and What is the Best Value for Fill Factor?
Fill factor is the value that determines the percentage of space on each leaf-level page to be filled with data. In
an SQL Server, the smallest unit is a page, which is made of Page with size 8K. Every page can store one or
more rows based on the size of the row. The default value of the Fill Factor is 100, which is same as value 0.
The default Fill Factor (100 or 0) will allow the SQL Server to fill the leaf-level pages of an index with the
maximum numbers of the rows it can fit. There will be no or very little empty space left in the page, when the
fill factor is 100.
Ref. http://blog.sqlauthority.com/2011/01/31/sql-server-what-is-fill-factor-and-what-is-the-best-value-for-fill-
factor/

TCS 10 Tricky SQL Server Interview


Questions/Query Asked during TCS Interview
3-4 minutes

TCS SQL SERVER INTERVIEW QUESTIONS ANSWERS 2016 SET

Today I want to share my interview experience with you, TCS was looking for 4+ years SQL Server
Experienced Developers, So I attend this interview(05/05/2016) to know the latest SQL Server question asked
in marked currently.
Below are the set of query which are asked during my TCS interview question answers session(tech round),
Which was held in Gurgaon TCS office. So be updated with new set of query, last query is most interesting.
Some of them asked during HCL interview as well I had attended HCL interview as well. Most of them are
very tricky queries. Must share with your friends.

1). How to select random record form a table?


Ans: Select top 1 * from <TableName> order by newId()

2). Suppose that you have table Employee with a column EName which contain Records Employee
name(EName) as A,B,A,A,B,D,C,M,A, Write a query which will change/Swap the EName A to B and B
to A.
Ans: UPDATE Employee

set EName = (CASE

WHEN EName='A' THEN 'B'

WHEN EName='B' THEN 'A'

ELSE EName

END)
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

6). Write a query to calculate number of A in string 'VIKASAAA'?


Ans: SELECT LEN('VIKASAAA') - LEN(REPLACE('VIKASAAA', 'A', ''))

7). What would be the output of below query?


SELECT * FROM ( SELECT 1 UNION ALL SELECT 2 ) M
Ans: It will throw error because in sub query no column name specified

8). What would be the output of below query?


Ans: SELECT SUM(A) AS [Sum] FROM ( SELECT 1 A UNION ALL SELECT NULL A) M
9). For 5/2, I want result 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

HCL 23 SQL Server DBA Interview Question : Real


Time Interview Questions
3 minutes

Hey DBA this time we come with SQL Server Interview Questions asked during HCL SQL Server DBA
interview. Me and my friends collecting latest interview questions by attending Interview in famous companies,
I am collecting questions from my friends and some time I attend interview to collect questions.
Before that I have posted TCS SQL Server Interview questions, After posting that set we are getting lots of
email to post questions related to different MNC. So this time we come with HCL Real Interview questions

HCL SQL SERVER DBA INTERVIEW QUESTIONS


(interview attended 3rd Feb 2017)

1). What is @@ERROR? (click on the questions to see answer)

2). What is a linked server?

3). Will Non-Clustered Index used every time by SQL Server Engine? (HCL/Unitedhealth Group)

4). What are different part of a SQL Page?

5). What are the types of database recovery models?

6). What are different types of Collation Sensitivity?

7). What are the disadvantages of using Stored Procedure?

8). Can we call Stored Procedure in a View?

9). What is FILL Factor?

10). How Fixed Length and Variable Length Data types affect performance in Sql server Explain with
example?

11). What would be the output of the following script?


SELECT NULL + 5

12). What do you understand by index_id = 0 and Index_id = 1, related to sys.indexes table? What they
represent?

13). Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible?

14).What would be the output of following query?


15). What is forwarding pointer in SQL Server? How it is helpful in performance optimization?

16). What would be the output of the following script?


SELECT COUNT(*)

17). How do you optimize Stored Procedures?

18). What would be the output of the following script?

DECLARE @Name VARCHAR(20)

SET @Name = 'विकास अहलाित'

SELECT @Name

19). What would be the output of following SQL Script.

20). What would be the output of the following query?

21). What Execute in SQL Server First?


A) WHERE
B) SELECT
C) ON
D) FROM
E) TOP

22). Sql server difference between session and connection?

23). Suppose you have following table"TestUpdate".


SELECT * FROM Testupdate

What would be the output of following query?


UPDATE Testupdate SET ID = ID + (SELECT MAX(ID) FROM Testupdate)
SELECT * FROM Testupdate

24). Repeat Rows N Times According to Column Value in SQL Server?


Top 18 SQL Stored Procedure Interview Questions
Answers
6-8 minutes

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

8). What are the advantages of using a Stored Procedures?


Ans: Following are the main advantage of using a SP

 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

 Writing and maintaining stored procedures requires more specialized skills.


 There are no debuggers available for stored procedures
 Stored procedure language may differ from one database system to another.
 Poor exception handling
 Tightly coupled to the database system
 Not possible to use objects
 Sometimes it is hard to understand the logic written in dynamic SQL

10). How do we recompile a stored procedure at run time?


Ans: Add the WITH RECOMPILE hint when creating or executing the stored procedure

11). How to Optimize Stored Procedure Optimization?


Ans: There are many tips and tricks for the same. Here are few:

 Include SET NOCOUNT ON statement.


 Use schema name with object name.
 Do not use the prefix "sp_" in the stored procedure name.
 Use IF EXISTS (SELECT 1) instead of (SELECT *).
 Use the sp_executesql stored procedure instead of the EXECUTE statement.
 Try to avoid using SQL Server cursors whenever possible.
 Keep the Transaction as short as possible.
 Use TRY-Catch for error handling.

12). How you will execute the stored procedure as a different user?
Ans: I will use EXECUTE AS
Example-

EXECUTE AS user = 'special_user'

EXECUTE YourProcerdure
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.

15). Explain the differences between Stored Procedures and triggers?


Ans: 1. When you create a trigger you have to identify event and action of your trigger but when you create s.p
you don't identify event and action
2.Trigger is run automatically if the event is occurred but s.p don't run automatically but you have to run it
manually
3. Within a trigger you can call specific s.p but within a sp you cannot call a trigger
4.Trigger execute implicitly whereas store procedure execute via procedure call from another block.
5.We can call a stored procedure from front end (.asp files, .aspx files, .ascx files etc.) but we can't call a trigger
from these files.
6. Stored procedure can take the input parameters, but we can't pass the parameters as an input to a trigger.

16). When would you use stored procedure or functions ?


Ans: Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e.
no INSERT or UPDATE statements allowed).
A Function can be used inline in SQL Statements if it returns a scalar value or can be joined upon if it returns a
result set.
for more see the diffrence between them, and use according to that.

17). Why use functions instead of stored procedure in SQL?


Ans: If you want perform some calculation base on some column value, then you can use function instead of
stored proc because you can not call a procedure in a select statement but you can call function in a select
statement.

18). Can we use try and catch in stored procedure and function both? give and example?
Ans: We can use try and catch block in stored procedure, but not in user defined function(UDF)
Example(try catch in SP)

CREATE PROCEDURE USP_TryCatch_Test


AS

BEGIN TRY

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: Yes, We can

21). Can we return NULL value using stored proc?


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.

Best of luck, please share interview question if you have any.

You might also like