If you're looking for SQL Server Interview Questions for Experienced or Freshers, you are in the right place. There are many opportunities from reputable companies around the world. According to research, the average salary for SQL Server ranges from approximately $69,682 per annum. So, you still have the opportunity to advance your career in SQL Server.
MindMajix offers Advanced SQL Server Interview Questions for 2-3 Years of Experience to help you crack your interview & acquire a dream career as an SQL Server Developer.
We have categorized SQL Server Interview Questions - 2024 (Updated) into 4 levels they are:
| If you want to enrich your career and become a professional in SQL, enroll in "SQL Server Training." This course will help you achieve excellence in this domain. |
CREATE TABLE Employees (
EmpID INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
DeptID INT FOREIGN KEY REFERENCES Departments(DeptID),
Salary DECIMAL(10,2) CHECK (Salary > 0),
IsActive BIT DEFAULT 1,
HireDate DATE DEFAULT GETDATE()
);
SELECT
fk.name AS ForeignKeyName,
tp.name AS ParentTable,
tr.name AS ReferencedTable
FROM sys.foreign_keys fk
JOIN sys.tables tp ON fk.parent_object_id = tp.object_id
JOIN sys.tables tr ON fk.referenced_object_id = tr.object_id;
SELECT
mid.statement AS TableName,
migs.avg_user_impact,
mid.equality_columns,
mid.inequality_columns,
mid.included_columns
FROM sys.dm_db_missing_index_details mid
JOIN sys.dm_db_missing_index_groups mig ON mid.index_handle = mig.index_handle
JOIN sys.dm_db_missing_index_group_stats migs ON mig.index_group_handle =
migs.group_handle
ORDER BY migs.avg_user_impact DESC;
CREATE PROCEDURE TransferFunds
@FromID INT, @ToID INT, @Amount DECIMAL(10,2)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - @Amount WHERE AccountID = @FromID;
UPDATE Accounts SET Balance = Balance + @Amount WHERE AccountID = @ToID;
IF (SELECT Balance FROM Accounts WHERE AccountID = @FromID) < 0
THROW 50001, 'Insufficient funds', 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
THROW;
END CATCH
END;
SELECT EmpID, [1] AS Jan, [2] AS Feb, [3] AS Mar
FROM (
SELECT EmpID, MONTH(OrderDate) AS OrderMonth, Amount
FROM Orders
WHERE MONTH(OrderDate) IN (1,2,3)
) src
PIVOT (
SUM(Amount) FOR OrderMonth IN ([1],[2],[3])
) AS pvt;
WITH Seq AS (
SELECT OrderID, LEAD(OrderID) OVER (ORDER BY OrderID) AS NextID
FROM Orders
)
SELECT OrderID + 1 AS GapStart, NextID - 1 AS GapEnd
FROM Seq
WHERE NextID - OrderID > 1;
SELECT e.Name AS Employee, m.Name AS Manager,
CASE WHEN e.Salary > m.Salary THEN 'Yes' ELSE 'No' END AS
EarnsMoreThanManager
FROM Employees e
JOIN Employees m ON e.ManagerID = m.EmpID;
SELECT Name, DeptID, Salary
FROM (
SELECT Name, DeptID, Salary,
AVG(Salary) OVER (PARTITION BY DeptID) AS DeptAvg,
STDEV(Salary) OVER (PARTITION BY DeptID) AS DeptStdDev
FROM Employees
) t
WHERE ABS(Salary - DeptAvg) > 2 * DeptStdDev;
SELECT OrderMonth, Revenue,
AVG(Revenue) OVER (ORDER BY OrderMonth ROWS BETWEEN 2 PRECEDING AND CURRENT
ROW) AS MovingAvg3
FROM (
SELECT FORMAT(OrderDate, 'yyyy-MM') AS OrderMonth, SUM(Amount) AS Revenue
FROM Orders GROUP BY FORMAT(OrderDate, 'yyyy-MM')
) t;
SELECT Name, DeptID, Salary,
MAX(Salary) OVER (PARTITION BY DeptID) - Salary AS DiffFromTop
FROM Employees;
WITH Ranked AS (
SELECT CustomerID, Amount,
ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) AS
rn,
AVG(Amount) OVER (PARTITION BY CustomerID) AS AvgAmount
FROM Orders
)
SELECT CustomerID, Amount AS LastOrderAmount, AvgAmount
FROM Ranked
WHERE rn = 1 AND Amount > AvgAmount;
SELECT Name, DeptID, Salary FROM (
SELECT Name, DeptID, Salary,
DENSE_RANK() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS rnk
FROM Employees
) t
WHERE rnk = 2;
SELECT TOP 3 c.Name, SUM(o.Amount) AS TotalSpent
FROM Customers c
JOIN Orders o ON c.CustomerID = o.CustomerID
GROUP BY c.Name
ORDER BY TotalSpent DESC;
SELECT TOP 1 p.ProductName, SUM(od.Quantity) AS TotalSold
FROM Products p
JOIN OrderDetails od ON p.ProductID = od.ProductID
GROUP BY p.ProductName
ORDER BY TotalSold DESC;
SELECT TOP 1 MONTH(OrderDate) AS OrderMonth, SUM(Amount) AS Revenue
FROM Orders
GROUP BY MONTH(OrderDate)
ORDER BY Revenue DESC;
SELECT CustomerID, AVG(Amount) AS AvgOrderValue, COUNT(*) AS OrderCount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) > 7;
SELECT p.ProductName, p.Price, p.CategoryID
FROM Products p
WHERE p.Price > (
SELECT AVG(p2.Price) FROM Products p2 WHERE p2.CategoryID = p.CategoryID
);
SELECT e1.Name AS Emp1, e2.Name AS Emp2, e1.ManagerID
FROM Employees e1
JOIN Employees e2 ON e1.ManagerID = e2.ManagerID AND e1.EmpID < e2.EmpID
WHERE e1.ManagerID IS NOT NULL;
SELECT Salary FROM (
SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rnk
FROM Employees
) t
WHERE rnk = @N;
SELECT Name, DeptID, COUNT(*) AS Occurrences
FROM Employees
GROUP BY Name, DeptID
HAVING COUNT(*) > 1;
SELECT d.DeptName
FROM Departments d
WHERE NOT EXISTS (
SELECT 1 FROM Employees e WHERE e.DeptID = d.DeptID
);
SQL Server can be linked to any server provided it has an OLE-DB provider from Microsoft to allow a link.
For E.g. Oracle has an OLE-DB provider for Oracle that Microsoft provides to add it as a linked server to the SQL Server group.
YES, SQL Server drops all related objects, which exist inside a table like constraints, indexes, columns, defaults, etc. BUT dropping a table will not drop Views and Stored Procedures as they exist outside the table.
How would you determine the time zone under which a database was operating?
YES, SQL Server support this
OUTER LEFT/RIGHT JOIN with WHERE clause can act like an INNER JOIN if not used wisely or logically.
ISNULL accepts only 2 parameters. The first parameter is checked for a NULL value, if it is NULL then the second parameter is returned, otherwise, it returns the 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,
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
The pattern matching operator is LIKE, and it has to be used with two attributes
1. % means matches zero or more characters and
2. _ ( underscore ) means matching exactly one character
-- 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, a one-row table containing zero, and the second yields a one-column, one-row table "containing a null."
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).
would like to avoid cursor in the OLTP database as much as possible, Cursors are mainly only used for maintenance or warehouse operations.
When a subquery is tied to the outer query. Mostly used in self joins.
Correlated subquery.
Exists
YES, We can call. Dll from SQL Server.
Should be avoided if possible as Scalar functions in these places make the query slow down dramatically.
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 called Flight_num_type of varchar(8) and use it across all your tables.
See sp_addtype, sp_droptype in books online.
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-NonClustered 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 do not consist of the data pages. instead, the leaf node contains index rows.
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] ]
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".
OSQL is a command-line tool that is used to execute the query and display the result the same as a query analyzer but everything is in the command prompt.
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.
256, check SQL Server Limits
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 maintained by the SQL server for their 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. Whenever we use insert statement is fired the Inserted table is populated with newly inserted Row and whenever delete statement is fired the Deleted table is populated with the deleted row.
But in case of update statement is fired both Inserted and Deleted tables used for records the Original row before updating get stored in the Deleted table and the new row Updated gets store in Inserted table.
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 triggers by using, “DISABLE Trigger ALL ON ALL SERVER”
We can’t create an Index on an Index... The index is stored in the 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 the various tables. Schema containing a set of tables, basically schema means logical separation of the database. The view is crated for faster retrieval of data. It’s a 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.
Union will remove the duplicate rows from the result set while Union all doesn't.
USER_CONSTRAINTS,
system table contains information on constraints on all the tables created
Below are the different types of SQL Server Joins:
A livelock 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 livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
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.
ALTER TABLE Department ADD (AGE, NUMBER);
YES, to delete a column in a table, use ALTER TABLE table_name DROP COLUMN column_name
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.
The AS keyword is optional when specifying a column alias.
The clauses of the subselect are processed in the following sequence (DB2):
sp_depends system stored procedure or query the says depends on 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 = '<>'
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.
When we did the operation on SQL SERVER that is not committed directly to the database. All operations must be logged in to Transaction Log files after that they should be done on to the main database.CheckPoint is the point that alerts SQL Server to save all the data to the main database if no checkpoint is there then log files get full we can use the Checkpoint command to commit all data in the SQL SERVER. When we stop the SQL Server it will take a long time because Checkpoint is also fired.
| Read these latest SQL Interview Questions For 5+ Years Experienced that helps you grab high-paying jobs |
OPENXML parses the XML data in SQL Server in an efficient manner. Its primary ability is to insert XML data into the DB.
YES, we can store this sort of data using a blob datatype.
YES, we can store Videos inside SQL Server by using FILESTREAM data type, which was introduced in SQL Server 2008.
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.
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:
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 the query execution plan in a separate window when the query is run again.
| → Explore SQL Server Sample Resumes Download & Edit, Get Noticed by Top Employers! |
SQL Server DATEADD() Function
SELECT DATEADD(mm, 2, getdate())
SELECT DATEADD(dd, -15, getdate())
SQL Server DATEDIFF() Function
SELECT *
DATEDIFF(yy, doj, getdate()) AS ‘Exp’ FROM employee
SELECT *
DATEDIFF(yy, doj, getdate()) AS ‘Exp’
FROM employee
WHERE DATEDIFF(yy, doj, getdate())>3 AND dept_name=’ECE’
SELECT *
DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee
SELECT *
DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee
WHERE DATEDIFF(yy, dob, getdate())>18
SQL Server Multi-Row Functions
SELECT MIN (salary)
FROM employee
SELECT MAX(salary)
FROM employee
SELECT SUM(salary) FROM employee
SELECT AVG(salary) FROM employee
SELECT COUNT(*) FROM employee
SELECT MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’ FROM employee
SELECT COUNT(*) FROM employee WHERE dept_name=’ECE’
SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM emp)
SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM emp where salary < (SELECT MAX(salary) FROM emp))
SQL SERVER: GROUP BY Clause
SELECT city, SUM(salary)
FROM employee
GROUP BY 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;
SELECT region, SUM(salary) AS ‘total_salary’
FROM employee
GROUP BY region;
SELECT region, COUNT(gender)
FROM employee
GROUP BY region;
(OR)
SELECT region, COUNT(gender) AS ‘no.of males’
FROM employee
GROUP BY region;
SELECT dept_name, MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’
FROM employee
GROUP BY dept_name
SELECT dept_name, SUM(salary) AS ‘total_sal’
FROM employee
GROUP BY dept_name
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 to 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
SELECT city, SUM(salary) AS ‘total_salary’
FROM employee
GROUP BY city
HAVING SUM(salary)>12000;
SELECT city, SUM(salary) AS ‘total_salary’
FROM employee
GROUP BY city
HAVING AVG(salary) >= 23000;
SQL SERVER: SUB QUERIES
SELECT *
FROM employee
WHERE Emp_No in (101, 102)
(OR)
SELECT * FROM employee
WHERE Emp_No in (select emp_no from emp)
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
SELECT TOP 1 *
FROM employee
SELECT TOP 3 *
FROM employee
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 |
SELECT *, ROW_NUMBER() OVER (ORDER BYstudent_name) AS ‘Row_ID’
FROM employee
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY student_no) AS ‘ Row_ID’ FROM student)
WHERE row_id %2=0
| SSIS | Power BI |
| SSRS | SharePoint |
| SSAS | SQL Server DBA |
| SCCM | BizTalk Server |
| Team Foundation Server | BizTalk Server Administrator |

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
| Name | Dates | |
|---|---|---|
| SQL Server Training | Jul 25 to Aug 09 | View Details |
| SQL Server Training | Jul 28 to Aug 12 | View Details |
| SQL Server Training | Aug 01 to Aug 16 | View Details |
| SQL Server Training | Aug 04 to Aug 19 | View Details |

Arogyalokesh is a Technical Content Writer and manages content creation on various IT platforms at Mindmajix. He is dedicated to creating useful and engaging content on Salesforce, Blockchain, Docker, SQL Server, Tangle, Jira, and few other technologies. Get in touch with him on LinkedIn and Twitter.