Blog

Sql Server Interview Questions for 2-3 Years Experience [UPDATED 2018]

  • (4.0)
  •   |   29996 Ratings

If you're looking for SQL Server Interview Questions for Experienced or Freshers, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research, The average salary for  SQL Server ranges from approximately $69,682 pa. So, You still have opportunity to move ahead in your career in SQL Server. Mindmajix offers Advanced SQL Server Interview Questions 2018 that helps you in cracking your interview & acquire dream career as SQL Server Developer.

Learn how to use SQL Server, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free SQL Server Training Demo!

SQL Server Interview Questions

In what sequence SQL statement are processed?

The clauses of the select are processed in the following sequence

  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause
  7. TOP clause

Can we write a distributed query and get some data which is located on other server and on Oracle Database ?

SQL Server can be lined to any server provided it has OLE-DB provider from Microsoft to allow a link.

E.g. Oracle has a OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group.

If we drop a table, does it also drop related objects like constraints, indexes, columns, defaults, Views and Stored Procedures ?

YES, SQL Server drops all related objects, which exists inside a table like, constraints, indexes, columns, defaults etc. BUT dropping a table will not drop Views and Stored Procedures as they exists outside the table.

How would you determine the time zone under which a database was operating?

Can we add identity column to decimal datatype?

YES
, SQL Server support this

What is the Difference between LEFT JOIN with WHERE clause & LEFT JOIN with no WHERE clause ?

OUTER LEFT/RIGHT JOIN with WHERE clause can act like an INNER JOIN if not used wisely or logically.

What are the Multiple ways to execute a dynamic query ?

EXEC sp_executesql, EXECUTE()


What is the Difference between COALESCE() & ISNULL() ?

ISNULL accepts only 2 parameters. The first parameter is checked for NULL value, if it is NULL then the second parameter is returned, otherwise it returns first parameter.

COALESCE accepts two or more parameters. One can apply 2 or as many parameters, but it returns only the first non NULL parameter,

How do you generate file output from SQL?

While using SQL Server Management Studio or Query Analyzer, we have an option in Menu BAR.QUERTY >> RESULT TO >> Result to FILE

How do you prevent SQL Server from giving you informational messages during and after a SQL statement execution?

SET NOCOUNT OFF

By Mistake, Duplicate records exists in a table, how can we delete copy of a record ?

;with T as
(
    select * , row_number() over (partition by Emp_ID order by Emp_ID) as rank
    from employee
)

delete
from T
where rank > 1

WHAT OPERATOR PERFORMS PATTERN MATCHING?

Pattern matching operator is LIKE and it has to used with two attributes

1. %  means matches zero or more characters and 

2. _ ( underscore ) means matching exactly one character

What’s the logical difference, if any, between the following SQL expressions?

-- Statement 1 
SELECT COUNT ( * ) FROM Employees

-- Statement 2
SELECT SUM ( 1 ) FROM Employees

They’re the same unless table Employee table is empty, in which case the first yields a one-column, one-row table containing a zero and the second yields a one-column, one-row table "containing a null."

SQL Server Interview Questions And Answers

Is it possible to update Views? If yes, How, If Not, Why?

Yes, We can modify views but a DML statement on a join view can modify only one base table of the view (so even if the view is created upon a join of many tables, only one table, the key preserved table can be modified through the view).

Could you please name different kinds of Joins available in SQL Server ?

  • OUTER JOIN – LEFT, RIGHT, CROSS, FULL ;
  • INNER JOIN

How important do you consider cursors or while loops for a transactional database?

would like to avoid cursor in OLTP database as much as possible, Cursors are mainly only used for maintenance or warehouse operations.

What is a correlated sub query?

When a sub query is tied to the outer query. Mostly used in self joins.

What is faster, a correlated sub query or an inner join?

Correlated sub query.

You are supposed to work on SQL optimization and given a choice which one runs faster, a correlated sub query or an exists?

Exists

Can we call .DLL from SQL server?

YES, We can call .Dll from SQL Server. 

What are the pros and cons of putting a scalar function in a queries select list or in the where clause?

Should be avoided if possible as Scalar functions in these places make the query slow down dramatically.

What is the difference between truncate and drop statement?

What is the difference between truncate and delete statement?

What are user defined data types and when you should go for them?

User-defined data types let you extend the base SQL Server data types by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined data type calledFlight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

Can You Explain Integration Between SQL Server 2005 And Visual Studio 2005 ?

This integration provide wider range of development with the help of CLR for database server because CLR helps developers to get flexibility for developing database applications and also provides language interoperability just like Visual C++, Visual Basic .Net and Visual C# .Net.

The CLR helps developers to get the arrays, classes and exception handling available through programming languages such as Visual C++ or Visual C# which is use in stored procedures, functions and triggers for creating database application dynamically and also provide more efficient reuse of code and faster execution of complex tasks. We particularly liked the error-checking powers of the CLR environment, which reduces run-time errors

SQL Server Interview Questions And Answers For Experienced

You are being assigned to create a complex View and you have completed that task and that view is ready to be get pushed to production server now. you are supposed to fill a deployment form before any change is pushed to production server.

One of the Filed in that deployment form asked, “Expected Storage requirement”. What all factors you will consider to calculate storage requirement for that view ?

Very tricky, View, doesn’t takes space in Database, Views are virtual tables. Storage is required to store Index, incase you are developing a indexed view.

What is Index, cluster index and non cluster index ?

Clustered Index:- A Clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table may have only one clustered index.Non-Clustered Index:- A Non-Clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows in the disk. The leaf nodes of a non-clustered index does not consists of the data pages. instead the leaf node contains index rows.

Write down the general syntax for a SELECT statements covering all the options.

Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list

[INTO new_table_]

FROM table_source

[WHERE search_condition]

[GROUP BY group_by__expression]

[HAVING search_condition]

[ORDER BY order__expression [ASC | DESC] ]

What is a join and explain different types of joins?

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins:

INNER JOINs,

OUTER JOINs,

CROSS JOINs

OUTER JOINs are further classified as

LEFT OUTER JOINS,

RIGHT OUTER JOINS and

FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

What is OSQL utility ?

OSQL is command line tool which is used execute query and display the result same a query analyzer but everything is in command prompt.

What Is Difference Between OSQL And Query Analyzer ?

OSQL is command line tool which executes query and display the result same a query analyzer but query analyzer is graphical and OSQL is a command line tool. OSQL is quite useful for batch processing or executing remote queries.

What Is Cascade delete / update  ?

CASCADE allows deletions or updates of key values to cascade through the tables defined to have foreign key relationships that can be traced back to the table on which the modification is performed.

SQL Server Interview Questions For 2-5 Years Experienced

What are some of the join algorithms used when SQL Server joins tables.

  1. Loop Join (indexed keys unordered)
  2. Merge Join (indexed keys ordered)
  3. Hash Join (non-indexed keys)

 

What is maximum number of tables that can joins in a single query ?

256, check SQL Server Limits

What is Magic Tables in SQL Server ?

The MAGIC tables are automatically created and dropped, in case you use TRIGGERS. SQL Server has two magic tables named, INSERTED and DELETED

These are mantained by SQL server for there Internal processing. When we use update insert or delete on tables these magic tables are used.These are not physical tables but are Internal tables.When ever we use insert statement is fired the Inserted table is populated with newly inserted Row and when ever delete statement is fired the Deleted table is populated with the delete

d row.But in case of update statement is fired both Inserted and Deleted table used for records the Original row before updation get store in Deleted table and new row Updated get store in Inserted table.

Can we disable a triger?, if yes HOW ?

YES, we can disable a single trigger on the database by using  “DISABLE TRIGGER triggerName ON <>”

we also have an option to disable all the trigger by using, “DISABLE Trigger ALL ON ALL SERVER”

Why you need indexing? where that is Stored and what you mean by schema object? For what purpose we are using view?

We can’t create an Index on Index.. Index is stoed in user_index table. Every object that has been created on Schema is Schema Object like Table, View etc. If we want to share the particular data to various users we have to use the virtual table for the Base table. So that is a view.

Indexing is used for faster search or to retrieve data faster from various table. Schema containing set of tables, basically schema means logical separation of the database. View is crated for faster retrieval of data. It’s customized virtual table. we can create a single view of multiple tables. Only the drawback is..view needs to be get refreshed for retrieving updated data.

What the difference between UNION and UNIONALL?

Union will remove the duplicate rows from the result set while Union all does’nt.

Which system table contains information on constraints on all the tables created ?

USER_CONSTRAINTS,

system table contains information on constraints on all the tables created

SQL Server Joins Interview Questions

Frequently Asked SQL Server Interview Questions & Answers

What are different Types of Join?

  1. Cross Join A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price.
  2. Inner Join A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer.
  3. Outer Join A join that includes rows even if they do not have related rows in the joined table is an Outer Join. You can create three different outer join to specify the unmatched rows to be included:
    1. Left Outer Join: In Left Outer Join all rows in the first-named table i.e. "left" table, which appears leftmost in the JOIN clause are included. Unmatched rows in the right table do not appear.
    2. Right Outer Join: In Right Outer Join all rows in the second-named table i.e. "right" table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included.
    3. Full Outer Join: In Full Outer Join all rows in all joined tables are included, whether they are matched or not.
  4. Self Join This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join can be Outer Join or Inner Join.

What is Data-Warehousing?

  1. Subject-oriented, meaning that the data in the database is organized so that all the data elements relating to the same real-world event or object are linked together;
  2. Time-variant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time;
  3. Non-volatile, meaning that data in the database is never over-written or deleted, once committed, the data is static, read-only, but retained for future reporting.
  4. Integrated, meaning that the database contains data from most or all of an organization’s operational applications, and that this data is made consistent.

What is a live lock?

A live lock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A live lock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

How SQL Server executes a statement with nested subqueries?

When SQL Server executes a statement with nested subqueries, it always executes the innermost query first. This query passes its results to the next query and so on until it reaches the outermost query. It is the outermost query that returns a result set.

How do you add a column to an existing table?

ALTER TABLE Department ADD (AGE, NUMBER);

Can one drop a column from a table?

YES, to delete a column in a table, use  ALTER TABLE table_name DROP COLUMN column_name

Which statement do you use to eliminate padded spaces between the month and day values in a function TO_CHAR(SYSDATE,’Month, DD, YYYY’) ?

To remove padded spaces, you use the "fm" prefix before the date element that contains the spaces. TO_CHAR(SYSDATE,’fmMonth DD, YYYY’)

Which operator do you use to return all of the rows from one query except rows are returned in a second query?

You use the EXCEPT operator to return all rows from one query except where duplicate rows are found in a second query. The UNION operator returns all rows from both queries minus duplicates. The UNION ALL operator returns all rows from both queries including duplicates. The INTERSECT operator returns only those rows that exist in both queries. 

How will you create a column alias?

The AS keyword is optional when specifying a column alias.

In what sequence SQL statement are processed?

The clauses of the subselect are processed in the following sequence (DB2): 1. FROM clause 2. WHERE clause 3. GROUP BY clause 4. HAVING clause 5. SELECT clause 6. ORDER BY clause 7. FETCH FIRST clause

How can we determine what objects a user-defined function depends upon?

sp_depends system stored procedure or query the sysdepends system table to return a list of objects that a user-defined function depends upon

SELECT DISTINCT so1.name, so2.name FROM sysobjects so1
INNER JOIN sysdepends sd
ON so1.id = sd.id
INNER JOIN sysobjects so2
ON so2.id = sd.depid
WHERE so1.name = '<>'

What is lock escalation ?

A query first takes the lowest level lock possible with the smallest footprint (row-level). When too many rows are locked (requiring too much RAM) the lock is escalated to a range or page lock. If too many pages  are locked, it may escalate to a table lock.

What are the main differences between #temp tables and @table variables and which one is preferred ?

  1. SQL Server can create column statistics on #temp tables
  2. Indexes can be created on #temp tables
  3. @table variables are stored in memory up to a certain threshold.

What are Checkpoint In SQL Server ?

When we done operation on SQL SERVER that is not commited directly to the database.All operation must be logged in to Transaction Log files after that they should be done on to the main database.CheckPoint are the point which alert Sql Server to save all the data to main database if no check point is there then log files get full we can use Checkpoint command to commit all data in the SQL SERVER.When we stop the SQL Server it will take long time because Checkpoint is also fired.

Related Page: SQL Interview Questions For 5+ Years Experienced 

Why we use OPENXML clause?

OPENXML parses the XML data in SQL Server in an efficient manner. It’s primary ability is to insert XML data to the DB.

Can we store we store PDF files inside SQL Server table ?

YES, we can store this sort of data using a blob datatype.

Can we store Videos inside SQL Server table ?

YES, we can store Videos inside SQL Server by using FILESTREAM datatype, which was introduced in SQL Server 2008.

Can we hide the definition of a stored procedure from a user ?

YES, while creating stored procedure we can use WITH ENCRYPTION which will convert the original text of the CREATE PROCEDURE statement to an encrypted format.

What are included columns when we talk about SQL Server indexing?

Indexed with included columns were developed in SQL Server 2005 that assists in covering queries. Indexes with Included Columns are non clustered indexes that

have the following benefits:

  • Columns defined in the include statement, called non-key columns, are not counted in the

    number of columns by the Database Engine.
  • Columns that previously could not be used in queries, like nvarchar(max), can be included

    as a non-key column.
  • A maximum of 1023 additional columns can be used as non-key columns.

What is an execution planHow would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since  the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query  drop-down menu). If this option is turned on it will display query execution plan in separate window  when query is ran again.

Explain UNION, MINUS, UNION ALL, INTERSECT ?

INTERSECT returns all distinct rows selected by both queries.

MINUS – returns all distinct rows selected by the first query but not by the second.

UNION – returns all distinct rows selected by either query

UNION  ALL  -  returns  all  rows  selected  by  either query, including all duplicates

Explore SQL Server Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

SQL SERVER Query Interview Questions with Answers

SQL Server DATEADD() Function

Q) Write a Query to display the date after 15 days?

SELECT DATEADD(dd, 15,getdate())

Q) Write a Query to display date after 12 months?

SELECT DATEADD(mm, 2, getdate())

Q) Write a Query to display date before 15 days?

SELECT DATEADD(dd, -15, getdate())

SQL Server DATEDIFF() Function

Q) Write a Query to display employee details along with exp?

SELECT *
DATEDIFF(yy, doj, getdate()) AS ‘Exp’ FROM employee

Q) Write a Query to display employee details who is working in ECE department & who his having more than 3 years of exp?

SELECT *
DATEDIFF(yy, doj, getdate()) AS ‘Exp’ 
FROM employee 
WHERE DATEDIFF(yy, doj, getdate())>3 AND dept_name=’ECE’

Q) Write a Query to display employee details along with age?

SELECT *
DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee

Q) Write a Query to display employee details whose age >18?

SELECT *
DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee
WHERE DATEDIFF(yy, dob, getdate())>18

SQL Server Multi Row Functions

Q) Write a Query to display minimum salary of an employee?

SELECT MIN (salary)
FROM employee

Q) Write a Query to display maximum salary of an employee?

SELECT MAX(salary)
FROM employee

Q) Write a Query to display total salary of all employees?

SELECT SUM(salary) FROM employee

Q) Write a Query to display average salary of an employee?

SELECT AVG(salary) FROM employee

Q) Write a Query to count the number of employees working in the company?

SELECT COUNT(*) FROM employee

Q) Write a Query to display minimum & maximum salary of employee?

SELECT MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’ FROM employee

Q) Write a Query to count the number of employee working in ECE department?

SELECT COUNT(*) FROM employee WHERE dept_name=’ECE’

Q) Write a Query to display second max salary of an employee?

SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM emp)

Q) Write a Query to display third max salary of an employe?

SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM emp where salary < (SELECT MAX(salary) FROM emp))

SQL SERVER: GROUP BY Clause

Q) Write a Query to display total salary of employee based on city?

SELECT city, SUM(salary) 
FROM employee 
GROUP BY city;

Q) Write a Query to display number of employee based on city?

SELECT city, COUNT(emp_no) 
FROM employee
GROUP BY city;

(OR)

SELECT city, COUNT(emp_no) AS ‘no.of employees’ 
FROM employee 
GROUP BY city;

Q) Write a Query to display total salary of employee based on region?

SELECT region, SUM(salary) AS ‘total_salary’ 
FROM employee
GROUP BY region;

Q) Write a Query to display the number of employees working in each region?

SELECT region, COUNT(gender) 
FROM employee
GROUP BY region;

(OR) 

SELECT region, COUNT(gender) AS ‘no.of males’
FROM employee
GROUP BY region;


Q) Write a Query to display minimum salary & maximum salary based on dept_name?

SELECT dept_name, MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’ 
FROM employee
GROUP BY dept_name

Q) Write a Query to display the total salary of employee based on dept_name?

SELECT dept_name, SUM(salary) AS ‘total_sal’ 
FROM employee
GROUP BY dept_name

Q) Write a Query to display no.of males in each department?

SELECT dept_name, COUNT(gender) 
FROM employee
GROUP BY dept_name 
WHERE gender=’male’

(OR)

SELECT dept_name, COUNT(gender) AS ‘no.of males’ 
FROM employee
WHERE gender=’male’ 
GROUP BY dept_name;

Note:: We cannot apply where condition in GROUP BY CLAUSE if we want apply use having clause.
We have to use WHERE condition before GROUP BY but cannot apply where condition after GROUP BY.

SQL SERVER: Having Clause

Q) Write a Query to display total salary of employee based on whose total salary > 12000?

SELECT city, SUM(salary) AS ‘total_salary’ 
FROM employee
GROUP BY city
HAVING SUM(salary)>12000;

Q) Write a Query to display the total salary of all employees based on city whose average salary >= 23000?

SELECT city, SUM(salary) AS ‘total_salary’ 
FROM employee
GROUP BY city
HAVING AVG(salary)  >= 23000;

SQL SERVER: SUB QUERIES

Q) Write a Query to display employee details whose employee numbers are 101, 102?

SELECT *
FROM employee
WHERE Emp_No in (101, 102)

(OR)

SELECT * FROM employee
WHERE Emp_No in (select emp_no from emp)

Q) Write a Query to display employee details belongs to ECE department?

SELECT Emp_No, Emp_Name, Salary
FROM employee
WHERE dept_no in (select dept_no from dept where dept_name = ‘ECE’)

SQL SERVER TOP Clause

Q) Write a Query to display first record from the table?

SELECT TOP 1 * 
FROM employee

Q) Write a Query to display top 3 records from the table?

SELECT TOP 3 *
FROM employee

Q) Write a Query to display last record from the table?

SELECT TOP 1 *
FROM employee 
ORDER BY emp_no descending

SQL SERVER: Ranking Functions

Student Details Table:

Student_No Student_Name Percentage Row_ID Rank_ID DenseRank_ID
105 James 87 1 1 1
106 John 83 2 2 2
101 Anil 83 3 2 2
104 Vijay 83 4 2 2
108 Rakesh 76 5 5 3
102 Sunil 76 6 5 3
103 Ajay 76 7 5 3
107 Ram 75 8 8 4

Q) Write a Query to display student details along with the row_no order by student name?

SELECT *, ROW_NUMBER() OVER (ORDER BYstudent_name) AS ‘Row_ID’
FROM employee

Q) Write a Query to display even records from the table?

SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY student_no) AS ‘ Row_ID’ FROM student)
WHERE row_id %2=0

Q) Write a Query to display odd records from student table?

SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY student_no) AS Row_ID FROM student)
WHERE row_id %2!=0

List of Related Microsoft Certification Courses:

 SSIS  Power BI
 SSRS  SharePoint
 SSAS  SQL Server DBA
 SCCM  BizTalk Server
 Team Foundation Server  BizTalk Server Administrator

 


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules