Google News
logo
SQL Server Interview Questions
SQL Server is the RDBMS system provided by Microsoft which functions mainly as retrieving and storing the data as per user request. Sometimes it is mistakenly referred as SQL, but both are different, as SQL is a language whereas SQL Server is a Microsoft product that supports SQL.
A Relational Database Management System (RDBMS) refers to the software used to store, manage, and query data. Data is stored in tables and can be linked to other datasets based on shared information, hence the name “relational”.
The key differences between Relational Database Management Systems (RDBMS) and Database Management Systems (DBMS) are :
 
* An RDBMS stores data in a relational table with rows and columns, whereas a DBMS stores data as a file

*
An RDBMS provides access to multiple users (including client-server side interaction), whereas a DBMS only supports single users
Authentication means identifying a user based on its username and password.

Two authentication modes on SQL Server are :
 
Windows Authentication : It is the default authentication mode in SQL Server. Trusted user and group accounts are authenticated when they login to the system. They do not have to present any additional credentials.
 
Mixed Authentication : It supports Windows authentication as well as SQL Server authentication. Windows authentication is the same as above. SQL Server maintains a username and password for authentication of valid users.
 
You can choose an authentication mode by changing Server Authentication on Security page in Properties of SQL Server Management Studio.
SQL is a programming language used to perform data-related tasks; every RDBMS uses SQL as its standard programming language. In these databases, SQL allows users to create tables, update data, make queries, and perform analytics.
If enabled, the default instance of the SQL Server Database Engine listens on TCP port 1433. Named instances of the Database Engine and SQL Server Compact are configured for dynamic ports.
* A clustered index is an index that rearranges the table in the order of the index itself. Its leaf nodes contain data pages. A table can have only one clustered index.
 
* A non-clustered index is an index that does not re-arrange the table in the order of the index itself. Its leaf nodes contain index rows instead of data pages. A table can have many non-clustered indexes.
A table can have one of the following index configurations :

* A clustered index : When only a single clustered index is present.
 
* A non-clustered index : When only a single non-clustered index is present.
 
* Many non-clustered indexes : When more than one non-clustered indexes is present.
 
* A clustered index and a non-clustered index : When a single clustered index and a single non-clustered index is present.
 
* A clustered index and many non-clustered indexes : When a single clustered index and more than one non-clustered indexes are present.
 
* No index : When there are no indexes present.
Suppose your server is running fine. Your application is booming all over the internet. Then, due to short-circuiting your servers went on fire. Now, all the data is gone and there’s nothing to show. Scary? It should be. This is the reason we always want to back up our data. So that in case of any disaster like hardware or software failure there will not be any data loss.
 
There are several types of backup options.
 
* Full backup : This backup includes all database objects, system tables, and data. Transactions that occur during the backup are also recorded.
 
* Transaction log backup : This backup records the transactions since the previous backup. Previous backup can be transaction log backup or full backup (whichever happened last). It then truncates the transaction log. Transaction log backup represents the state of the transaction log at the time the backup is initiated rather than at the time the backup completes. Transaction log backup functions incrementally rather than differentially. When restoring transaction log backup, you must restore in the sequence of transaction log backups.
 
* Differential backup : This backup backs the data that has been altered since the last full backup. Differential backup requires less time than a full database backup. Differential backups record transactions that occur during the differential backup process.

* Copy Only Backup : A copy-only backup is a SQL Server backup that is independent of the sequence of conventional SQL Server backups. Usually, taking a backup changes the database and affects how later backups are restored.
 
The types of copy-only backups are as follows :
 
   * Copy-only full backups (all recovery models)
 
  A copy-only backup cannot serve as a differential base or differential backup and does not affect the differential base.

  Restoring a copy-only full backup is the same as restoring any other full backup.
 
   * Copy-only log backups (full recovery model and bulk-logged recovery model only)
* File and Filegroup backup : This topic describes how to back up files and filegroups in SQL Server by using SQL Server Management Studio, Transact-SQL, or PowerShell. When the database size and performance requirements make a full database backup impractical, you can create a file backup instead. A file backup contains all the data in one or more files (or filegroups).
It is a process of attempting to optimize the performance of a database by adding redundant data. Redundancy is introduced intentionally in a table to improve performance, and it is called de-normalization. The de-Normalization process enhances the read performance while some degradation occurs in write performance. It can be achieved by making a group of data in the redundant form. The un-normalized and de-Normalized database are completely different from each other. Before the process of de-normalization of any database, that should be normalized firstly.
* A Function must return a value while stored procedure can return zero or n value.

* Functions can have only input parameter while procedures can have input/ output parameters.

* Functions take one mandatory input parameter while stored procedures may take 0 to n input parameter.

* Try-catch block can handle exceptions. In the stored procedure, while you can't use try-catch in functions.
Collation sensitivity is used to define the rules for sorting and comparing the strings of character data. The basic rule for sorting a character data are correct character sequence, Case-sensitivity, character width, and accent marks, etc.
 
Different types of collation sensitivity :
 
Case Sensitivity : Case sensitivity defines every character with a unique value, as alphabet characters A and a are treated individually, as they have different ASCII values for a computer language
 
Accent sensitivity : Accent sensitivity is related that whether the accent is off or not, as a and á both should be treated differently
 
Kana sensitivity : Kana sensitivity defines the difference between two Japanese words: Hiragana and Katakana
 
Width sensitivity : It differentiates between a single-byte character (half- width) and representation of the double-byte character of the same character
The Standby server is the type of server which is brought online when the primary server goes offline, and the application needs continuous availability of the server. The requirement for a mechanism which can shift a primary server to secondary or standby server is always there.
 
There are three types of standby servers :
 
* Hot standby : Hot standby method is a method of redundancy in which the primary and secondary backup systems run simultaneously so the data also present in the secondary server in a real-time and this way both systems contain identical information.
 
* Warm standby : Warm standby is a method of redundancy in which the secondary system runs in the background of the primary system. Data is mirrored in the secondary server at a regular interval, so in this method sometimes both servers don't contain the same data.
 
* Cold standby : Cold standby is the method of redundancy in which the secondary server is only called when the primary server fails. Cold standby systems are used in cases where data is changed infrequently or for nor critical applications. The physical replacement of Primary server with standby server occurs in cold standby.
Functions are part of SQL. A function in SQL Server is a group of statements that might take input, perform some task and return a result.
There are two types of function in SQL Server :
 
* System Defined Function : These functions are built-in ready-to-use and provided by SQL Server. Pass in input parameters if it takes one and get the result.

Example : Below code show min, max, and sum of ‘salary’ column values from ‘employee’ table
SELECT MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary, SUM(salary) AS TotalSalary
FROM employee
 
* User Defined Function : These are the functions that are written by users.
CREATE FUNCTION getAverageSalary(@salary int)
RETURNS int
AS
BEGIN RETURN(SELECT @salary)
END
CHECK constraint is applied to any column to limit the values that can be placed in it. It helps to enforce integrity in the database.
Suppose, your website caters to users between age 18 and 60 years. You can use CHECK to ensure that users who are creating an account have age in that range.
CREATE TABLE Users (
    id int NOT NULL,
    first_name varchar(255) NOT NULL,
    last_name varchar(255) NOT NULL,
    age int CHECK (age >= 18 AND age <= 60)
);
The trigger is a special type of stored procedure. It gets invoked automatically when an event like INSERT, UPDATE, DELETE, etc. happens on the database server. You can use it, for example, to enforce referential integrity in the database. Suppose you want to delete an author from the ‘authors’ table. You can use triggers to delete all rows in the ‘books’ table which has ‘author_id’ as of the deleted author.
 
Types of triggers :
 
DML trigger : DML trigger gets fired whenever a user tries to manipulate data using DML(Data Manipulation Language) event on the database server. DML events are INSERT, DELETE, or UPDATE.
 
DDL trigger : DDL trigger gets fired whenever a user tries to manipulate data using DDL(Data Definition Language) event on the database server. DDL events are CREATE, ALTER, DROP, etc.
 
Logon trigger : Logon trigger gets fired when a LOGON event is raised whenever a user’s session is created.
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT | UPDATE | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
   Declaration-statements
BEGIN
   Executable-statements
EXCEPTION
   Exception-handling-statements
END;
SQL Server Agent is a background tool for Microsoft SQL Server. It helps the database administrator(DBA) to schedule a job to run after a specific interval of time. These tasks can be scheduling backups, handling reporting services subscription or log-shipping tasks.
Replication in Microsoft SQL Server is a process to synchronize the data across multiple servers. This is generally done by a replica set, and these sets provide multiple copies of data with redundancy and high availability on different servers.
 
Not only this, but replication provides a mechanism to recover from failures. It also removes dependencies from single server to protect the loss of data from a single server.
 
Following are three types of replications in SQL Server :
 
* Merge Replication : This replication groups the data from various sources to a single centralized database and is used in the server to the client environment.

* Transactional Replication : This replication is a process of distributing data from publisher to subscriber and is used in server to server environment.

* Snapshot Replication : This replication distributes data exactly as it appears at a specific moment and is used for replicating data, which changes infrequently. 
Microsoft SQL Server uses a lock hierarchy whenever the data is  read or something is changed in the data. Whenever a row is read, SQL Server acquires a shared lock. Similarly, as soon as we change a row, SQL Server acquires an Exclusive lock. These locks are incompatible with each other. So, the INTENT locks are used to indicate at a higher level which locks are applied within a lock hierarchy.

There are mainly three kinds of INTENT locks :
 
* Intent Shared Lock(IS) : This lock is used when you have a shared lock at the row level.

* Intent Update Lock(IU) :
The Intent update lock is used when you have an update lock at the row level.

* Intext Exclusive Lock(IX) :
This lock is used when you have an exclusive lock at the row level.
The data quality services in SQL Server is a knowledge-driven data quality product. SQL Server Data Quality Services (DQS)  enable the user to build a knowledge base and thereafter use it to perform tasks such as correction, deduplication, enrichment, standardization of data.
 
Apart from this, DQS also provides profiling and enables you to perform data cleaning with the help of cloud-based data services.
 
DQS consists of two components :
 
* Data Quality Server : It is an SQL Server instance feature consisting of three SQL Server catalogs with data-quality functionality and storage

* Data Quality Client : It is an SQL Server feature which users can use to perform computer-assisted data quality analysis and manage their data quality interactively.
Magic Tables are tables automatically created tables in SQL Server used to internally store the inserted, updated values for DML operations such as (SELECT, DELETE, INSERT, UPDATE, etc).

There are two magic tables in SQL Server : "inserted" and "deleted". These tables are called magic tables because they do not exist physically.
 
* "inserted" table stores the data of last inserted row or “insert operation”.
* "deleted" table stores the data of last deleted row or “delete operation”.
 
Note : An update operation is actually a delete operation + an insert operation i.e., old data is deleted and new data is inserted.
 
For the sake of example, we assume there is a table with name Employee and columns ‘ID’ and ‘Name’.
 
SQL Server provides two ways to view data in magic tables.
 
Use Triggers : One way is to use triggers on delete, insert or update operations in a table to view the data in “inserted” and “deleted” magic tables.
CREATE TRIGGER Inserted_Trigger
ON Employee
FOR INSERT
AS
BEGIN
    SELECT * FROM Inserted
END
Whenever an insert operation will be done on Employee table, this trigger will be called and this will show the “inserted” table.
 
 
Use OUTPUT clause : Another way is to use the OUTPUT clause to view data in “inserted” or “deleted” magic tables. OUTPUT returns the copy of data inserted into or deleted from a table.
INSERT INTO Employee OUTPUT Inserted.* VALUES('Narayan')
Change Data Capture or most commonly known as CDC is used to record INSERT, UPDATE, DELETE activities applied on the tables. So, as the name suggests, Change Data Capture is used to capture the data that has been changed recently. The column information and metadata required to apply the changes to the target environment are captured for the modified rows and are eventually stored in the change tables. These change tables are the mirror image of the original column structure.  
A query is a request for data or information from a database.

There are two main types of SQL queries :
 
* A select query is a query that groups data from a table for analytical purposes
* An action query is a query that changes the contents of the database based on specified criteria
A subquery is a query that is embedded within another statement that requires multiple steps. The subquery provides the enclosing query with additional information needed to execute a task, such as when the completion of one query depends firstly on the results of another.
The join clause combines columns with related values from two or more tables to create a new table. There are four main types of SQL join clause :
 
* JOIN returns records with matching values in both tables
* LEFT JOIN returns all records from the left table and matching records from the right table
* RIGHT JOIN returns all records from the right table and matching records from the left table
* FULL JOIN returns all records from both tables
There are three main types of SQL subqueries. These are :
 
* Single-row subqueries, which return one row in results
* Multi-row subqueries, which return two or more rows in results
* Correlated subqueries, which return results according to outer queries
The main differences between the DELETE and TRUNCATE commands are :
 
* DELETE is a DML command, whereas TRUNCATE is a DDL command

* DELETE removes records and records each deletion in the transaction log, whereas TRUNCATE deallocates pages and records each deallocation in the transaction log

* TRUNCATE is generally considered quicker as it makes less use of the transaction log
* Local temporary tables are visible when there is a connection, and are deleted when the connection is closed.
CREATE TABLE #<tablename>
* Global temporary tables are visible to all users, and are deleted when the connection that created it is closed.
CREATE TABLE ##<tablename>
SQL server can be connected to any database which has OLE-DB provider to give a link.

Example : Oracle has OLE-DB provider which has link to connect with the SQL server group.
SIGN function is used to determine whether the number specified is Positive, Negative and Zero. This will return +1,-1 or 0.
 
Example :  SIGN(-35) returns -1
Bulkcopy is a tool used to copy large amount of data from Tables. This tool is used to load large amount of data in SQL Server.
Query to get the list of triggers in database :
 
Select * from sys.objects where type='tr'
* UNION : To select related information from two tables UNION command is used. It is similar to JOIN command.

* UNION ALL : The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It will not remove duplicate rows, instead it will retrieve all rows from all tables.
Following are the queries can be used to get the count of records in a table  :
Select * from <tablename> Select count(*) from <tablename> Select rows from sysindexes where id=OBJECT_ID(tablename) and indid<2
Select SERVERPROPERTY('productversion')

is used to get the version of SQL Server.
OLTP means Online Transaction Processing which follows rules of data normalization to ensure data integrity. Using these rules, complex information is broken down into a most simple structure.
Relational tables have six properties :
 
* Values are atomic.
* Column values are of the same kind.
* Each row is unique.
* The sequence of columns is insignificant.
* The sequence of rows is insignificant.
* Each column must have a unique name.
The differences between HAVING CLAUSE and WHERE CLAUSE is :
 
* HAVING Clause : HAVING CLAUSE is used only with the SELECT statement. It is generally used in a GROUP BY clause in a query.
 
 If GROUP BY is not used, HAVING works like a WHERE clause. HAVING clause can be used with the aggregate function.
 
Syntax :
SELECT expr1, expr2, expr3..,  
FROM tables  
WHERE condition   
GROUP BY expr1, expr2, expr3..,  
HAVING condition;   

 

WHERE Clause : The WHERE clause is applied to each row before they become a part of the GROUP BY function in a query. 'WHERE' clause cannot use with the aggregate function.
 
Syntax :
WHERE condition;
Log shipping is nothing but the automation of backup and restores the database from one server to another standalone standby server. This is one of the disaster recovery solutions. If one server fails for some reason we will have the same data available on the standby server.
Advantages of Log Shipping includes :
 
* Easy to set up.
* The secondary database can be used as a read-only purpose.
* Multiple secondary standby servers are possible
* Low maintenance.
Following are the common performance issues :
 
* Deadlocks
* Blocking
* Missing and unused indexes.
* I/O bottlenecks
* Poor Query plans
* Fragmentation
Various tools available for performance tuning are : 
 
* Dynamic Management Views
* SQL Server Profiler
* Server Side Traces
* Windows Performance monitor.
* Query Plans
* Tuning advisor
One-to-One relationship : It can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
 
One to one relationship exists if an entity in one table has a link with only one entity on another table. Let's take an example of the employee and their employee id so that a unique employee id will be there for a particular employee at another table.
COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments. COALESCE accepts all the values but it only returns non-null value present in the expression.
 
Syntax :
COALESCE(expr1, expr2, expr3,......,expr n) 
Scheduled tasks let you manage the tasks in an automated manner that runs on regular or predictable cycles. You can schedule administrative tasks and also determine the order in which tasks will run.
DBCC stands for database consistency checker. This command is used to check the consistency of the database. DBCC command help to review and monitoring the maintenance of tables, database, and for validation of operations done on the database, etc. For example:
 
DBCC CHECKDB : It makes sure that table in the database and the indexes are correctly linked.
 
DBCC CHECKALLOC : It checks all pages in the database and makes sure that all are correctly allocated.
 
DBCC CHECKFILEGROUP : It checks all table file group for any damage.
 
IF the user executes the above commands, a database snapshot is created through the database engine, and it continues in the consistent transactional state. After that, It runs the checks against stored database snapshot, and after the completion of the command, it dropped the snapshot.
The session object is used to maintain the session of each user. If a user enters into an application, he gets a session id, and when he leaves application, then the session id is deleted. If he enters again into the application, he gets a different session id, but for application object, once ad id is generated, it maintains the whole application.
A list of third-party tools used in SQL Server :
 
* SQL CHECK - Idera : It is used to monitor server activities and memory levels.
* SQL DOC 2 - RedGate : It is used to document the databases.
* SQL Backup 5 - RedGate : It is used to automate the Backup Process.
* SQL Prompt - RedGate : It provides IntelliSense for SQL SERVER 2005/2000.
* Lite Speed 5.0 - Quest Soft : It is used for Backup and Restore.
A list of advantages of using third-party tools :
 
* Third party tools provide faster backups and restore.
* They provide flexible backup and recovery options.
* They provide secure backups with encryption.
* They provide the enterprise view of your backup and recovery environment.
* Easily identify optimal backup settings.
* Visibility into the transaction log and transaction log backups.
* Timeline view of backup history and schedules.
* Recover individual database objects.
* Encapsulate a complete database restore into a single file to speed up restore time.
* When we need to improve upon the functionality that SQL Server offers natively.
* Save time, better information or notification.
* Third party tools can put the backups in a single compressed file to reduce the space and time.
Hotfixes are small software patches that are applied to live systems. A hotfix is a single, cumulative package that includes one or more files used to address a problem in a software product.
 
For example : a software bug
 
* A patch is a program installed in the machine to rectify the problem occurred in the system and ensured the security of that system. The hotfix is a Kind of Patches provided by the Microsoft.
 
* In Microsoft SQL Server, hotfixes are small patches designed to address specific issues, most commonly to freshly-discovered security holes. Hotfix response proactively against any bug
Trace flag in SQL server sets the specific characteristic of the server. It works as an "IF" condition for the SQL Server. The most common trace flags used with SQL Server are :
 
* Deadlock Information : 1204, 1205, 1222

* Network Database files : 1807

* Log Record for Connections : 4013

* Skip Startup Stored Procedures : 4022

* Disable Locking Hints : 8755

* Do Force uniform extent allocations instead of mixed page allocations 1118 (SQL 2005 and 2008).
FLOOR function is used to round up a non-integer value to the previous least integer. Floor expression returns a unique value after rounding down the expression.
 
Syntax :
FLOOR (expression)  
For example :
 
FLOOR (7.3)
A user can delete a TABLE from the database by using SQL Server Management Studio or by Transact-SQL in SQL Server
 
Following are the steps for deleting a table using SQL Server Management
 
* Select a Table(wanted to remove) in object explorer
* Choose DELETE from the shortcut menu by right- click on the table
* Click on the 'yes' to confirm the deletion of the table
* Hotfixes in SQL Server are the updates to fix issues which are not released publicly.

* Patches
in SQL Server are the updates to fix known issues or bugs. Microsoft releases patches publicly.
A developer must check type of information stored, volume of data and the data that will be accessed. 
 
* In a scenario, where you are upgrading an existing system, you should analyze the present data, existing data volumes occur, and check the method through which data is accessed, to help you understand the problem areas for design.
 
* In a scenario, where you are using a new system, you have to keep the information about what data will be captured, and what are the constituents of data, and the relationship between the data items.
To check locks in the database, you can use the in-built stored procedure sp_lock :
 
Syntax :
sp_lock [ [ @spid1 = ] 'session ID1' ] [ , [@spid2 = ] 'session ID2' ]
[ ; ]

 

Example : To list all the locks currently held in an instance of the Database Engine, use the following command :
USE SampleDB;  
GO  
EXEC sp_lock;  
GO ​
 
* UPDATE _STATISTICS is used to update the information used by indexes such as the distribution of key values for one or more statistic groups in the mentioned indexed view or table. 

*
SCOPE_IDENTITY is used to create identity value for tables in the current execution scope.
We can use encryption for security of data in the database in SQL Server. Following are the encryption mechanism used in SQL server :
 
* Certificates
* Symmetric keys
* Asymmetric keys
* Transact-SQL functions
* Transparent Data Encryption
SQL Server 2019 is available in 5 editions. These are as follows :
 
Enterprise : This delivers comprehensive high-end datacenter capabilities with blazing-fast performance, unlimited virtualization, and end-to-end business intelligence for mission-critical workloads and end-user access to data insights.

Standard : This delivers basic data management and business intelligence database for departments and small organizations to run their applications and supports common development tools for on-premises and cloud-enabling effective database management.

Web : This edition is a low total-cost-of-ownership option for Web hosters and Web VAPs to provide scalability, affordability, and manageability capabilities for small to large-scale Web properties.

Express : Express edition is the entry-level, free database and is ideal for learning and building desktop and small server data-driven applications.

Developer : This edition lets developers build any kind of application on top of SQL Server. It includes all the functionality of Enterprise edition, but is licensed for use as a development and test system, not as a production server.
These are built-in functions of the SQL Server like String functions which are provided by SQL Server like ASCII, CHAR, LEFT, etc. string functions.
Views are very beneficial because of the following reasons :
 
* Views are required to hide the complexity that is involved in the database schema and also to customize the data for a particular set of users.

* Views provide a mechanism to control access to particular rows and columns.

* These help in aggregating the data to improve the performance of the database.
TCL is Transaction Control Language Commands which are used to manage the transactions in the SQL Server.
There are 3 TCL Commands in the SQL Server. These are as follows :
 
Commit : This command is used to save the transaction permanently in the database.

Rollback : This is used to roll back the changes that are done i.e. to restore the database in the last committed state.

Save Tran : This is used for saving the transaction to provide the convenience that the transaction can be rolled back to the point wherever required.
SQL Server provides 6 types of Constraints. These are as follows :
 
* Not Null Constraint : This puts a constraint that the value of a column cannot be null.

* Check Constraint : This puts a constraint by checking some particular condition before inserting data in the table.

* Default Constraint : This constraint provides some default value that can be inserted in the column if no value is specified for that column.

* Unique Constraint : This puts a constraint that each row of a particular column must have a unique value. More than one unique constraint can be applied to a single table.

* Primary Key Constraint : This puts a constraint to have a primary key in the table to identify each row of a table uniquely. This cannot be null or duplicate data.

* Foreign Key Constraint : This puts a constraint that the foreign key should be there. A Primary key in one table is the foreign key of another table. Foreign Key is used to create a relation between 2 or more tables.
Stored Procedure can be executed with the help of keyword called RECOMPILE.
 
Example :
Exe <SPName>  WITH RECOMPILE
Or we can include WITHRECOMPILE in the stored procedure itself.