Index Algorithim
Index Algorithim
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. :)
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.
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:
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
ANS:
MS SQL Server: SELECT * 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
8. Get all employee details from EmployeeDetail table whose "FirstName" contains 'k'
ANS:
MS SQL Server: 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'
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]%'
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.
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 '%'
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]
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***
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'
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.
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'
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
(SELECT TOP 2 Salary FROM [EmployeeDetail] ORDER BY Salary DESC) T ORDER BY Salary ASC
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]
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]
47. Get
department wise maximum salary from "EmployeeDetail" table order by salary ascending
Ans: SELECT Department, MAX(Salary) AS [Average Salary] FROM [EmployeeDetail]
48. Get department wise minimum salary from "EmployeeDetail" table order by salary ascending
Ans: SELECT Department, MIN(Salary) AS [Average Salary] FROM [EmployeeDetail]
--
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
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:
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
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)
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
SELECT T1.ID, T2.ID FROM TBL_1 T1 LEFT OUTER JOIN TBL_2 T2 ON T1.ID = T2.ID
--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
--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
--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)
--ANS:
--68. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--69. What would be the output of the following query.(Related Tables : Table_1,Table_2)
--ANS:
--70. What would be the output of the following query.(Related Tables : Table_1,Table_2)
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)
ON NOT(A.ID = B.ID)
--ANS:
--72. What would be the output of the following query.(Related Tables : Table_1,Table_2)
ON A.ID IN(1)
--ANS:
--73. What would be the output of the following query.(Related Tables : Table_1,Table_2)
ON NOT(A.ID = B.ID)
--ANS:
--74. 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 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
--76. 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 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
This set contains most frequently asked ddl related interview queries, It contains query related to Identity
column, Primary key and foreign key.
--78. Write down the query to create employee table with Identity column([EmployeeID])
--ANS:
--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)
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.
83). SELECT 15
B). 15
C). 0
D). 1
84). SELECT $
B). $
C). 1
D). 0.00
B). 0
C). 1
D). *
B). 7
C). 0
D). 1
B). 'VIKAS'
C). VIKAS
D). VIKAS1
B). 'VIKAS'
C). VIKAS
D). VIKAS1
B). 'VIKAS'
C). VIKAS
D). VIKAS1
B). 'VIKAS'
C). VIKAS
D). VIKAS1
C). Country
B). 0
C). 1
D). 2
95).SELECT SUM(1+2*3)
B). 9
C). 7
D). 6
B). 3
C). 7
D). 6
97).SELECT MAX(1,3,4)
A).Throw error
B). 1
C). 3
D). 4
98).SELECT MAX('VIKAS')
A).Throw error
B). 1
C). 2
D). VIKAS
A).Throw error
C). 0
B). 1
C). 2
D). 11
B). 1
C). 2
D). 11
B). NULL
C). 5
D). 0
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). NOTHING WILL RETURN BY This (0 rows will be returned by this) because the condition is false
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). 0
B). NULL
C). 1
D). 0
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
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
ANS:
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.
--This means that he/she fill the petrol at 25th April 2014 at 2PM
ANS:
Solution 1:
FROM FuelDetail c
JOIN
WHERE c1.fuel>c.fuel
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
Options:
Options:
106). What would be the out-put of the following Sql query?
Options:
Options:
Options:
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 are the two types of character data SQL Server supports?
What can you define with variable length character data types?
Ans: VARCHAR(MAX)
Ans: 1.) DATETIME 2.) SMALLDATETIME 3.) DATE 4.) TIME 5.) DATETIME2 6.) DATETIMEOFFSET
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?
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:
OR
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
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())
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?
Ans: it will add 2 days in current date time and according to date specified it will display 29th Aug 2015 with
current time.
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.
Ans: No
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.
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).
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)
-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.
-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).
Ans: No
What is the only data type avaliable in SQL Server which can store GPS data that has been defined by
the OGC()?
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)
SELECT @Name
SELECT @Name
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
SELECT @Name
Indexed Views
Partitioned Views
System Views
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.
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.
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
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))
createview vw_onTempTable
as
select MobileName,CompanyNamefrom ##MobileDetails
go
An error prompted by the SQL Server after running the preceding command.
3. You can't use an order by clause at the time of view creation. Kindly have a look at an example below:
CreateView vw_OrdersNorthwind
As
select OrderID,CustomerID,ShipCity,ShipCountryfrom orders orderby OrderID desc
go
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.
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
CreateView vw_OrdersNorthwind
As
--select OrderID,CustomerID,ShipCity,ShipCountry from orders
select count(*) As Total from orders
go
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
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.
12). Will below script correct or not? If not what is wrong with it?
WITH SCHEMABINDING
AS
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:
WITH SCHEMABINDING
AS
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.
Types of Indexes?
SQL Server has two major types of indexes:
Clustered
Non-Clustered
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.
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/
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.
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
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
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
Using Loop:
DECLARE @i INT
SET @i = 0
BEGIN
SELECT @i = @i + 1
PRINT @i
END
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?
Ans: Output of the above query would be as below; Inner join will join both blank values
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
3). Will Non-Clustered Index used every time by SQL Server Engine? (HCL/Unitedhealth Group)
10). How Fixed Length and Variable Length Data types affect performance in Sql server Explain with
example?
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?
SELECT @Name
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.
AS
IF @Number != 1
BEGIN
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.
12). How you will execute the stored procedure as a different user?
Ans: I will use EXECUTE AS
Example-
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.
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.
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)
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
,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?