Basic SQL Server Interview Questions
Basic SQL Server Interview Questions
The model database, as its name implies, serves as the model (or template) for all databases created on the
same instance. If the model database is modified, all subsequent databases created on that instance will pick
up those changes, but earlier created databases will not. Note that TEMPDB is also created from the model
every time SQL Server starts up.
SQL profiler is the SQL Server utility you can use to trace the traffic on the SQL Server instance. Traces can
be filtered to narrow down the transactions that are captured and reducing the overhead incurred for the trace.
The trace files can be searched, saved off, and even replayed to facilitate troubleshooting.
SQL Server has three types of replication: Snapshot, Merge, and Transaction.
Snapshot replication creates a snapshot of the data (point-in-time picture of the data) to deliver to the
subscribers. This is a good type to use when the data changes infrequently, there is a small amount of data to
replicate, or large changes occur over a small period of time.
Merge replication uses a snapshot to seed the replication. Changes on both sides of the publication are tracked
so the subscriber can synchronize with the publisher when connected. A typical use for this type of replication
is in a client and server scenario. A server would act as a central repository and multiple clients would
independently update their copies of the data until connected. At which time, they would all send up their
modifications to the central store.
Transaction replication also begins with a snapshot only this time changes are tracked as transactions (as the
name implies). Changes are replicated from publisher to subscriber the same as they occurred on the
publisher, in the same order as they occurred, and in near real-time. This type of replication is useful when the
subscriber needs to know every change that occurred to the data (not point-in-time), when the change volume
is high, and when the subscriber needs near real-time access to the changes.
SQL Agent is the job scheduling mechanism in SQL Server. Jobs can be scheduled to run at a set time or
when a specific event occurs. Jobs can also be executed on demand. SQL Agent is most often used to
schedule administrative jobs such as backups.
Checkpoints, whether scheduled or manually executed, cause the transaction log to be truncated up to the
beginning of the oldest open transaction (the active portion of the log). That is, the dirty pages from the buffer
cache are written to disk. Storing committed transactions in the cache provides a performance gain for SQL
Server. However, you do not want the transaction log to get too big because it might consume too many
resources and, should your database fail, take too long to process to recover the database.
One important thing to note here is that SQL Server can only truncate up to the oldest open transaction.
Therefore, if you are not seeing the expected relief from a checkpoint, it could very well be that someone
forgot to commit or rollback their transaction. It is very important to finalize all transactions as soon as
possible.
7. What is DBCC?
DBCC statements are Database Console Commands and come in four flavors:
1. Maintenance
2. Informational
3. Validation
4. Miscellaneous
Maintenance commands are those commands that allow the DBA to perform maintenance activities on the
database such as shrinking a file.
Informational commands provide feedback regarding the database such as providing information about the
procedure cache. Validation commands include commands that validate the database such as the ever-popular
CHECKDB. Finally, miscellaneous commands are those that obviously don’t fit in the other three categories.
This includes statements like DBCC HELP, which provides the syntax for a given DBCC command.
8. How can you control the amount of free space in your index pages?
You can set the fill factor on your indexes. This tells SQL Server how much free space to leave in the index
pages when re-indexing. The performance benefit here is fewer page splits (where SQL Server has to copy
rows from one index page to another to make room for an inserted row) because there is room for growth built
into the index.
Update Statistics is used to force a recalculation of query optimization statistics for a table or indexed view.
Query optimization statistics are automatically recomputed, but in some cases, a query may benefit from
updating those statistics more frequently.
Beware though that re-computing the query statistics causes queries to be recompiled. This may or may not
negate all performance gains you might have achieved by calling update statistics. In fact, it could have a
negative impact on performance depending on the characteristics of the system.
A correlated sub-query is a nested query that is linked to the outer query. For instance, say I wanted to find all
the employees who have not entered their time for the week. I could query the Employee table to get their first
and last name, but I need to look at the time entry table to see if they’ve entered their time or not. I can’t do a
straight join here because I’m looking for the absence of time data, so I’ll do a correlated sub-query similar to
this:
Notice that the inner query relates to the outer query on the employee ID, thus making it a correlated sub-
query. The inner query will be evaluated once per the outer query row.
SQL Server supports Windows Authentication and mixed-mode. Mixed-mode allows you to use both
Windows Authentication and SQL Server Authentication to log into your SQL Server. It’s important to note
that if you use Windows Authentication, you will not be able to log in.
This is a generic question often asked by many interviewers. Explain what are the different SQL Server
Versions you have worked on, what kind of administration of those instances has been done by you.
Your role and responsibilities carried out in your earlier projects would be of significance to the potential
employer. This is the answer that lets the interviewer know how suitable are you for the position to which you
are being interviewed.
13. What are the different SQL Server Versions you have worked on?
The answer would be depending on the versions you have worked on, I would say I have experience working
in SQL Server 7, SQL Server 2000, 2005, and 2008. If you have worked only on some versions be honest in
saying that, remember, no one would be working on all versions, it varies from individual to individual.
14. What are the different types of Indexes available in SQL Server?
The simplest answer to this is “Clustered and Non-Clustered Indexes”. There are other types of Indexes that
can be mentioned such as Unique, XML, Spatial and Filtered Indexes. More on these Indexes later.
In a clustered index, the leaf level pages are the actual data pages of the table. When a clustered index is
created on a table, the data pages are arranged accordingly based on the clustered index key. There can only
be one Clustered index on a table.
In a Non-Clustered index, the leaf level pages do not contain data pages instead it contains pointers to the data
pages. There can multiple non-clustered indexes on a single table.
16. What are the new features in SQL Server 2005 when compared to SQL Server 2000?
There are quite a lot of changes and enhancements in SQL Server 2005. A few of them are listed here:
Database Partitioning
Resource Database
Database Snapshots
1. Profiler being able to trace the MDX queries of the Analysis Server.
2. Peer-to-peer Replication
3. Database Mirroring
17. What are the High-Availability solutions in SQL Server and differentiate them briefly?
Failover Clustering, Database Mirroring, Log Shipping, and Replication are the High-Availability features
available in SQL Server. I would recommend reading this blog of mine which explains the differences
between these 4 features.
The execution history of the job is displayed and you may choose the execution time (if the job failed multiple
times during the same day). There would information such as the time it took to execute that Job and details
about the error that occurred.
1433
20. How many files can a Database contain in SQL Server? How many types of data files exist in SQL
Server? How many of those files can exist for a single database?
2. There are Primarily 2 types of data files Primary data file and Secondary data file(s)
3. There can be only one Primary data file and multiple secondary data files as long as the total # of files is
Fill Factor is a setting that is applicable to Indexes in SQL Server. The fill factor value determines how much
data is written to an index page when it is created/rebuilt.
25. Where do you find the default Index fill factor and how to change it?
The easiest way to find and change the default fill factor value is from Management Studio, right-click the
SQL Server, and choose properties. In the Server Properties, choose Database Settings, you should see the
default fill factor value in the top section.
You can change to the desired value there and click OK to save the changes. The other option for viewing and
changing this value is using.
There are 3 recovery models available for a database. Full, Bulk-Logged, and Simple are the three recovery
models available.
Primarily, the recovery model is chosen keeping in view the amount of data loss one can afford. If one
expects to have minimal or no data loss, choosing the Full recovery model is a good choice.
Depending on the recovery model of a database, the behavior of the database log file changes. I would
recommend you read more material on log backups and log file behavior and so on to understand in depth.
Replication is a feature in SQL Server that helps us publish database objects and data and copy (replicate) it to
one or more destinations. It is often considered as one of the High-Availability options. One of the advantages
of Replication is that it can be configured on databases that are in a simple recovery model.
30. What the different types of Replication and why are they used?
There are basically 3 types of replication: Snapshot, Transactional and Merge Replication. The type of
Replication you choose depends on the requirements and/or the goals one is trying to achieve. For example,
Snapshot Replication is useful only when the data inside the tables does not change frequently and the amount
of data is not too large, such as a monthly summary table or a product list table, etc.
Transactional Replication would useful when maintaining a copy of a transactional table such as sales order
tables etc. Merge Replication is more useful in the case of remote / distributed systems where the data flow
can be from multiple sites, for example, sales done at a promotional event that might not be connected to the
central servers always.
31. What the different components of Replication and what is their use?
The 3 main components in Replication are Publisher, Distributor, and Subscriber. The publisher is the data
source of a publication. The distributor is responsible for distributing the database objects to one or more
destinations. The subscriber is the destination where the publisher's data is copied/replicated.
32. What are the different Topologies in which Replication can be configured?
Replication can be configured in any topology depending on keeping in view the complexity and the
workload of the entire Replication. It can be any of the following:
Publisher and Distributor on the same SQL Instance and Subscriber on a separate Instance.
Publisher, Distributor, and Subscriber on individual SQL Instances.
33. If you are given access to a SQL Server, how do you find if the SQL Instance is a named instance or
a default instance?
I would go to the SQL Server Configuration Manager. In the left pane of the tool, I would select SQL Server
Services, the right side pane displays all of the SQL Server Services/components that are installed on that
machine. If the Service is displayed as (MSSQLSERVER), then it indicates it is a default instance, else there
will be the Instance name displayed.
34. What are the different authentication modes in SQL Server and how can you change authentication
mode?
SQL Server has 2 Authentication modes; Windows Authentication and SQL Server and Windows
Authentication mode also referred to as Mixed Mode.
35. What are the differences in Clustering in SQL Server 2005 and 2008 or 2008 R2?
On SQL Server 2005, installing the SQL Server failover cluster is a single-step process whereas on SQL
Server 2008 or above it is a multi-step process. That is, in SQL Server 2005, the Installation process itself
installs on all of the nodes (be it 2 nodes or 3 nodes). In 2008 or above this has changed, we would need to
install separately on all the nodes. 2 times if it is a 2 node cluster or 3 times in a 3 node cluster, and so on.
An Active-Passive cluster is a failover cluster configured in a way that only one cluster node is active at any
given time. The other node, called the Passive node is always online but in an idle condition, waiting for a
failure of the Active Node, upon which the Passive Node takes over the SQL Server Services and this
becomes the Active Node, the previous Active Node now being a Passive Node.
An Active-Active cluster is a failover cluster configured in a way that both the cluster nodes are active at any
given point in time. That is, one Instance of SQL Server is running on each of the nodes always; when one of
the nodes has a failure, both the Instances run on only one node until the failed node is brought up (after
fixing the issue that caused the node failure). The instance is then failed over back to its designated node.
37. List out some of the requirements to set up a SQL Server failover cluster?
Virtual network name for the SQL Server, Virtual IP address for SQL Server, IP addresses for the Public
Network and Private Network(also referred to as Heartbeat) for each node in the failover cluster, shared
drives for SQL Server Data and Log files, Quorum Disk, and MSDTC Disk.
Introduced in SQL Server 2008 Transparent Data Encryption (TDE) is a mechanism through which you can
protect the SQL Server Database files from unauthorized access through encryption. Also, TDE can protect
the database backups of the instance on which TDE was set up.
39. Does Transparent Data Encryption provide encryption when transmitting data across the network?
No, Transparent Data Encryption (TDE) does not encrypt the data during transfer over a communication
channel.
40. What are the operating modes in which Database Mirroring runs?
Database Mirroring runs in 2 operating modes High-Safety Mode and High-Performance Mode.
41. What is the difference between the 2 operating modes of Database Mirroring (mentioned in the
above answer)?
1. High-Safety Mode is to ensure that the Principal and Mirrored database are synchronized state, that is
the transactions are committed at the same time on both servers to ensure consistency, but there
2. High-Performance Mode is to ensure that the Principal database runs faster, by not waiting for the
Mirrored database to commit the transactions. There is a slight chance of data loss and also the
Mirrored database can be lagging behind (in terms of being up to date with the Principal database) if
42. When setting Replication, is it possible to have a Publisher as a 64 Bit SQL Server and Distributor
or Subscribers as a 32 Bit SQL Server?
43. What is the difference between dropping a database and taking a database offline?
Drop database deletes the database along with the physical files, it is not possible to bring back the database
unless you have a backup of the database. When you take a database offline, the database is not available for
users, it is not deleted physically, it can be brought back online.
Setting an auto-growth in multiples of MB is a better option than setting auto growth in percentage (%).
45. What are the different types of database compression introduced in SQL Server 2008?
46. What are the different types of Upgrades that can be performed in SQL Server?
47. On a Windows Server 2003 Active – Passive failover cluster, how do you find the node which is
active?
Using Cluster Administrator, connect to the cluster and select the SQL Server cluster. Once you have selected
the SQL Server group, on the right-hand side of the console, the column “Owner” gives us the information of
the node on which the SQL Server group is currently active.
From Start -> Run and type CluAdmin (case insensitive) and the Cluster Administrator console is displayed
OR you can also go to Start -> All Programs -> Administrative Tools -> Cluster Administrator.
49. Due to some maintenance being done, the SQL Server on a failover cluster needs to be brought
down. How do you bring the SQL Server down?
In the Cluster Administrator, rick click on the SQL Server Group, and from the popup menu item choose to
Take Offline.
50. What are the different ways you can create Databases in SQL Server?
51. When setting Replication, can you have a Distributor on SQL Server 2005, Publisher of SQL Server
2008?
No, you cannot have a Distributor on a previous version than the Publisher.
5. Question 5. Where Does The Copy Job Runs In The Log Shipping Primary
Or Secondary?
Answer :
Secondary server. This question is basically asked to find out whether you have a
hands on work on log shipping or not.
6. Question 6. What Are The Ways To Find What Code Is Running For Any
Spid?
Answer :
Well there are many ways to do this.
o find the spid which you want to analyze. An spid is assigned as soon as a
client connection is established with the SQL server. To find the spid you
can run any of the following command:
o SP_WHO2 ‘ACTIVE’ — This will give you only active spids.
o SELECT * FROM sys.dm_exec_requests
o Get the spid from above two queries and use any of the following query
to get what is happening behind that spid.
o dbcc inputbuffer()
o sql2005 and sql2008 – SELECT * FROM sys.dm_exec_sql_text()
o sql2005 and sql2008 – SELECT * FROM fn_get_sql()
7. Question 7. When You Get Following Error? Error 3154: The Backup Set
Holds A Backup Of A Database Other Than The Existing Database?
Answer :
The error comes when you are trying to restore the DB which already exists. Use
WITH REPLACE option to restore the DB with a different name
9. Question 9. How To View The Error Log For Any Specific Instance?
Answer :
There are many ways but I prefer following method. Take a scenario when you
want to find the error log when the DB was put in a single user mode.
CREATE TABLE #Errorlog (Logdate Datetime, Processinfo
VARCHAR(20),Text VARCHAR(2000))
INSERT INTO #Errorlog
EXEC xp_readerrorlog
SELECT * FROM #Errorlog
WHERE Text Like ‘%SINGLE%USER%’
10. Question 10. According To You What Goes Into Making The Best
Database Administrator?
Answer :
The primary job of DBAs is to secure the data. They should be able to keep it safe
as well as reproduce it efficiently, whenever required. So as per my view, a
Database Administrator who can fulfill the requirements of Securing Data and
Retrieving Data is the best DBA.
When I hire a DBA I always ask them questions about backup strategies and
efficient restoring methodologies.
11. Question 11. I Have All The Primary Data Files, Secondary Data Files
As Well As Logs. Now, Tell Me Can I Still Restore The Database Without
Having A Full Backup?
Answer :
You cannot restore the database without having a full database backup.
However, if you have the copy of all the data files (.mdf and .ndf) and logs (.ldf)
when database was in working condition (or your desired state) it is possible to
attach the database using sp_attach_db.
12. Question 12. As Per Your Opinion What Are The Five Top
Responsibilities Of A Dba?
Answer :
I rate the following five tasks as the key responsibilities of a DBA.
o Securing database from physical and logical integrity damage.
o Restoring database from backup as a part of disaster management plan.
o Optimizing queries performance by appropriate indexing and optimizing
joins, where conditions, select clause etc.
o Designing new schema, support legacy schema, and legacy database
systems.
o Helping developers improve their SQL-related code writing skill.
14. Question 14. What Is The Difference Between Sql Server 2000
Object Owner And Sql Server 2005 Schema?
Answer :
Let us first see the fully qualified query name to access a table for SQL Server
2000 and SQL Server 2005.
SQL Server 2000: [DataBaseServer].[DataBaseName].[ObjectOwner].[Table]
SQL Server 2005: [DataBaseServer].[DataBaseName].[Schema].[Table]
SQL Server 2008: [DataBaseServer].[DataBaseName].[Schema].[Table]
In SQL Server 2000, prior to dropping the user who owns database objects, all
the objects belonging to that user either need to be dropped or their owner has
to be changed. Every time a user is dropped or modified, system admin has to
undergo this inconvenient process.
In SQL Server 2005 and the later versions, instead of accessing a database
through database owner, it can be accessed through a schema. Users are
assigned to schemas, and by using this schema a user can access database
objects. Multiple users can be assigned to a single schema, and they all can
automatically receive the same permissions and credentials as the schema to
which they are assigned. Because of the same reason in SQL Server 2005 and
the later versions – when a user is dropped from database – there is no negative
effect on the database itself.
15. Question 15. What Is Bi? I Have Heard This Term Before But I Have
No Idea About It?
Answer :
BI stands for Business Intelligence. Microsoft started to promote the acronym BI
since the launch of SQL Server 2005. However, it has been in use for a long time.
The basic idea of BI is quite similar to Data Warehousing. Business intelligence is
a method for storing and presenting accurate and timely key enterprise data to
CXO, IT Managers, Business Consultants, and distributed teams of a company, to
provide them with up-to-date information to drive intelligent decisions for
business success, which ultimately leads to enhanced revenue, reduced risk,
decreased cost, and better operational control for business agility and
competitiveness. An effective BI empowers end users to use data to understand
the cause that led to a particular business result, to decide on the course of
action based on past data, and to accurately forecast future results.
17. Question 17. What Should Be The Fill Factor For Indexes Created On
Tables?
Answer :
Fill factor specifies a percentage that indicates how full the Database Engine
should make the leaf level of each index page during index creation or alteration.
Fill factor must be an integer value from 1 to 100. The default is 0. I prefer to
keep my servers default fill factor as 90.
18. Question 18. Which Feature In Sql Server 2008 Has Surprised You?
You Can Name Just One.
Answer :
Plan Freezing is a new feature I never thought of. I find it very interesting! It is
included in SQL Server 2008 CTP5. SQL Server 2008 enables greater query
performance stability and predictability by providing new functionality to lock
down query plans. This empowers organizations to promote stable query plans
across hardware server replacements, server upgrades, and production
deployments.
19. Question 19. How Do You Test Your Database?
Answer :
This is a very generic question. I would like to describe my generic database
testing method as well as stored procedure testing methods.
Testing Databases:
Table Column data type and data value validation.
Index implementation and performance improvement.
Constraints and Rules should be validated for data integrity.
Application field length and type should match the corresponding database field.
Database objects like stored procedures, triggers, functions should be tested
using different kinds of input values and checking the expected output variables.
20. Question 20. What Are System Databases Into Sql Server
(2005/2008)
Answer :
TEMPDB, MSDEB, MASTER, MSDB, mssqlsystemresource.
29. Question 29. Describe The Left Outer Join & Right Outer Join.
Answer :
Left Outer join Retrieves the all records from LEFT table and matching from the
RIGHT table, and null values where is no match. Right Outer Join just opposite.
32. Question 32. What Are The Difference Between Primary Key And
Unique Key?
Answer :
An unique key cant not be referenced as foreign key. And it may allow on null.
33. Question 33. What Is Mean By Clustered Index And Non Clustered
Index, Give Syntax Of Creation?
Answer :
create clustered index index_name on empmst(card)
34. Question 34. What Is Scan Table/view And Seek Table/view When Its
Occurs?
Answer :
A Table/view SCAN occurs when no useful indexes exist. A TABLE SCAN reads all
data, row by row, to find the match.
35. Question 35. What Is Sql Profiler. What Are The Default Templates
With It?
Answer :
SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an
instance of the Database Engine or Analysis Services. You can capture and save
data about each event to a file or table to analyze later.
39. Question 39. How To Truncate The Log In Sql Server 2012?
Answer :
BACKUP LOG TestDB WITH TRUNCATE_ONLY is gone. SQL server does not allow
you to truncate the log now otherwise whole purpose of a DB is defeated. You
have to make sure whether you need log or not. If you do not need log then have
the recovery model simple instead of full. If you do not want the log to be
accumulated in some particular bulk logging then change the recovery model
BULK LOGGED for that duration and take one TLog Backup just before and after
this change. I shall discuss this later in my later blog. BACKUP LOG command
backs up the t-log and frees the space in the log file.
40. Question 40. What Is The Purpose Of Sql Profiler In Sql Server?
Answer :
SQL profiler is a tool to monitor performance of various stored procedures. It is
used to debug the queries and procedures. Based on performance, it identifies
the slow executing queries. Capture any problems by capturing the events on
production environment so that they can be solved.
41. Question 41. What Is Copyonly Data Backup? How This Is Useful?
Answer :
There are 21 types of Backups in SQL Server. A non-base FULL BACKUP is called
COPYONLY Data Backup. This is used to service 'on demand' Backup requests
from end users. Using this type of Backups, we can service the 'on demand'
backup requests from end users without disturbing the Backup sequence of Jobs /
Maintenance Plans or other differential Backups. This gives us easy restore paths
as well in case of DR process.
42. Question 42. What Are Truncate Options Available In Sql Server?
Answer :
Use TRUNCATE_ONLY option for SQL Server 2005 systems while performing
Backup. This option is not available in SQL Sever 2008 and R2. Instead, we use
ON_TRUNCATE option available in the Backup statement.
45. Question 45. What Are The Uses Of Standby Mode In Log Shipping?
Answer :
If the Restore Jobs is scheduled / delayed for longer intervals this option can be
used. As uses needs to be disconnected every time Restore Job runs(to ensure
timely shipping of Transaction Logs) its recommended not to use this option for
regular, less interval Log Shipping configurations. Using this option gives us
advantage of Load Balancing for READONLY connections and Reporting purposes
at the cost of timely disconnections to help success of Restore Jobs.
48. Question 48. Where Can You Find The Error Log Information?
Answer :
We can make use of SQL Profiler , SQL Server Log or use xp_readerrorlog
extended Stored Procedure to retrieve the error log information.
49. Question 49. What Is The Status Of Services On Passive Node For
Failover Cluster In Sql Server?
Answer :
SQL services will be in manual and stopped. Cluster service will be in automatic
and started mode on both the nodes.
50. Question 50. Can You Move The Resources After Pausing The Node?
Answer :
Yes resources can be moved after pausing the node. But we can't move them
back till the node is paused.
51. Question 51. What Happens If We Start The Full Text Service On
Passive Node.
Answer :
This can be started on both the nodes as this doesn't have any dependency on
SQL service or any resource which is possessed by active node.
53. Question 53. What Are The Basic Functions For Master, Msdb,
Model, Tempdb And Resource System Databases?
Answer :
o The master database holds information for all databases located on the
SQL Server instance. As SQL Server cannot start without a functioning
master database, we must administer this database with care and
monitor Startup Parameters in Configuration Manager.
o The msdb database stores information regarding database backups, SQL
Agent information, DTS packages, SQL Server jobs, and some replication
information such as for log shipping.
o The tempdb holds temporary objects such as global and local temporary
tables and stored procedures.
o The model is essentially a template database used in the creation of any
new user database created in the instance.
o The resource Database is a read-only database that contains all the
system objects that are included with SQL Server. SQL Server system
objects, such as sys.objects, are physically persisted in the Resource
database, but they logically appear in the sys schema of every database.
The Resource database does not contain user data or user metadata.
54. Question 54. What Is Service Broker?
Answer :
Service Broker is a message-queuing technology in SQL Server that allows
developers to integrate SQL Server fully into distributed applications. Service
Broker is feature which provides facility to SQL Server to send an asynchronous,
transactional message. it allows a database to send a message to another
database without waiting for the response, so the application will continue to
function if the remote database is temporarily unavailable.
55. Question 55. Where Sql Server User Names And Passwords Are
Stored In Sql Server?
Answer :
They get stored in System Catalog Views sys.server_principals and sys.sql_logins.
59. Question 59. What Are The Steps To Take To Improve Performance
Of A Poor Performing Query?
Answer :
Steps to take to improve performance of queries:
o Use indexes efficiently
o Create all primary and foreign keys and relationships among tables.
o Avoid using cursors
o Avoid using Select*, rather mention the needed columns and narrow the
resultset as needed.
o Denormalize
o Use partitioned views
o Use temporary tables and table variables
o Reduce joins and heavy clauses like GROUP BY if not needed
o Implement queries as stored procedures.
o Have a WHERE Clause in all SELECT queries.
o Use data types wisely
o Instead of NULLS use string values such as N/A
60. Question 60. What Is A Deadlock And What Is A Live Lock? How Will
You Go About Resolving Deadlocks?
Answer :
o Deadlock occurs when two user processes/transactions have locks on 2
separate objects and each process is trying to acquire a lock on the
object that has been acquired by the other process. In such a scenario
each process is waiting for the other process to release the lock to
acquire a lock on the object itself. When a request for exclusive lock is
denied again and again because a series of overlapping shared locks are
interfering with each other and to adapt from each other they keep on
changing the status, it is known as live lock.
o One can resolve deadlocks by using TRY CATCH blocks. If the code inside
a TRY statement fails, the CATCH automatically catches the control of
the flow letting the transaction rollback and resume execution.
61. Question 61. What Is Blocking And How Would You Troubleshoot It?
Answer :
Blocking occurs when a process has acquired lock on a set of rows, and another
process is trying to acquire a lock on the same set of rows. In such a case, the
other process has to wait until the first process finishes its job and releases the
lock on the above said rows.
o Use sp_lock procedure to see type of locks acquired by various sessions
on the server to find the cause of blocking.
o Problem is hinted by the WAIT status is a lot of rows that are returned as
an output of sp_lock stored procedure execution.
o Use sp_who and sp_who2 to return more columns to get more
information around the blocking.
o Use DBCC INPUTBUFFER (spid).This will show the last 128 characters of
the last T-SQL statement executed from connection referred through
spid. This way one can identify the stored procedure or application
module that caused blocking.
o To resolve blocking, you can disconnect the connection causing the
blocking using KILL command. If this does not solve the problem
permanently, then rewrite the stored procedure/module causing the
block more efficiently.
What is SQLOS?
SQLOS stands for SQL Server Operating System. SQLOS is the lowest layer of SQL Server Database Engine
which is responsible to perform critical internal tasks like scheduling threads on CPU to execute SQL Serve
transactions, memory management, deadlock detection, and IO completion activities. It works just like
another mini operating system for SQL Server operations.
Any record deleted from SQL Server is not actually deleted from its physical data pages but marked as “To
BE DELETED” or “GHOSTED” by changing a bit in the row header. These records will be cleaned up by an
internal process that is called the ghost cleanup process. This is a single-threaded background process that
automatically runs on some intervals to check if any page is marked for ghost records or not and if it finds
any, then it physically removes those ghosted records from pages.
What would be the potential reason behind SQL Server connection issues?
You might be failed to connect to SQL Server instance because of various reasons such as:
Ensure you are entering the right connection details like server name and port no
Ensure SQL Server port is open from the machine you are connecting to the instance
Make sure SQL Server instance is running
TCP or named pipe protocols are enabled through SQL Server configuration manager
SQL browser service is not running
Is it possible that database physical file names also changed after renaming a database?
No, renaming a database will not change its physical file names. You need to manually perform additional
steps to change the database physical file names.
Explain how will you change the physical file name of a data file?
Changing the physical database file name is multistep activity. We must not perform such activities on regular
basis and only do them on a need basis. Below are the high-level steps to change a physical file of a database.
Update system catalog with new files names by running ALTER DATABASE statement for each file
separately
USE master
1
GO
2
ALTER DATABASE SQLSHACK MODIFY FILE (Name='SQLSHACK_Data1', FILENAME='F:\
3
MSSQL12.MSSQLSERVER\MSSQL\DATA\SQLSHACK_Renamed.mdf')
4
GO
How do you get I/O statistics of a specific database file like the number of reads, writes, IO stalls, etc.?
We can use either the system dynamic management function sys.dm_io_virtual_file_stats or a system function
fn_virtualfilestats to get this information. We need to pass database and file id details about that specific
database file for which we are looking for IO statistics. Below is its example. I am pulling IO statistics for the
master database log file.
Automatic seeding is a feature launched in SQL Server 2016 to initialize the secondary replica. Earlier we
have only one option to initialize secondary replica that is using backup, copy and restore database operation.
We use this feature while creating the always on availability group. Although Microsoft has given this feature,
but it is not suitable for very big databases or if you have multiple databases on your SQL Server instance
because this feature is a single-threaded process that affects performance and can take long hours to initialize
your secondary replica.
Only 2 replicas can be created. One primary replica and another one is a secondary replica
Only 1 database will work as an availability database just like in database mirroring
Secondary replica cannot be used for reading transactions, database backups, or other database
maintenance activities
Basic availability groups cannot be part of distributed availability groups
We cannot upgrade basic availability groups to standard availability groups. We need to drop them
and reconfigure standard availability groups from scratch
Microsoft has added a new feature in SQL Server 2016 availability groups where you can configure your
databases participating in availability groups to failover if they are unable to do write operations. Earlier
versions of SQL Server were not triggering failover if any database from the availability group was unable to
write operation. It is also called database level health detection in the availability group. This is an optional
feature that can be configured during creating an availability group or you can even configure it by running
the below ALTER statement for existing availability groups.
How do you know whether Enhanced Database Failover is configured or enabled for your availability
group or not?
We can get this information by accessing a dynamic management view sys.availability_groups. This DMV
has a column named DB_Failover, if the value of this column is 0 it means enhanced database failover is not
enabled and if the value of this column is 1 then enhanced database failover is enabled for that availability
group.
Can we run DBCC CHECKDB on the secondary replica of the availability group?
Yes, we can execute CHEKDB on a secondary replica for database integrity check. This will ensure the
integrity of the database hosted on secondary replica only. This execution will not guarantee the integrity of
the database hosted on a primary replica as a primary replica uses a different set of storage systems to host
their databases.
Yes, database snapshots can be created of primary or secondary databases if their role state is either
PRIMARY or SECONDARY. Database snapshots cannot be created if the role state is RESOLVING.
You have created a database snapshot on the primary replica. What would happen to the database snapshot if
the primary replica failed over to the secondary replica?
Database snapshots will not have any impact. They will be there on previous primary replica and you can use
them for your requirements.
Can we get how much space is needed in the tempdb database to run DBCC CHECKDB without
running its actual execution?
DBCC CHECKDB heavily uses a tempdb database to temporarily store data and perform activities that are
needed for integrity check like reading each data page and ensuring there is no corruption. We can use DBCC
CHECKDB WITH ESTIMATEONLY statement to predict the estimated amount of tempdb space before
its actual execution.
Can we change the restore mode of the secondary database from NORECOVERY to STANDBY in
SQL Server log shipping configuration?
Yes, we can change the secondary database restore mode from restoring to standby to use it for read-only
operations. We will use a system stored procedure sp_change_log_shipping_secondary_database to make
this change. This stored procedure will take an input value 1 for argument @restore_mode while running it.
There are two values for this argument. Use 1 to restore the log with STANDBY and use 0 to restore the log
with NORECOVERY.
Merge Replication does not use a queue reader agent so there is no functionality of queue reader agent in
Merge replication.
Can we replicate SQL Server data to other RDBMS systems like Oracle?
Yes, SQL Server replication can be used to publish data from SQL Server to Oracle or Oracle to SQL Server.
DELETE statements can be prevented to replicate any articles in SQL Server replication. We can get this
done by accessing the properties window of the identified article and choose not to replicate delete statements
there.
What would be the impact on Log shipping if the SQL Server Agent job is stopped and not running?
Log shipping relies on agent jobs to do all its activities. If SQL Server Agent is stopped, log shipping will not
perform these activities of backup, copy, and restore and can become out of sync if the agent will be stopped
for a longer duration.
Replication is the process by which data is stored in more than one place in a database. This is a general
question that tests your knowledge of data processing in an SQL system.
Example: “There are three types of replication in SQL server, namely snapshot, merge and transaction.
*Snapshot replication: This kind of replication involves a snapshot of the publisher’s database that is then
distributed to subscribers. Snapshot replication is rarely used, as it’s time and resource intensive, but would,
for instance, be applicable when a subscriber’s database needs to be completely overwritten.*
*Merge replication: This replication is well-suited when both the publisher and subscriber need to make
changes to their databases and these changes have to be merged.*
*Transaction replication: This kind of replication takes place when changes happen frequently. The
replication process constantly monitors the publisher for changes and then updates subscribers accordingly.”*
As a database administrator, troubleshooting database issues should be your specialty and is an essential
function of the job. Answering this question allows you to show, by example, that you understand how to
handle performance issues that are a part of the DBA role.
In the example below, you’ll see the STAR method of answering interview questions is used in part of the
answer. This is a method that asks you to speak from your experience by considering a challenging situation,
your role in the situation, what tasks were performed to solve it and what overall outcome was achieved.
Example: “The most common SQL server issues relate to CPU, memory, networking, and I/O bottlenecks. To
get to the bottom of the problem, there are a few troubleshooting tools you can use.
*Performance Monitor: This is a Windows system monitoring tool that displays metrics with regard to key
system components such as CPU, memory, disks, and networking.*
*Execution Plan: This is a useful SQL server tool, as query execution plans can be used to establish
processes that need to be fine-tuned for a query to run faster.*
*SQL Profiler: This tool helps you trace and troubleshoot problems in SQL server, by, for instance, tracing
and evaluating database queries.*
*DMV and DMF Queries: Dynamic Management Views and Functions are system views and functions that
allow administrators to monitor the performance of the SQL server instance, in this way diagnosing issues.*
*SP_WHO2: This is a defined stored procedure that will give you information on current users, sessions and
processes in a SQL server instance.*
What is blocking and what’s the best way to deal with it?
To deal with reads and writes from multiple inputs in a database, either a read lock or an exclusive lock has to
be applied to a piece of data. To prevent data changes while a person is reading it, a read lock is applied on
that data and, if data needs to be edited, an exclusive lock is used to prevent people from reading the data
while it's being changed.
These two important features of a database result in the intentional blocking of data. Blocking is important for
administrators to understand because it’s a function they may be called upon to use or troubleshoot.
Answering this question also gives you the chance to explain a database issue in simple, clear terms that even
people without the same level of technical expertise can understand.
Example: “Blocking occurs when one connection is holding a lock on a resource while a second connection
wants to read or write to it. An even more complex situation occurs when two connections each hold a lock
but want to access each other’s resource, which is referred to as deadlocking.
Two effective ways of locating and dealing with block issues are:
*The SP_WHO2: This stored procedure will provide you with a list of queries, and any process that is locked
will display the SPID of the process that is causing the block.*
*The DBCC set of commands, and more specifically DBCCINPUTBUFFER, can also be used to trace the
“bad query” that is blocking other processes.*
*SQL Server Management Activity Monitor: This tool can also be used to view processes to find out
which ones are in a blocked state.”*
What is DBCC?
DBCC is a hub of essential functions for any DBA. To appropriately answer this question, rather than recite
the meaning of the acronym, instead, offer both definition and functional value to your answer.
Example: “DBCC is an acronym for Database Console Commands, and they are grouped in four categories:
*Maintenance commands: These commands allow a DBA to do maintenance activities on a database, such
as clean caches, shrink databases, and maintain database space. Examples of maintenance DBCC commands
include DBCCCLEANTABL, DBCCINDEXDEFRAG and DBCCSHRINKFILE.*
*Information commands: Provides information regarding the database, such as transaction logs, space
usage, and system information. Information commands include DBCCDBINFO, DBCC LOG and
DBCCDBTABLE.*
*Validation commands: These commands are used to check the consistency of the database. Commands
include DBCCCHECKDB, DBCCCHECKCATALOG and DBCCCHECKCONSTRAINTS.*
*Miscellaneous commands: These commands do not fit into the other three categories. Examples are DBCC
HELP, DBCCOUTPUTBUFFER and DBCC SHOW_STATISTICS.”*
To set up a functional backup plan, you need to decide on what recovery model you need to set for each
database. This recovery model tells SQL what data should be kept in the transaction log and for what amount
of time. The type of backups you will perform will also depend on the recovery model you have chosen, and
the type of restores that you can do.
For a DBA, recovery is an important function because sometimes data gets lost, accidental changes are made
to it or it gets deleted. To answer this question, be straightforward and detailed with your response.
*Full: This is the most complete recovery model as all database operations are fully logged to the
transaction file, which allows you to recover data to any specific point in time. You can do all kinds of
backups with this recovery model, including full, differential, partial and point-in-time recovery. With this
kind of model, however, you need to ensure that you back up the transaction log periodically, otherwise, it
will just keep growing.*
*Bulked logged: This recovery model is the same as the full recovery model, except that certain bulk
data operations, such as BULK INSERT, SELECT INTO and CREATE INDEX, are not fully logged, with
the effect that they don’t take up so much space. With this recovery model, you can still do a point-in-time
restore, as long as your last transaction log backup didn’t include a bulk operation. You can do all of the
backups with this recovery model too, and should also ensure that you prevent constant expansion of the log
file by scheduling regular backups.*
*Simple: This simple recovery model doesn’t keep log files permanently, but overwrites transactions
once they have been completed. Since the data is overwritten, you will not be able to do a point-in-time
recovery. Your latest restore point will be the latest full or differential backup that was completed. With this
recovery model, however, your transaction log will not keep growing as is the case with the previous two
models.”*
Q1: Working as a SQL Server database administrator, A SQL Server developer asked
you to allow him to view the code definition of the stored procedures in one
database. Which permission should you grant him?
View definition.
Q2: During your absence, you ask one of your colleagues to terminate a specific
session if it takes more than one hour. To which Fixed Server-Level role should you
add his account to perform that task?
Processadmin
Q3: A SQL development engineer claims that each time he tries to run a BULK
INSERT statement, the query failed with permission related error. To which Fixed
Server-Level role should you add that engineer to allow him to execute the BULK
INSERT statement?
Bulkadmin
Q4: While trying to assign tasks to the new database administration team engineers,
you ask one of the engineers to run a DBCC CHECKDB command to check the
consistency of a user database. What server scoped permissions should you grants
to that engineer in order to perform that task?
DBCreator
Q6: As a SQL Server database administrator, you are planning to perform the
multiple tasks with the minimum effort performed by your team. These tasks involve
scheduling a backup plan for all user databases, checking the databases consistency
once a week, and maintaining the indexes during the weekend. How could you
achieve that?
Q7: After creating a list of linked servers, you need to leave and ask one of your
colleagues to test and reconfigure these linked servers in case there is anything
incorrect. Which permission should you grant the engineer to perform that task?
setupadmin
Q8: You are managing the permission of the new database administration team. To
which fixed server role should you add the SQL Server database administrators in
order to be able to perform any action on the server?
sysadmin
Q9: You asked one of your colleagues from the database administration team to
execute a script that checks the blocking chain by querying a number of dynamic
management objects. Which server scoped permissions should you grant that
engineer to be able to execute this script?
Q10: Working as a SQL Server database administrator, you are planning to track and
audit all logon operations at your SQL Server. Which type of triggers can you take
advantage of to achieve that?
LOGON trigger
Note: To learn more about trends that impact Database Administration, please read this
article: 5 DBMS Trends Impacting Database Administration
Q11: Which tool can you use to check the performance-related information about
CPU times, logins and Disk I/O on your SQL Server instance?
Q12: As a SQL Server database administrator you are responsible for securing your
SQL Server environment. Part of this task, you need to choose the security protocol
that will be used to manage the security policies such as strong passwords, account
locking, and password expiration. Which authentication protocol will you use?
Kerberos Authentication protocol.
Q13: The managed codes are .NET codes that are used to write any complex
procedure or function that cannot be performed using the T-SQL language. After
building that code, which permission should be granted to that assembly in order to
allow the code to access local and network resources, registry and environment
variables?
External_Access
Q14: During the backup job configuration, it is recommended to ensure that the
backup file is valid and will be successfully restored without any errors. Which
backup option should be used to achieve that?
WITH CHECKSUM
Q15: Working as SQL Server database administrator, you are planning to recover a
user database to the Tuesday 7:15 AM point in time, before the database becomes
corrupted.
The Transaction Log backup is taken every one hour. And the last log backup file has taken at 7
AM on Tuesday.
1. Take a tail-log backup to cover the changes on Tuesday between 7 AM and 7:15 AM
2. Restore the Full backup using the NORECOVERY option
3. Restore the differential backup taken on Tuesday using the NORECOVERY option
4. Restore the Transaction Log backups starting from the file taken Tuesday 12 AM till 7 AM
and the tail log backup file, where all files will be restored with NORECOVERY except for
the last file that will be restored with RECOVERY
Q16: You are working as a SQL Server database administrator on a company. After
restarting one of the SQL Servers, the SQL service cannot be brought online as the
driver where the tempdb database is stored fails. How could you start the SQL
Server service?
Q17: You are a SQL Server database administrator in a company. One of your tasks is
adding another disk drive to your FCI for the SQL Server cluster site.
Q18: Assume that you have a data warehouse database that contains 15 large
database data files. Which Backup operation should you use to take a backup from
that database, taking into consideration that they are writing to 3 database data
files only?
Q19: While trying to take backup for a database, you need to ensure that all backup
sets will be overwritten. Which backup option should you use to achieve that?
WITH INIT
Q20: You are using the Always Encrypted technique for encryption of your critical
data and prevent the SQL Server database administrators from viewing it. Always
Encrypted supports both Deterministic and Randomized encryption types. Which
encryption option is more secure?
Randomized Encryption
Question 1 - What are 2 options to validate whether or not a backup will restore successfully?
o Restore the backup as a portion of a testing process or log shipping.
o Restore the backup with the Verify Only option.
Additional information - Verifying Backups with the RESTORE
VERIFYONLY Statement
Question 2 - How can you issue a full backup and not interrupt the LSN's?
o Issue a copy only backup.
o Additional information - COPY_ONLY Backups with SQL Server 2005
Question 1 - Name as many native SQL Server performance monitoring and tuning tools that
you know of and their associated value.
o System objects - System objects such as sp_who2, sp_lock, fn_get_sql, etc.
provide a simple means to capture basic metrics related to locking, blocking,
executing code, etc.
Additional information - SQL Server Command Line Tools To Manage
Your Server
o Profiler - In a nutshell, Profiler provides the lowest common denominator of
activity on a SQL Server instance. Profiler captures per session code with the
ability to filter the data collection based on database, login, host name,
application name, etc. in order to assess the IO, CPU usage, time needed, etc.
Additional information - SQL Server Performance Statistics Using a
Server Side Trace
o Perfmon\System Monitor - Perfmon\System Monitor is responsible for macro
level metrics related to processes and sub systems.
Additional information - Free Microsoft Tools to Help Setup and Maintain
PerfMon
o Dynamic Management Views and Functions - New to SQL Server 2005 and
beyond, the Dynamic Management Views and Functions offer a real time view
into the SQL Server sub systems.
Additional information - Dynamic Management Views and Functions in
SQL Server 2005
o TYPEPERF.EXE - TYPEPERF.EXE is a command line tool included with the
Windows operating system that writes performance data to the command
window or to a file. It is necessary to capture performance data whenever you
are trying to diagnose performance issues on a server. Performance data
provides information on the server's utilization of the processor, memory, and
disk, as well as SQL Server-specific performance data.
Additional information - How To Collect Performance Data With
TYPEPERF.EXE
o SQL Server Management Studio Built-in Performance Reports - As part of the
installation of SQL Server 2005 and beyond a number of performance-related
reports are installed. To get to these reports open the SQL Server
Management Studio (SSMS) and connect to a SQL Server instance. If you don't
have an instance of Reporting Services installed then the icon will be disabled.
Additional information
Built-In Performance Reports in SQL Server 2005
o Additional resources for this question:
Tutorial - SQL Server Performance Monitoring and Tuning
Tip Category - SQL Server Performance Tuning
Question 1 - What are the three options in SQL Server 2005 and beyond to rebuild indexes?
o CREATE INDEX with DROP_EXISTING
o DROP INDEX and CREATE INDEX
o ALTER INDEX
Additional information - Index Rebuilds in SQL Server 2000 vs SQL
Server 2005
Tip Category - SQL Server Indexing
Question 2 - What are included columns with respect to SQL Server indexing?
o A new type of index was developed in SQL Server 2005 and beyond that
assists in situations where a covering index is needed.
o Indexes with Included Columns are nonclustered 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.
o Additional information - Improve Performance with SQL Server 2005 Covering
Index Enhancements
Question 1 - Name some new features from Data Transformation Services to SQL Server
Integration Services.
o SSIS checkpoints.
o SSIS logging.
o SSIS package configurations.
o SSIS Breakpoint.
o Dynamic flat file connections.
o SSIS batch processing.
o MERGE JOIN.
o Additional information - SQL Server Integration Services
1. What is Database?
2. What is DBMS?
RDBMS stands for Relational Database Management System. The key difference
here, compared to DBMS, is that RDBMS stores data in the form of a collection of
tables, and relations can be defined between the common fields of these tables.
Most modern database management systems like MySQL, Microsoft SQL Server,
Oracle, IBM DB2, and Amazon Redshift are based on RDBMS.
4. What is SQL?
SQL stands for Structured Query Language. It is the standard language for
relational database management systems. It is especially useful in handling
organized data comprised of entities (variables) and relations between different
entities of the data.
A table is an organized collection of data stored in the form of rows and columns.
Columns can be categorized as vertical and rows as horizontal. The columns in a
table are called fields while the rows can be referred to as records.
Constraints are used to specify the rules concerning data in the table. It can be
applied for single or multiple fields in an SQL table during the creation of the table
or after creating using the ALTER TABLE command. The constraints are:
NOT NULL - Restricts NULL value from being inserted into a column.
CHECK - Verifies that all values in a field satisfy a condition.
DEFAULT - Automatically assigns a default value if no value has been specified for the
field.
UNIQUE - Ensures unique values to be inserted into the field.
INDEX - Indexes a field providing faster retrieval of records.
PRIMARY KEY - Uniquely identifies each record in a table.
FOREIGN KEY - Ensures referential integrity for a record in another table.
The PRIMARY KEY constraint uniquely identifies each row in a table. It must
contain UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is
comprised of single or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key */
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
write a sql statement to add primary key 't_id' to the table 'teachers'.
Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'.
A UNIQUE constraint ensures that all values in a column are different. This
provides uniqueness for the column(s) and helps identify each row uniquely.
Unlike primary key, there can be multiple unique constraints defined per table.
The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be
used interchangeably.
Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references 'col_pk'
in 'table_x'.
The SQL Join clause is used to combine records (rows) from two or more tables in
a SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
(INNER) JOIN: Retrieves records that have matching values in both tables involved in the
join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched
records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or
right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
A self JOIN is a case of regular join where a table is joined to itself based on some
relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN
clause and a table alias is used to assign different names to the table within the
query.
Cross join can be defined as a cartesian product of the two tables included in the
join. The table after join contains the same number of rows as in the cross-product
of the number of rows in the two tables. If a WHERE clause is used in cross join
then the query will work like an INNER JOIN.
Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from
table_1 & 'col_2' from table_2 respectively. Do not use alias.
Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively.
There are different types of indexes that can be created for different purposes:
Unique indexes are indexes that help maintain data integrity by ensuring that no
two rows of data in a table have identical key values. Once a unique index has
been defined for a table, uniqueness is enforced whenever keys are added or
changed within the index.
Non-unique indexes, on the other hand, are not used to enforce constraints on the
tables with which they are associated. Instead, non-unique indexes are used solely
to improve query performance by maintaining a sorted order of data values that
are used frequently.
Clustered indexes are indexes whose order of the rows in the database
corresponds to the order of the rows in the index. This is why only one clustered
index can exist in a given table, whereas, multiple non-clustered indexes can exist
in the table.
The only difference between clustered and non-clustered indexes is that the
database manager attempts to keep the data in the database in the same order
as the corresponding keys appear in the clustered index.
Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields
"column_1" & "column_2".
As explained above, the differences can be broken down into three small factors -
Clustered index modifies the way records are stored in a database based on the indexed
column. A non-clustered index creates a separate entity within the table which references
the original table.
Clustered index is used for easy and speedy retrieval of data from the database, whereas,
fetching records from the non-clustered index is relatively slower.
In SQL, a table can have a single clustered index whereas it can have multiple non-
clustered indexes.
Data Integrity is the assurance of accuracy and consistency of data over its entire
life-cycle and is a critical aspect of the design, implementation, and usage of any
system which stores, processes, or retrieves data. It also defines integrity
constraints to enforce business rules on the data when it is entered into an
application or a database.
Write a SQL query to select the field "app_id" in table "applications" where "app_id" less
than 1000.
Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is equal to
the above collection of "app_id".
SELECT operator in SQL is used to select data from a database. The data returned
is stored in a result table, called the result-set.
20. What are some common clauses used with SELECT query in
SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
WHERE clause in SQL is used to filter records that are necessary, based on specific
conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending
(ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used in
conjunction with some aggregation functions to produce summarized results from the
database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause.
It is different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set
obtained by the second SELECT query from the result-set obtained by the first
SELECT query and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT
statements where records from one match the other and then returns this
intersection of result-sets.
Each SELECT statement within the clause must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement should necessarily have the same order
Write a SQL query to fetch "names" that are present in either table "accounts" or in table
"registry".
Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry".
Write a SQL query to fetch "names" from table "contacts" that are neither present in
"accounts.name" nor in "registry.name".
A database cursor is a control structure that allows for the traversal of records in a
database. Cursors, in addition, facilitates processing after traversal, such as
retrieval, addition, and deletion of database records. They can be viewed as a
pointer to one row in a set of rows.
1. DECLARE a cursor after any variable declaration. The cursor declaration must
always be associated with a SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before
fetching rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release
the associated resources.
Entity: An entity can be a real-world object, either tangible or intangible, that can
be easily identifiable. For example, in a college database, students, professors,
workers, departments, and projects can be referred to as entities. Each entity has
some associated properties that provide it an identity.
One-to-One - This can be defined as the relationship between two tables where each
record in one table is associated with the maximum of one record in the other table.
One-to-Many & Many-to-One - This is the most commonly used relationship where a
record in a table is associated with multiple records in the other table.
Many-to-Many - This is used in cases when multiple instances on both sides are needed
for defining a relationship.
Self-Referencing Relationships - This is used when a table needs to define a
relationship with itself.
An alias is represented explicitly by the AS keyword but in some cases, the same
can be performed without it as well. Nevertheless, using the AS keyword is always
a good practice.
Write an SQL statement to select all from table "Limited" with alias "Ltd".
Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:
Students Table
Studen Salutati
Address Books Issued
t on
Amanora Park Town Until the Day I Die (Emily Carpenter), Inception
Sara Ms.
94 (Christopher Nolan)
Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho), Inferno (Dan Brown) Mr.
As we can observe, the Books Issued field has more than one value per record,
and to convert it into 1NF, this has to be resolved into separate individual records
for each book issued. Check the following table in 1NF form -
Studen Salutati
Address Books Issued
t on
A relation is in second normal form if it satisfies the conditions for the first normal
form and does not contain any partial dependency. A relation in 2NF has no
partial dependency, i.e., it has no non-prime attribute that depends on any
proper subset of any candidate key of the table. Often, specifying a single column
Primary Key is the solution to the problem. Examples -
Example 1 - Consider the above example. As we can observe, the Students Table
in the 1NF form has a candidate key in the form of [Student, Address] that can
uniquely identify all records in the table. The field Books Issued (non-prime
attribute) depends partially on the Student field. Hence, the table is not in 2NF. To
convert it into the 2nd Normal Form, we will partition the tables into two while
specifying a new Primary Key attribute to identify the individual records in the
Students table. The Foreign Key constraint will be set on the other table to
ensure referential integrity.
Here, WX is the only candidate key and there is no partial dependency, i.e., any
proper subset of WX doesn’t determine any non-prime attribute in the relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the
second normal form and there is no transitive dependency between the non-
prime attributes, i.e., all non-prime attributes are determined only by the
candidate keys of the relation and not by any other non-prime attribute.
94
Student_I
Book Issued
D
Salutation_ Salutati
ID on
1 Ms.
2 Mr.
3 Mrs.
For the above relation to exist in 3NF, all possible candidate keys in the above
relation should be {P, RS, QR, T}.
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal
form and for every functional dependency, Left-Hand-Side is super key. In other
words, a relation in BCNF has non-trivial functional dependencies in form X –> Y,
such that X is always a super key. For example - In the above example, Student_ID
serves as the sole unique identifier for the Students Table and Salutation_ID for
the Salutations Table, thus these tables exist in BCNF. The same cannot be said
for the Books Table and there can be several books with common Book Names
and the same Student_ID.
TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
DROP command is used to remove an object from the database. If you drop a
table, all the rows in the table are deleted and the table structure is removed from
the database.
Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'.
Write a SQL statement to delete the table 'Temporary' while keeping its relations intact.
If a table is dropped, all things associated with the tables are dropped as well. This
includes - the relationships defined on the table with other tables, the integrity
checks and constraints, access privileges and other grants that the table has. To
create and use the table again in its original form, all these relations, checks,
constraints, privileges and relationships need to be redefined. However, if a table
is truncated, none of the above problems exist and the table retains its original
structure.
The TRUNCATE command is used to delete all the rows from the table and free
the space containing the table.
The DELETE command deletes only the rows from the table based on the
condition given in the where clause or deletes all the rows from the table if no
condition is specified. But it does not free the space containing the table.
Note: All aggregate functions described above ignore NULL values except for the
COUNT function.
A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:
The user-defined functions in SQL are like functions in any other programming
language that accept parameters, perform complex calculations, and return a
value. They are written to use the logic repetitively whenever required. There are
two types of SQL user-defined functions:
Scalar Function: As explained earlier, user-defined scalar functions return a single scalar
value.
Table-Valued Functions: User-defined table-valued functions return a table as output.
o Inline: returns a table data type based on a single SELECT statement.
o Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT
statements can be used inside the function body.
Collation refers to a set of rules that determine how data is sorted and compared.
Rules defining the correct character sequence are used to sort the character data.
It incorporates options for specifying case sensitivity, accent marks, kana
character types, and character width. Below are the different types of collation
sensitivity:
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
A stored procedure that calls itself until a boundary condition is reached, is called
a recursive stored procedure. This recursive function helps the programmers to
deploy the same set of code several times as and when required. Some SQL
programming languages limit the recursion depth to prevent an infinite loop of
procedure calls from causing a stack overflow, which slows down the system and
may lead to system crashes.
Creating empty tables with the same structure can be done smartly by fetching
the records of one table into a new table using the INTO operator while fixing a
WHERE clause to be false for all records. Hence, SQL prepares the new table with
a duplicate structure to accept the fetched records but since no records get
fetched due to the WHERE clause in action, nothing is inserted into the new table.
SQL pattern matching provides for pattern search in data if you have no clue as to
what that word should be. This kind of SQL query uses wildcards to match a string
pattern, rather than writing the exact word. The LIKE operator is used in
conjunction with SQL Wildcards to fetch the required information.
The % wildcard matches zero or more characters of any type and can be used to
define wildcards both before and after the pattern. Search a student in your
database with first name beginning with the letter K:
SELECT *
FROM students
WHERE first_name LIKE 'K%'
Use the NOT keyword to select records that don't match the pattern. This query
returns all students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
The _ wildcard matches exactly one character of any type. It can be used in
conjunction with % wildcard. This query fetches all students with letter K at the
third position in their first name.
SELECT *
FROM students
WHERE first_name LIKE '__K%'
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
SQL is a language for the database. It has a vast scope and robust capability of
creating and manipulating a variety of database objects using commands like
CREATE, ALTER, DROP, etc, and also in loading the database objects using
commands like INSERT. It also provides options for Data Manipulation using
commands like DELETE, TRUNCATE and also does effective retrieval of data using
cursor commands like FETCH, SELECT, etc. There are many such commands which
provide a large amount of control to the programmer to interact with the database
in an efficient way without wasting many resources. The popularity of SQL has
grown so much that almost every programmer relies on this to implement their
application's storage functionalities thereby making it an exciting language to
learn. Learning this provides the developer a benefit of understanding the data
structures used for storing the organization's data and giving an additional level of
control and in-depth understanding of the application.
Q #27) What is the difference between a Local and a Global temporary table?
Answer: If defined inside a compound statement a local temporary table exists only for the duration
of that statement but a global temporary table exists permanently in the database but its rows
disappear when the connection is closed.
Q #28) What is the SQL Profiler?
Answer: SQL Profiler provides a graphical representation of events in an instance of SQL Server
for monitoring and investment purpose. We can capture and save the data for further analysis. We
can put filters as well to captures the specific data we want.
Q #29) What do you mean by authentication modes in SQL Server?
Answer: There are two authentication modes in SQL Server.
Windows mode
Mixed Mode – SQL and Windows.
Q #30) How can we check the SQL Server version?
Answer: By running the following command:
SELECT @@Version
Q #31) Is it possible to call a stored procedure within a stored procedure?
Answer: Yes, we can call a stored procedure within a stored procedure. It is called the recursion
property of the SQL server and these types of stored procedures are called nested stored
procedures.
Q #32) What is the SQL Server Agent?
Answer: SQL Server agent allows us to schedule the jobs and scripts. It helps in implementing the
day to day DBA tasks by automatically executing them on a scheduled basis.
Q #33) What is the PRIMARY KEY?
Answer: The primary key is a column whose values uniquely identify every row in a table. Primary
key values can never be reused.
Q #34) What is a UNIQUE KEY constraint?
Answer: A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no
duplicate values are entered. The unique key constraints are used to enforce entity integrity as the
primary key constraints.
Q #35) What is FOREIGN KEY
Answer: When a one table’s primary key field is added to related tables to create the common field
which relates the two tables, it called a foreign key in other tables.
Foreign Key constraints enforce referential integrity.
Q #48) Where SQL server usernames and passwords are stored in a SQL server?
Answer: They get stored in System Catalog Views sys.server_principals and sys.sql_logins.
Q #49) What are the properties of a transaction?
Answer: Generally, these properties are referred to as ACID properties.
They are:
Atomicity
Consistency
Isolation
Durability
Q #50) Define UNION, UNION ALL, MINUS, INTERSECT?
Answer:
UNION – returns all distinct rows selected by either query.
UNION ALL – returns all rows selected by either query, including all duplicates.
MINUS – returns all distinct rows selected by the first query but not by the second.
INTERSECT – returns all distinct rows selected by both queries.
Q #51) What is SQL Server used for?
Answer: SQL Server is one of the very popular Relational Database Management Systems. This is
a product from Microsoft to store and manage the information in the database.
Q #52) Which language is supported by SQL Server?
Answer: SQL Server is based upon the implementation of the SQL also known as Structured
Query Language to work with the data inside the database.
Q #53) Which is the latest version of SQL Server and when it is released?
Answer: SQL Server 2019 is the latest version of SQL Server that is available in the market and
Microsoft launched this on November 4th, 2019 with the support of the Linux O/S.
Q #54) What are the various editions of SQL Server 2019 that are available in the market?
Answer: 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.
Q #55) What are functions in the SQL Server?
Answer: Functions are the sequence of the statements which accept inputs, process the inputs to
perform some specific task and then provide the outputs. Functions should have some meaningful
name but these should not start with a special character such as %,#,@, etc.
Q #56) What is a User-Defined function in the SQL Server and what is its advantage?
Answer: User-Defined Function is a function that can be written as per the needs of the user by
implementing your logic. The biggest advantage of this function is that the user is not limited to pre-
defined functions and can simplify the complex code of pre-defined function by writing a simple
code as per the requirement.
This returns Scalar value or a table.
Q #57) Explain the creation and execution of a user-defined function in the SQL Server?
Answer: A User-Defined function can be created in the following way:
CREATE Function fun1(@num int)
returns table
as
So, in the above case, a function with the name of ‘fun1’ is created to fetch employee details of an
employee having empid=12.
Q #64) What are the different types of Columns Types Constraints in the SQL Server?
Answer: SQL Server provides 6 types of Constraints. These are as follows:
1. Not Null Constraint: This puts a constraint that the value of a column cannot be null.
2. Check Constraint: This puts a constraint by checking some particular condition before
inserting data in the table.
3. Default Constraint: This constraint provides some default value that can be inserted in the
column if no value is specified for that column.
4. 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.
5. 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.
6. 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.
Q #65) What command is used to delete a table from the database in the SQL Server and
how?
Answer: DELETE Command is used to delete any table from the database in the SQL Server.
Syntax: DELETE Name of the table
Example: If the name of a table is “employee” then DELETE command to delete this table can be
written as
DELETE employee;
Q #67) What command is used to create a database in the SQL Server and how?
Answer: CREATEDATABASE Command is used to create any database in the SQL Server.
Syntax: CREATEDATABASE Name of the Database
Example: If the name of a database is “employee” then create command to create this database
that can be written as CREATEDATABASE employee.
Q #68) What function does a database engine serve in the SQL Server?
Answer: Database Engine is a type of service in the SQL Server which starts as soon as the
Operating System starts. This may run by default depending upon the settings in the O/S.
Q #69) What are the advantages of having an index on the SQL Server?
Answer: The index has the following advantages:
Index supports the mechanism of having faster data retrieval from the database.
This forms a data structure in a way that helps in minimizing data comparisons.
This improves the performance of the retrieval of the data from the database.
Conclusion
This is all about SQL Server interview questions. I hope this article must have provided insight
regarding the questions that can be asked in an interview and you can now confidently handle your
interview process.
Practice all the important SQL Server topics for better understanding and appearing for the
interview confidently.
Happy Learning!!
Q1. What is the difference between SQL and MySQL?
SQL vs MySQL
SQL MySQL
SQL is the core of the relational database which is MySQL is an RDMS (Relational Database
used for accessing and managing database Management System) such as SQL Server,
Informix etc.
Q2. What are the different subsets of SQL?
Data Definition Language (DDL) – It allows you to perform various operations on the database
such as CREATE, ALTER, and DELETE objects.
Data Manipulation Language(DML) – It allows you to access and manipulate data. It helps you to
insert, update, delete and retrieve data from the database.
Data Control Language(DCL) – It allows you to control access to the database. Example – Grant,
Revoke access permissions.
Q3. What do you mean by DBMS? What are its different types?
A DBMS allows a user to interact with the database. The data stored in the database can be
modified, retrieved and deleted and can be of any type like strings, numbers, images, etc.
There are two types of DBMS:
Relational Database Management System: The data is stored in relations (tables). Example –
MySQL.
Non-Relational Database Management System: There is no concept of relations, tuples and
attributes. Example – MongoDB
A relational database management system (RDBMS) is a set of applications and features that
allow IT professionals and others to develop, edit, administer, and interact with relational
databases. Most commercial relational database management systems use Structured Query
Language (SQL) to access the database, which is stored in the form of tables.
The RDBMS is the most widely used database system in businesses all over the world. It offers
a stable means of storing and retrieving massive amounts of data.
Databases, in general, hold collections of data that may be accessed and used in other
applications. The development, administration, and use of database platforms are all supported
by a database management system.
The following are some further distinctions between database management systems and
relational database management systems:
A self-join is a type of join that can be used to connect two tables. As a result, it is a unary
relationship. Each row of the table is attached to itself and all other rows of the same table in a
self-join. As a result, a self-join is mostly used to combine and compare rows from the same
database table.
A SELECT command gets zero or more rows from one or more database tables or views. The
most frequent data manipulation language (DML) command is SELECT in most applications.
SELECT queries define a result set, but not how to calculate it, because SQL is a declarative
programming language.
Q7. What are some common clauses used with SELECT query in SQL?
The following are some frequent SQL clauses used in conjunction with a SELECT query:
WHERE clause: In SQL, the WHERE clause is used to filter records that are required
depending on certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or
descending (DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and
may be used with aggregation methods to obtain summarised database results.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator is used to combine the results of two tables while also removing duplicate
entries.
The MINUS operator is used to return rows from the first query but not from the second query.
The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –
Within the clause, each SELECT query must have the same amount of columns.
The data types in the columns must also be comparable.
In each SELECT statement, the columns must be in the same order.
After any variable declaration, DECLARE a cursor. A SELECT Statement must always be
coupled with the cursor definition.
To start the result set, move the cursor over it. Before obtaining rows from the result set, the
OPEN statement must be executed.
To retrieve and go to the next row in the result set, use the FETCH command.
Finally, use the DEALLOCATE command to remove the cursor definition and free up the
resources connected with it.
One-to-One – This is a connection between two tables in which each record in one table
corresponds to the maximum of one record in the other.
One-to-Many and Many-to-One – This is the most frequent connection, in which a record in
one table is linked to several records in another.
Many-to-Many – This is used when defining a relationship that requires several instances on
each sides.
Self-Referencing Relationships – When a table has to declare a connection with itself, this is
the method to employ.
OLTP, or online transactional processing, allows huge groups of people to execute massive
amounts of database transactions in real time, usually via the internet. A database transaction
occurs when data in a database is changed, inserted, deleted, or queried.
OLTP stands for online transaction processing, whereas OLAP stands for online analytical
processing. OLTP is an online database modification system, whereas OLAP is an online
database query response system.
Q14. How to create empty tables with the same structure as another table?
SQL Comments are used to clarify portions of SQL statements and to prevent SQL statements
from being executed. Comments are quite important in many programming languages. The
comments are not supported by a Microsoft Access database. As a result, the Microsoft Access
database is used in the examples in Mozilla Firefox and Microsoft Edge.
Single Line Comments: It starts with two consecutive hyphens (–).
Multi-line Comments: It starts with /* and ends with */.
You may use the NVL function to replace null values with a default value. The function returns
the value of the second parameter if the first parameter is null. If the first parameter is anything
other than null, it is left alone.
This function is used in Oracle, not in SQL and MySQL. Instead of NVL() function, MySQL have
IFNULL() and SQL Server have ISNULL() function.
Change, extract, and edit the character string using character manipulation routines. The
function will do its action on the input strings and return the result when one or more characters
and words are supplied into it.
A) CONCAT (joining two or more values): This function is used to join two or more values
together. The second string is always appended to the end of the first string.
B) SUBSTR: This function returns a segment of a string from a given start point to a given
endpoint.
C) LENGTH: This function returns the length of the string in numerical form, including blank
spaces.
D) INSTR: This function calculates the precise numeric location of a character or word in a
string.
E) LPAD: For right-justified values, it returns the padding of the left-side character value.
F) RPAD: For a left-justified value, it returns the padding of the right-side character value.
G) TRIM: This function removes all defined characters from the beginning, end, or both ends of
a string. It also reduced the amount of wasted space.
H) REPLACE: This function replaces all instances of a word or a section of a string (substring)
with the other string value specified.
Q19. Write the SQL query to get the third maximum salary of an employee from
a table named employees.
Employee table
employee_name salary
A 24000
C 34000
D 55000
E 75000
F 21000
G 40000
H 50000
SELECT * FROM(
WHERE r=&n;
The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the
provided column value, with no gaps. It always indicates a ranking in order of precedence. This
function will assign the same rank to the two rows if they have the same rank, with the next rank
being the next consecutive number. If we have three records at rank 4, for example, the next
level indicated is 5.
A table is made up of numerous records (rows), each of which can be split down into smaller
units called Fields(columns). ID, Name, Department, and Salary are the four fields in the
Employee table above.
The UNIQUE Constraint prevents identical values in a column from appearing in two records.
The UNIQUE constraint guarantees that every value in a column is unique.
A self-join is a type of join that can be used to connect two tables. As a result, it is a unary
relationship. Each row of the table is attached to itself and all other rows of the same table in a
self-join. As a result, a self-join is mostly used to combine and compare rows from the same
database table.
Q25. What are some common clauses used with SELECT query in SQL?
The following are some frequent SQL clauses used in conjunction with a SELECT query:
WHERE clause: In SQL, the WHERE clause is used to filter records that are required
depending on certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or
descending (DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and
may be used with aggregation methods to obtain summarised database results.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator is used to combine the results of two tables while also removing
duplicate entries.
The MINUS operator is used to return rows from the first query but not from the second query.
The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –
Within the clause, each SELECT query must have the same amount of columns.
After any variable declaration, DECLARE a cursor. A SELECT Statement must always be
coupled with the cursor definition.
To start the result set, move the cursor over it. Before obtaining rows from the result set, the
OPEN statement must be executed.
To retrieve and go to the next row in the result set, use the FETCH command.
SQL is a database query language that allows you to edit, remove, and request data from
databases. The following statements are a few examples of SQL statements:
SELECT
INSERT
UPDATE
DELETE
CREATE DATABASE
ALTER DATABASE
SQL skills aid data analysts in the creation, maintenance, and retrieval of data from relational
databases, which divide data into columns and rows. It also enables users to efficiently retrieve,
update, manipulate, insert, and alter data.
The most fundamental abilities that a SQL expert should possess are:
1. Database Management
2. Structuring a Database
3. Creating SQL clauses and statements
4. SQL System SKills like MYSQL, PostgreSQL
5. PHP expertise is useful.
6. Analyze SQL data
7. Using WAMP with SQL to create a database
8. OLAP Skills
Schemas come in a variety of shapes and sizes. Star schema and Snowflake
schema are two of the most popular. The entities in a star schema are represented in
a star form, whereas those in a snowflake schema are shown in a snowflake shape.
Any database architecture is built on the foundation of schemas.
Temporary tables are created in TempDB and are erased automatically after the last
connection is closed. We may use Temporary Tables to store and process interim results.
When we need to store temporary data, temporary tables come in handy.
Step 1: Click on SSMS, which will take you to the SQL Server Management Studio page.
Step 2: Moreover, click on the SQL Server Management Studio link and tap on Save File.
Step 3: Save this file to your local drive and go to the folder.
Step 4: The setup window will appear, and here you can choose the location where you want to
save the file.
Step 5: Click on Install.
Step 6: Close the window after the installation is complete.
Step 7: Furthermore, go back to your Start Menu and search for SQL server management
studio.
Step 8: Furthermore, double-click on it, and the login page will appear once it shows up.
Step 9: You should be able to see your server name. However, if that’s not visible, click on the
drop-down arrow on the server and tap on Browse.
After that, the SQL server will connect, and Windows 11 will run good.
Q34. What is the case when in SQL Server?
The CASE statement is used to construct logic in which one column’s value is determined by
the values of other columns.
At least one set of WHEN and THEN commands makes up the SQL Server CASE Statement.
The condition to be tested is specified by the WHEN statement. If the WHEN condition returns
TRUE, the THEN sentence explains what to do.
When none of the WHEN conditions return true, the ELSE statement is executed. The END
keyword brings the CASE statement to a close.
1 CASE
5 ELSE result
END;
6
In summary, the following are the five major distinctions between SQL and NoSQL:
SQL databases have a specified schema and employ structured query language. For
unstructured data, NoSQL databases use dynamic schemas.
NoSQL databases are document, key-value, graph, or wide-column stores, whereas SQL
databases are table-based.
SQL databases excel in multi-row transactions, while NoSQL excels at unstructured data such
as documents and JSON.
BLOB stands for Binary Huge Objects and can be used to store binary data, whereas TEXT
may be used to store a large number of strings. BLOB may be used to store binary data, which
includes images, movies, audio, and applications.
BLOB values function similarly to byte strings, and they lack a character set. As a result, bytes’
numeric values are completely dependent on comparison and sorting.
TEXT values behave similarly to a character string or a non-binary string. The
comparison/sorting of TEXT is completely dependent on the character set collection.
If the SQL table has duplicate rows, the duplicate rows must be removed.
ID Name Age
1 A 21
2 B 23
2 B 23
4 D 22
5 E 25
6 G 26
5 E 25
The following SQL query removes the duplicate ids from the table:
A stored procedure is a piece of prepared SQL code that you can save and reuse again and
over.
So, if you have a SQL query that you create frequently, save it as a stored procedure and then
call it to run it.
You may also supply parameters to a stored procedure so that it can act based on the value(s)
of the parameter(s) given.
AS
sql_statement
GO;
EXEC procedure_name;
Black Box Testing is a software testing approach that involves testing the functions of software
applications without knowing the internal code structure, implementation details, or internal
routes. Black Box Testing is a type of software testing that focuses on the input and output of
software applications and is totally driven by software requirements and specifications.
Behavioral testing is another name for it.
Databases Training
5(8617)
MYSQL DBA CERTIFICATION TRAINING
MySQL DBA Certification Training
Reviews
5(5223)
4(15716)
5(12545)
5(2669)
5(902)
Next
SQL Sandbox is a secure environment within SQL Server where untrusted programmes can be
run. There are three different types of SQL sandboxes:
Safe Access Sandbox: In this environment, a user may execute SQL activities like as building
stored procedures, triggers, and so on, but they can’t access the memory or create files.
Sandbox for External Access: Users can access files without having the ability to alter memory
allocation.
Unsafe Access Sandbox: This contains untrustworthy code that allows a user to access
memory.
Prior to the introduction of MySQL 5.5 in December 2009, MyISAM was the default storage
engine for MySQL relational database management system versions. It’s based on the older
ISAM code, but it comes with a lot of extra features. Each MyISAM table is split into three files
on disc (if it is not partitioned). The file names start with the table name and end with an
extension that indicates the file type. The table definition is stored in a.frm file, however this file
is not part of the MyISAM engine; instead, it is part of the server. The data file’s suffix is.MYD
(MYData). The index file’s extension is.MYI (MYIndex). If you lose your index file, you may
always restore it by recreating indexes.
employee_name salary
A 24000
C 34000
D 55000
E 75000
F 21000
G 40000
H 50000
SELECT * FROM(
SELECT employee_name, salary, DENSE_RANK()
WHERE r=&n;
A table refers to a collection of data in an organised manner in form of rows and columns. A
field refers to the number of columns in a table. For example:
Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them. It is used to merge two tables or retrieve data from there. There are 4 types of
joins, as you can refer to below:
Inner join: Inner Join in SQL is the most common type of join. It is used to return all the rows
from multiple tables where the join condition is satisfied.
Left Join: Left Join in SQL is used to return all the rows from the left table but only the
matching rows from the right table where the join condition is fulfilled.
Right Join: Right Join in SQL is used to return all the rows from the right table but only
the matching rows from the left table where the join condition is fulfilled.
Full Join: Full join returns all the records when there is a match in any of the tables.
Therefore, it returns all the rows from the left-hand side table and all the rows from the
right-hand side table.
Q46. What is the difference between CHAR and VARCHAR2 datatype in SQL?
Both Char and Varchar2 are used for characters datatype but varchar2 is used for character
strings of variable length whereas Char is used for strings of fixed length. For example, char(10)
can only store 10 characters and will not be able to store a string of any other length whereas
varchar2(10) can store any length i.e 6,8,2 in this variable.
Constraints in SQL are used to specify the limit on the data type of the table. It can be specified
while creating or altering the table statement. The sample of constraints are:
NOT NULL
CHECK
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
DELETE vs TRUNCATE
DELETE TRUNCATE
You can rollback data after using delete statement. You cannot rollback data.
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
Foreign key maintains referential integrity by enforcing a link between the data in two tables.
The foreign key in the child table references the primary key in the parent table.
The foreign key constraint prevents actions that would destroy links between the child and parent
tables.
Data Integrity defines the accuracy as well as the consistency of the data stored in a database.
It also defines integrity constraints to enforce business rules on the data when it is entered into
an application or a database.
The differences between the clustered and non clustered index in SQL are :
1. Clustered index is used for easy retrieval of data from the database and its faster whereas
reading from non clustered index is relatively slower.
2. Clustered index alters the way records are stored in a database as it sorts out rows by the
column which is set to be clustered index whereas in a non clustered index, it does not alter the
way it was stored but it creates a separate object within a table which points back to the original
table rows after searching.
3. One table can only have one clustered index whereas it can have many non clustered
index.
Q54. Write a SQL query to display the current date?
In SQL, there is a built-in function called GetDate() which helps to return the current
timestamp/date.
The phase that identifies a plan for evaluation query which has the least estimated cost is
known as query optimization.
Denormalization refers to a technique which is used to access data from higher to lower forms
of a database. It helps the database managers to increase the performance of the entire
infrastructure as it introduces redundancy into a table. It adds the redundant data into a table by
incorporating database queries that combine data from various tables into a single table.
Entities: A person, place, or thing in the real world about which data can be stored in a
database. Tables store data that represents one type of entity. For example – A bank database
has a customer table to store customer information. The customer table stores this information
as a set of attributes (columns within the table) for each customer.
Relationships: Relation or links between entities that have something to do with each other.
For example – The customer name is related to the customer account number and contact
information, which might be in the same table. There can also be relationships between
separate tables (for example, customer to accounts).
An index refers to a performance tuning method of allowing faster retrieval of records from the
table. An index creates an entry for each value and hence it will be faster to retrieve data.
Unique Index:
This index does not allow the field to have duplicate values if the column is unique indexed. If a
primary key is defined, a unique index can be applied automatically.
Clustered Index:
This index reorders the physical order of the table and searches based on the basis of key
values. Each table can only have one clustered index.
Non-Clustered Index:
Non-Clustered Index does not alter the physical order of the table and maintains a logical order
of the data. Each table can have many nonclustered indexes.
Normalization in SQL is the process of organizing data to avoid duplication and redundancy.
Some of the advantages are:
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
DROP command removes a table and it cannot be rolled back from the database whereas
TRUNCATE command removes all the rows from the table.
There are many successive levels of normalization. These are called normal forms. Each
consecutive normal form depends on the previous one.The first three normal forms are usually
adequate.
Normal Forms are used in database tables to remove or decrease duplication. The following
are the many forms:
A relation is in second normal form if it meets the first normal form’s requirements and does not
contain any partial dependencies. In 2NF, a relation has no partial dependence, which means it
has no non-prime attribute that is dependent on any suitable subset of any table candidate key.
Often, the problem may be solved by setting a single column Primary Key.
OLTP, or online transactional processing, allows huge groups of people to execute massive
amounts of database transactions in real time, usually via the internet. A database transaction
occurs when data in a database is changed, inserted, deleted, or queried.
OLTP stands for online transaction processing, whereas OLAP stands for online analytical
processing. OLTP is an online database modification system, whereas OLAP is an online
database query response system.
Q64. How to create empty tables with the same structure as another table?
Using the INTO operator to fetch the records of one table into a new table while setting a
WHERE clause to false for all entries, it is possible to create empty tables with the same
structure. As a result, SQL creates a new table with a duplicate structure to accept the fetched
entries, but nothing is stored into the new table since the WHERE clause is active.
In 1986, a team lead by Computer Science Professor Michael Stonebraker created PostgreSQL
under the name Postgres. It was created to aid developers in the development of enterprise-
level applications by ensuring data integrity and fault tolerance in systems. PostgreSQL is an
enterprise-level, versatile, resilient, open-source, object-relational database management
system that supports variable workloads and concurrent users. The international developer
community has constantly backed it. PostgreSQL has achieved significant appeal among
developers because to its fault-tolerant characteristics.
It’s a very reliable database management system, with more than two decades of community
work to thank for its high levels of resiliency, integrity, and accuracy. Many online, mobile,
geospatial, and analytics applications utilise PostgreSQL as their primary data storage or data
warehouse.
Q67. What is the difference between the RANK() and DENSE_RANK() functions?
The RANK() function in the result set defines the rank of each row within your ordered partition.
If both rows have the same rank, the next number in the ranking will be the previous rank plus a
number of duplicates. If we have three records at rank 4, for example, the next level indicated is
7.
The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the
provided column value, with no gaps. It always indicates a ranking in order of precedence. This
function will assign the same rank to the two rows if they have the same rank, with the next rank
being the next consecutive number. If we have three records at rank 4, for example, the next
level indicated is 5.
SQL injection is a sort of flaw in website and web app code that allows attackers to take control
of back-end processes and access, retrieve, and delete sensitive data stored in databases. In
this approach, malicious SQL statements are entered into a database entry field, and the
database becomes exposed to an attacker once they are executed. By utilising data-driven
apps, this strategy is widely utilised to get access to sensitive data and execute administrative
tasks on databases. SQLi attack is another name for it.
Getting access to secret data in order to change a SQL query to acquire the desired results.
UNION attacks are designed to steal data from several database tables.
Examine the database to get information about the database’s version and structure
SQL aggregate functions provide information about a database’s data. AVG, for example,
returns the average of a database column’s values.
SQL provides seven (7) aggregate functions, which are given below:
Q70. What is the default ordering of data using the ORDER BY clause? How could it be
changed?
The ORDER BY clause in MySQL can be used without the ASC or DESC modifiers. The sort
order is preset to ASC or ascending order when this attribute is absent from the ORDER BY
clause.
The SQL DISTINCT keyword is combined with the SELECT query to remove all duplicate
records and return only unique records. There may be times when a table has several duplicate
records.
The DISTINCT clause in SQL is used to eliminate duplicates from a SELECT statement’s result
set.
Q72. What are the syntax and use of the COALESCE function?
From a succession of expressions, the COALESCE function returns the first non-NULL value.
The expressions are evaluated in the order that they are supplied, and the function’s result is
the first non-null value. Only if all of the inputs are null does the COALESCE method return
NULL.
ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data
transactions are processed reliably in a database system.
Atomicity: Atomicity refers to the transactions that are completely done or failed where
transaction refers to a single logical operation of a data. It means if one part of any transaction
fails, the entire transaction fails and the database state is left unchanged.
Consistency: Consistency ensures that the data must meet all the validation rules. In simple
words, you can say that your transaction never leaves the database without completing its state.
Isolation: The main goal of isolation is concurrency control.
Durability: Durability means that if a transaction has been committed, it will occur whatever may
come in between such as power loss, crash or any sort of error.
Want to upskill yourself to get ahead in your career? Check out this video in this SQL Interview
Questions
Trigger in SQL is are a special type of stored procedures that are defined to execute
automatically in place or after data modifications. It allows you to execute a batch of code when
an insert, update or any other query is executed against a specific table.
1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
A NULL value is not at all same as that of zero or a blank space. NULL value represents a
value which is unavailable, unknown, assigned or not applicable whereas a zero is a number
and blank space is a character.
Q77. What is the difference between cross join and natural join?
The cross join produces the cross product or Cartesian product of two tables whereas the
natural join is based on all the columns having the same name and data types in both the
tables.
Correlated subquery: These are queries which select the data from a table referenced in the
outer query. It is not considered as an independent query as it refers to another table and refers
the column in a table.
Non-Correlated subquery: This query is an independent query where the output of subquery
is substituted in the main query.
To count the number of records in a table in SQL, you can use the below commands:
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
Q81. Write a SQL query to find the names of employees that begin
with ‘A’?
To display name of the employees that begin with ‘A’, type in the below command:
2 FROM(
Group functions work on the set of rows and return one result per group. Some of the
commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.
Relation or links are between entities that have something to do with each other. Relationships
are defined as the connection between the tables in a database. There are various
relationships, namely:
Q85. How can you insert NULL values in a column while inserting
the data?
BETWEEN operator is used to display rows based on a range of values in a row whereas the
IN condition operator is used to check for values contained in a specific set of values.
Example of BETWEEN:
This statement allows conditional update or insertion of data into a table. It performs an
UPDATE if a row exists, or an INSERT if the row does not exist.
Recursive stored procedure refers to a stored procedure which calls by itself until it reaches
some boundary condition. This recursive function or procedure helps the programmers to use
the same set of code n number of times.
SQL clause helps to limit the result set by providing a condition to the query. A clause helps to
filter the rows from the entire set of records.
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on
this technology, you can opt for a structured training from edureka! Click below to know more.
HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY
clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is
applied to each row before they are a part of the GROUP BY function in a query.
Constraints are the representation of a column to enforce data entity and consistency. There
are two levels of a constraint, namely:
You can fetch common records from two tables using INTERSECT. For example:
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
LOWER: This function returns the string in lowercase. It takes a string as an argument and
returns it by converting it into lower case. Syntax:
LOWER(‘string’)
UPPER: This function returns the string in uppercase. It takes a string as an argument and
returns it by converting it into uppercase. Syntax:
UPPER(‘string’)
INITCAP: This function returns the string with the first letter in uppercase and rest of the letters in
lowercase. Syntax:
INITCAP(‘string’)
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on
this technology, you can opt for a structured training from edureka! Click below to know more.
Some of the available set operators are – Union, Intersect or Minus operators.
ALIAS command in SQL is the name that can be given to any table or a column. This alias
name can be referred in WHERE clause to identify a particular table or a column.
For example-
Scalar functions return a single value based on the input value. For example – UCASE(),
NOW() are calculated with respect to string.
You can fetch alternate records i.e both odd and even row numbers. For example- To display
even numbers, use the following command:
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
You can select unique records from a table by using the DISTINCT keyword.
There are a lot of ways to fetch characters from a string. For example:
SQL is a query language that allows you to issue a single query or execute a single
insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows
you to write a full program (loops, variables, etc.) to accomplish multiple operations such as
selects/inserts/updates/deletes.
A view is a virtual table which consists of a subset of data contained in a table. Since views are
not present, it takes less space to store. View can have data of one or more tables combined
and it depends on the relationship.
A view refers to a logical snapshot based on a table or another view. It is used for the following
reasons:
A Stored Procedure is a function which consists of many SQL statements to access the
database system. Several SQL statements are consolidated into a stored procedure and
execute them whenever and wherever required which saves time and avoid writing code again
and again.
Advantages:
A Stored Procedure can be used as a modular programming which means create once, store
and call for several times whenever it is required. This supports faster execution. It also reduces
network traffic and provides better security to the data.
Disadvantage:
The only disadvantage of Stored Procedure is that it can be executed only in the database and
utilizes more memory in the database server.
Scalar Functions
Inline Table-valued functions
Multi-statement valued functions
Scalar returns the unit, variant defined the return clause. Other two types of defined functions
return table.
Collation is defined as a set of rules that determine how data can be sorted as well as
compared. Character data is sorted using the rules that define the correct character sequence
along with options for specifying case-sensitivity, character width etc.
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on
this technology, you can opt for structured training from edureka!
Local variables:
These variables can be used or exist only inside the function. These variables are not used or
referred by any other function.
Global variables:
These variables are the variables which can be accessed throughout the program. Global
variables cannot be created whenever that function is called.
Autoincrement keyword allows the user to create a unique number to get generated whenever a
new record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY in SQL is used.
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in
SQL SERVER.
Datawarehouse refers to a central repository of data where the data is assembled from multiple
sources of information. Those data are consolidated, transformed and made available for the
mining as well as online processing. Warehouse data also have a subset of data called Data
Marts.
Windows mode and Mixed Mode – SQL and Windows. You can go to the below steps to
change authentication mode in SQL Server:
Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL
Enterprise Manager from the Microsoft SQL Server program group.
Then select the server from the Tools menu.
Select SQL Server Configuration Properties, and choose the Security page.
STUFF Function: This function is used to overwrite existing character or inserts a string into another
string. Syntax:
replacement_string: They are the new characters which are injected in the string.
REPLACE function: This function is used to replace the existing characters of all the occurrences.
Syntax:
So this brings us to the end of the SQL interview questions blog. I hope this set of SQL
Interview Questions will help you ace your job interview. All the best for your interview!
Q1. Mention the differences between SQL Server and MySQL.
SQL Server MySQL
The main components of the SQL Server Agent are Jobs, Schedules, Operators, and Alerts.
Example:
If an enterprise wishes to take a backup of the company servers at 9:00 pm on every Friday,
then you can very well automate this task to let the schedule happen on its own. In a scenario,
the backup encounters an error, the SQL Server Agent records the event and notifies the
corresponding team.
Q4. Mention the differences between local and global temporary tables.
Local Temporary Table Global Temporary Table
1 SELECT @@version
Q6. What is single-user mode and what are the steps you should follow to start
SQL Server in single-user mode?
It may often happen that you would want to start an instance of SQL Server in the single-user
mode. You could do this, either when you want to recover data from other database systems or
may want to change server configurations.
When you start the SQL Server in the single-user mode then, any member of the computer’s
local Administrators group gets connected to the instance of SQL Server as sysadmin.
Also, note that you have to stop the SQL Server Agent service before connecting to an instance
of SQL Server in the single-user mode.
You can use SQL Server Profiler for activities such as:
1. Finding the root cause of the problem
2. Monitoring the performance of SQL Server to handle the workloads.
3. Diagnosing the slow queries
4. Capturing a series of SQL statements causing problem, to further replicate the problem on the
test server, while debugging the issue.
5. It also helps in correlating performance counters to debug issues easily.
Must be enclosed in parentheses as it must be executed first before the main query
More than one query can be included.
A sub query should not have ORDER BY clause but can include WHERE, GROUP BY, and
HAVING CLAUSE
The subquery must be on the right hand side of the comparison operator of the main query
A subquery must include the SELECT clause and a FROM clause.
In this state, if you try to bring SQL Server Agent resources online, then it may fail over SQL
resources to a different node as it could be configured to a group. So, to start a single user-
mode in clustered installation, you can follow the below steps:
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.
1. 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.
2. Transactional Replication: This replication is a process of distributing data from publisher to
subscriber and is used in server to server environment.
3. Snapshot Replication: This replication distributes data exactly as it appears at a specific
moment and is used for replicating data, which changes infrequently.
Q12. What are the differences between MS SQL Server & Oracle?
MS SQL Server Oracle
1. Intent Shared Lock(IS): This lock is used when you have a shared lock at the row level.
2. Intent Update Lock(IU): The Intent update lock is used when you have an update lock at the
row level.
3. Intext Exclusive Lock(IX): This lock is used when you have an exclusive lock at the row level.
Q14. What are the steps you must follow to hide SQL Server instances?
The steps you must follow to hide SQL Server instances are as follows:
MySQL DBA Certification Training
Explore Curriculum
Open the SQL Server Configuration Manager and expand the SQL Server Network
Configuration.
Then go to Protocols and choose the instance of SQL Server.
Later on, right-click on the instance and select the Properties
Next, in the Hide Instance box, go to the on the Flags tab, and select Yes.
Finally, click on OK, and close the dialog box.
Q15. What do you understand by the data quality services in SQL Server?
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.
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.
Q16. Explain Magic Tables in SQL server
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).
Q18. What do you understand by triggers and mention the different types of it?
Triggers are used to execute batches of SQL code whenever INSERT, DELETE, or UPDATE
commands are executed against a table. So, basically triggers are automatically executed
whenever the data is modified based on the data manipulation operations.
1. INSERT
2. UPDATE
3. DELETE
4. INSTEAD OF
Q21. What are trace flags and mention a few common trace flags used with SQL
Server?
These flags are used to alter server behavior or set server characteristics. Few common trace
flags used with SQL Server are as follows
1204, 1205, 1222 – These flags are used for deadlock Information.
174 – This trace flag increases the SQL Server Database Engine plan cache bucket count from
40,009 to 160,001 on 64-bit systems.
1118 – Forces uniform extent allocations instead of mixed page allocations – (SQL 2005 and
2008) To reduces TempDB contention.
652 – This trace flag disables page prefetching scans.
2566 – Used to run the DBCC CHECKDB command without data purity check, unless
the DATA_PURITY option is specified.
Q22. Mention the differences between SUBSTR and CHARINDEX in SQL Server.
SUBSTR CHARINDEX
Used to return a specific portion of the string Used to return a character position in a given
in a given string specified string
Example: Example:
SUBSTRING(‘Edureka’,1,4) CHARINDEX(‘r’,’Edureka’,1)
Output: Output:
Edur 4
Q23. What do you understand by the Analysis Services in SQL Server?
Analysis Services in Microsoft SQL Server is an analytical data engine used in business
analytics and decision support. This service provides enterprise-grade semantic models for
client applications and reports such as Power BI, Microsoft Excel, and other visualization tools.
Q24. What do you understand by Mirroring and mention the advantages of the
Mirroring?
Mirroring in SQL Server is designed to maintain a hot standby server, that is consistent with the
primary server in terms of a transaction. Also, the transaction log records are sent from the
principal server to the secondary server.
Q25. When do you think a developer should use SQL Server-based cursors?
SQL Server-based cursors are used when you wish to work on a record at any instance of time,
rather than taking all the data from a table as a bulk. However, cursors are not preferred to be
used when large volumes of data is present as it affects performance. In a scenario, where it is
not possible to avoid cursors, then try to reduce the number of records to process by using a
temporary table and then eventually build the cursor from this.
Q26. What part does database design plays a role in performance of an SQL
Server-based application?
The physical and logical design plays an important part in the performance of SQL Server-
based applications. We need to ensure that correct data is captured in proper tables, the data
items have proper relationships between them and data redundancy is reduced. I would also
suggest that while you are designing a database, make sure that it is an iterative process to
achieve all the required system goals and is under constant observation. Once the database
design is set, it is very tough to change the design according to requirement. You can only add
new relationships and data items.
Q27. What do you understand by User-Defined function in the SQL Server and explain
the steps to create and execute a user-defined function in the SQL Server?
A user-defined function is a function written as per the needs of the user by implementing logic.
In these kinds of functions the user is not limited to pre-defined functions and simplify the
complex code of predefined function by writing simple code. This function returns a scalar value
or a table.
2 RETURNS TABLE
3 AS
Q28. How can you ensure that the database and SQL Server based application
perform well?
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.
Databases Training
5(8617)
5(5223)
4(15716)
5(12545)
5(2669)
5(902)
Next
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.
Q29. What are relationships and mention different types of relationships in the
DBMS
A relationship in DBMS is the scenario where two entities are related to each other. In such a
scenario, the table consisting of foreign key references to that of a primary key of the other
table.
One-to-One Relationship – Used when a single row in Table A is related to a single row in
Table B.
One-to-Many Relationship – Used when a single row in Table A is related to many rows in
table B.
Many-to-Many Relationship – Used when many rows in table A can be related to many rows in
table B.
Self -Referencing Relationship – Used when a record in table A is related to record in same
table.
Q30. What are joins in SQL and what are the different types of joins?
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them. It is used to merge two tables or retrieve data from there. There are 4 joins in
SQL namely:
Inner Join
Right Join
Left Join
Full Join
Also, note that DBCC is supported on databases that contain memory-optimized tables but
does not provide repair options. This implies that you must regularly back up databases and
test those backups.
Example:
3 FirstName varchar(255),
4 Age int,
5 City varchar(255),
Example:
Syntax:
1 FLOOR(expression)
Example:
1 FLOOR(7.3)
Q35. What is the command used to check locks in Microsoft SQL Server?
To check locks in the database, you can use the in-built stored procedure sp_lock.
Syntax
2 [ ; ]
Example:
To list all the locks currently held in an instance of the Database Engine, use the following
command:
1 USE SampleDB;
2 GO
3 EXEC sp_lock;
4 GO
Q36. Mention the 3 ways to get a count of the number of records in a table.
The following are three ways to count the number of records in the table:
Syntax:
1 SIGN(number)
Example:
Q40. Write a query to find 5th highest amount paid from the Customer table.
To find the 5th highest amount paid from the customers’ table, you can write a query as below:
1 SELECT TOP 1 amount FROM (SELECT DISTINCT TOP 5 amount FROM customers ORDER BY amou
Syntax:
1 DELETE TableName
Example:
1 DELETE Customers;
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.
The PHYSICAL_ONLY option is used to limit check to the integrity of the physical structure of the
record headers, page, and also the allocation consistency of the database.
The PHYSICAL_ONLY check is used to provide a small overhead check of the physical
consistency of the database.
Also, the PHYSICAL_ONLY option causes a shorter run-time for DBCC CHECKDB on large
databases. So, it is generally recommended for frequent use on production systems.
Q44. Can you explain how long are locks retained within the REPEATABLE_READ
and SERIALIZABLE isolation levels, during a read operation with row-level
locking?
With REPEATABLE_READ and SERIALIZABLE isolation levels, locks are held during the
transaction. But, if you consider READ_COMMITTED, then locks are held for isolation level.
Note: Whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Also, integration services can extract and transform data from a wide variety of sources such as
relational data sources, XML data files, load the data into more than a single database. So,
basically, you can use the integration services to create solutions without coding, code complex
tasks, program the extensive integration object model to create packages.
The integration services include good set of built-in tasks and transformations, graphical tools
used for building packages and also contain the Catalog database to store, run and manage
packages.
Q49. What are the options which must be set to allow the usage of optimistic
models?
The READ_COMMITED_SNAPSHOT option and the ALLOW_SNAPSHOT_ISOLATION option
must be set to allow the usage of optimistic models.
The READ_COMMITTED_SNAPSHOT option is used for the read committed optimistic model.
ALLOW_SNAPSHOT_ISOLATION option is used for the snapshot isolation level.
Fragmentation
Input/Output bottlenecks
Blocking Queues
Deadlocks
Missing and unused indexes
So this brings us to the end of the SQL Server Interview Questions article. I hope this set of
SQL Server Interview Questions will help you ace your job interview. All the best for your
interview!
SQL Server Interview Questions
A list of top frequently asked SQL Server interview questions and answers are
given below.
2) What is Normalization?
In RDBMS, the process of organizing data to minimize redundancy and surety of
logical data integrity is called normalization. In normalization, the database is
divided into two or more tables, and a relationship is defined among the tables.
Normalization technique increases performance for the database.
Types of Normalization
25.4M
585
Next
Stay
o 1NF
o 2NF
o 3NF
o BCNF
o 4NF
o 5NF
However, the first three types are only frequently used, where "NF" stands for
normal form. The originator of the RD model "E.F Codd" has proposed the process
"normalization" with the first "normal form" and continued till third normal form.
3) What is De-Normalization?
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.
o A Function must return a value while stored procedure can return zero or n value.
o Functions can have only input parameter while procedures can have input/ output
parameters.
o Functions take one mandatory input parameter while stored procedures may take 0
to n input parameter.
o Try-catch block can handle exceptions. In the stored procedure, while you can't use
try-catch in functions.
o Case sensitivity
o Accent sensitivity
o Kana sensitivity
o Width 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
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.
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.
If GROUP BY is not used, HAVING works like a WHERE clause. HAVING clause can be
used with the aggregate function.
Syntax:
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:
1. WHERE condition;
o Stored procedures help in reducing the network traffic and latency. It boosts up the
application performance.
o Stored procedures facilitate the reusability of the code.
o Stored procedures provide better security for data.
o You can encapsulate the logic using stored procedures and change stored procedure
code without affecting clients.
o It is possible to reuse stored procedure execution plans, which are cached in SQL
Server's memory. This reduces server overhead.
o It provides modularity of application.
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.
Follow the below instructions to launch SQL Server Configuration Manager and do
the following:
EXAMPLE:
Syntax:
16) In which TCP/IP port does SQL Server run? Can it be changed?
SQL Server runs on port 1433. Yes, it can be changed from the network utility
TCP/IP properties.
17) What are the authentication modes in SQL Server? How can it be
changed?
Authentication mode is used for authentication of the user in SQL server, and it can
be selected at the time of setup of the database engine.
SQL Server supports two authentication modes: Window authentication mode and
mixed mode.
Mixed mode: It is used to connect with the instance of SQL Server using window
authentication or SQL Server authentication. In SQL server authentication mode a
unique username and password are required for a particular database, as it will not
depend on windows account.
You can watch the trace results when the trace runs.
You can find out the bugs in queries and diagnose it.
If it is necessary, you can start, stop, pause and modify the trace results.
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.
23) Can SQL Server be linked with other Servers like Oracle?
Yes, it can be linked to any Server. It has OLE-DB provider from Microsoft which
allow linking.
o It provides a set of rules to implement next class. Rules are provided through
abstract methods.
o An Abstract method does not contain any definition.
o When a class contains all functions without the body, it is called as Fully Abstract
Class.
o Another class can inherit only one abstract class.
Interface:
o If a class contains all abstract methods, then that class is called Interface.
o Interface support like multiple inheritances.
o An Interface does not contain any implementation
o We can only use public or abstract modifiers.
25) What is the difference between the application object and session
object?
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.
26) Is there any difference between primary key and unique with the
NOT NULL condition?
There is no difference between primary key and unique key but, a unique key will
allow single NULL, but in the primary key, no NULL is accepted.
27) What is the difference between value type and reference type?
Value type and reference type may be similar regarding declaration syntax and
usage, but their semantics are distinct. Value type and reference type differ with
the memory area, where it stored.
The Value type is stored on the stack while reference type is stored on the heap.
The Value type stores real data while reference type stores reference to the data.
The value type can contain null value while reference type can't hold a null value.
The value types are derived from System. Value Type while Reference type is
derived from System Object. Means value type stores a particular value but a
reference type stores a reference or address to the object
String, Object, array are the reference type, as they are stored in heap and
dynamic in nature
Example
Example
Only ASCII character data types are allowed in GET method while in POST method
there is no restriction, it allows binary data also.
In GET method length of the string is restricted while in POST method length of the
string is not limited.
Get method is not secured as it can be bookmarked but, post method is secured as
it cannot be bookmarked
Get method is stored in browser history but post method is not stored in browser
history
The primary purpose of log shipping is to increase database availability just like
replication. On each of secondary database, log backups are applied particularly.
o Firstly take a backup of transaction log file on Primary SQL server instance
o Copy the log file on secondary SQL server instance
o Restore the Log backup file onto secondary SQL Server instance
3) Merge replication: Merge replication grouped the data from various sources to
a single centralized database. It is generally used in the server to the client
environment. Merge replication is appropriate when multiple subscribers might
update the same data at the various time.
32) Which is the main third-party tool used in SQL Server?
A list of third-party tools used in SQL Server:
o SQL CHECK - Idera: It is used to monitor server activities and memory levels.
o SQL DOC 2 - RedGate: It is used to document the databases.
o SQL Backup 5 - RedGate: It is used to automate the Backup Process.
o SQL Prompt - RedGate: It provides IntelliSense for SQL SERVER 2005/2000.
o Lite Speed 5.0 - Quest Soft: It is used for Backup and Restore.
34) What are the different types of collation sensitivity in SQL Server?
There are four types of collation sensitivity in SQL Server:
o Case sensitivity
o Accent sensitivity
o Kana Sensitivity
o Width sensitivity
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
36) What is the most common trace flags used with SQL Server?
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:
SYNTAX:
1. FLOOR (expression)
For example:
FLOOR (7.3)
SYNTAX:
1. SIGN (number)
2.
3. If the number>0, then it will return +1
4. If the number=0, then it will return 0
5. If the number<0, then it will return -1
40) What is sub-query in SQL server? Explain its properties.
In SQL Server, a query within the main query like Select, Update, Insert or Delete, is
termed as sub-query. It is also called as INNER Query.
A subquery can be Added to WHERE clause, the FROM clause, or the SELECT clause.
Following are the steps for deleting a table using SQL Server Management
o Transact-SQL functions
o Asymmetric keys
o Symmetric keys
o Certificates
o Transparent Data Encryption
43) Define Magic Tables in SQL server?
A Table which is automatically created and managed by SQL server internally to
store the inserted, updated values for any DML (SELECT, DELETE, UPDATE, etc.)
operation, is called as Magic tables in SQL server. The triggers preferably use it.
1) What is SQL?
SQL stands for the Structured Query Language. It is the standard language used to
maintain the relational database and perform many different data manipulation
operations on the data. SQL was initially invented in 1970. It is a database language
used for database creation, deletion, fetching and modifying rows, etc. sometimes,
it is pronounced as 'sequel.' We can also use it to handle organized data comprised
of entities (variables) and relations between different entities of the data.
o Data definition language (DDL): It defines the data structure that consists of
commands like CREATE, ALTER, DROP, etc.
o Data manipulation language (DML): It is used to manipulate existing data in the
database. The commands in this category are SELECT, UPDATE, INSERT, etc.
o Data control language (DCL): It controls access to the data stored in the
database. The commands in this category include GRANT and REVOKE.
o Transaction Control Language (TCL): It is used to deal with the transaction
operations in the database. The commands in this category are COMMIT, ROLLBACK,
SET TRANSACTION, SAVEPOINT, etc.
Example
Example
REVOKE: It enables system administrators to revoke privileges and roles from the
user accounts so that they cannot use the previously assigned permission on the
database.
Example
Example
Table: Student
1. CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
13) What is the difference between a primary key and a unique key?
The primary key and unique key both are essential constraints of the SQL. The main
difference among them is that the primary key identifies each record in the table. In
contrast, the unique key prevents duplicate entries in a column except for a NULL
value. The following comparison chart explains it more clearly:
The primary key act as a unique The unique key is also a unique identifier for records
identifier for each record in the table. when the primary key is not present in the table.
We cannot store NULL values in the We can store NULL value in the unique key column, but
primary key column. only one NULL is allowed.
We cannot change or delete the We can modify the unique key column values.
primary key column values.
o Software
o Data
o Procedures
o Database Languages
o Query Processor
o Database Manager
o Database Engine
o Reporting
16) What are the different types of database management systems?
The database management systems can be categorized into several types. Some of
the important lists are given below:
The occurrence of redundant terms in the database causes the waste of space in
the disk.
Due to redundant terms, inconsistency may also occur. If any change is made in the
data of one table but not made in the same data of another table, then
inconsistency will occur. This inconsistency will lead to the maintenance problem
and effects the ACID properties as well.
o Unique Index
o Clustered Index
o Non-Clustered Index
o Bit-Map Index
o Normal Index
o Composite Index
o B-Tree Index
o Function-Based Index
Example
Suppose we want to make a Phone column as a unique index. We can do this like
below:
The purpose of creating a non-clustered index is for searching the data. Its best
example is a book where the content is written in one place, and the index is at a
different place. We can create 0 to 249 non-clustered indexes in each table. The
non-clustered indexing improves the performance of the queries which use keys
without assigning the primary key.
30) What are the differences between SQL, MySQL, and SQL Server?
The following comparison chart explains their main differences:
SQL or Structured Query MySQL is the popular database SQL Server is an RDBMS
Language is useful for management system used for database system mainly
managing our relational managing the relational developed for the Windows
databases. It is used to query database. It is a fast, scalable, system to store, retrieve, and
and operate the database. and easy-to-use database. access data requested by the
developer.
SQL first appeared in 1974. MySQL first appeared on May SQL Server first appeared on
23, 1995. April 24, 1989.
SQL was developed by IBM MySQL was developed by SQL Server was developed by
Corporation. Oracle Corporation. Microsoft Company.
SQL is a query language for MySQL is database software SQL Server is also a software
managing databases. that uses SQL language to that uses SQL language to
conduct with the database. conduct with the database.
SQL has no variables. MySQL can use variables SQL Server can use variables
constraints and data types. constraints and data types.
SQL PL/SQL
SQL has no variables. PL/SQL can use variables constraints and data types.
SQL can execute only a single query at PL/SQL can execute a whole block of code at once.
a time.
SQL query can be embedded in PL/SQL. PL/SQL cannot be embedded in SQL as SQL does not
support any programming language and keywords.
SQL can directly interact with the PL/SQL cannot directly interact with the database
database server. server.
SQL is like the source of data that we PL/SQL provides a platform where SQL data will be
need to display. shown.
A clustered index is a table or view where the The indexes other than PRIMARY indexes
data for the rows are stored. In a relational (clustered indexes) are called non-clustered
database, if the table column contains a primary indexes. It has a structure separate from the
key, MySQL automatically creates a clustered data row. The non-clustered indexes are also
index named PRIMARY. known as secondary indexes.
Clustered indexes store the data information Non-clustered indexes stores only the
and the data itself. information, and then it will refer you to the
data stored in clustered data.
There can only be one clustered index per table. There can be one or more non-clustered
indexes in a table.
A clustered index determines how data is stored It creates a logical ordering of data rows and
physically in the table. Therefore, reading from uses pointers for accessing the physical data
a clustered index is faster. files. Therefore, reading from a clustered index
is slower.
35) Which are joins in SQL? Name the most commonly used SQL
joins?
SQL joins are used to retrieve data from multiple tables into a meaningful result set.
It is performed whenever you need to fetch records from two or more tables. They
are used with SELECT statement and join conditions.
o INNER JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o INNER JOIN
o SELF JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN
o CROSS JOIN
1. SELECT column_lists
2. FROM table1
3. INNER JOIN table2 ON join_condition1
4. INNER JOIN table3 ON join_condition2
5. ...;
1. SELECT colum_lists
2. FROM table1
3. RIGHT JOIN table2
4. ON join_condition;
1. SELECT colum_lists
2. FROM table1
3. LEFT JOIN table2
4. ON join_condition;
SQL triggers have two main components one is action, and another is an event.
When certain actions are taken, an event occurs as a result of those actions.
We use the CREATE TRIGGER statement for creating a trigger in SQL. Here is the
syntax:
A SELF JOIN is required when we want to combine data with other data in the same
table itself. It is often very useful to convert a hierarchical structure to a flat
structure.
1. SELECT column_lists
2. FROM table1 AS T1, table1 AS T2
3. WHERE join_conditions;
Example
If we want to get retrieve the student_id and name from the table where student_id
is equal, and course_id is not equal, it can be done by using the self-join:
A. UNION: It combines two or more results from multiple SELECT queries into a
single result set. It has a default feature to remove the duplicate rows from the
tables. The following syntax illustrates the Union operator:
B. UNION ALL: This operator is similar to the Union operator, but it does not
remove the duplicate rows from the output of the SELECT statements. The following
syntax illustrates the UNION ALL operator:
1. SELECT columns FROM table1
2. UNION ALL
3. SELECT columns FROM table2;
C. INTERSECT: This operator returns the common records from two or more
SELECT statements. It always retrieves unique records and arranges them in
ascending order by default. Here, the number of columns and data types should be
the same. The following syntax illustrates the INTERSECT operator:
D. MINUS: This operator returns the records from the first query, which is not
found in the second query. It does not return duplicate values. The following syntax
illustrates the MINUS operator:
This operator is used to selects the range It is a logical operator to determine whether or not a
of data between two values. The values specific value exists within a set of values. This
can be numbers, text, and dates as well. operator reduces the use of multiple OR conditions
with the query.
It returns records whose column value It compares the specified column's value and returns
lies in between the defined range. the records when the match exists in the set of
values.
The following syntax illustrates this The following syntax illustrates this operator:
operator: SELECT * FROM table_name
SELECT * FROM table_name WHERE column_name IN ('value1','value 2');
WHERE column_name BETWEEN 'value1'
AND 'value2';
Column Level Constraints: These constraints are only applied to a single column
and limit the type of data that can be stored in that column.
Table Level Constraints: These constraints are applied to the entire table and
limit the type of data that can be entered.
46) How to write an SQL query to find students' names start with 'A'?
We can write the following query to get the student details whose name starts with
A:
Here is the demo example where we have a table named student that contains two
names starting with the 'A' character.
47) Write the SQL query to get the third maximum salary of an
employee from a table named employees.
The following query is the simplest way to get the third maximum salary of an
employee:
Here is the demo example that shows how to get the third maximum salary of an
employee.
The following are the alternative way to get the third-highest salary of an
employee:
B. Using Subquery
1. SELECT salary
2. FROM
3. (SELECT salary
4. FROM employees
5. ORDER BY salary DESC
6. LIMIT 3) AS Temp
7. ORDER BY salary LIMIT 1;
1) The delete statement removes single or The truncate command deletes the whole
multiple rows from an existing table contents of an existing table without the table
depending on the specified condition. itself. It preserves the table structure or
schema.
6) You can roll back data after using the It is not possible to roll back after using the
DELETE statement. TRUNCATE statement.
7) DELETE query takes more space. TRUNCATE query occupies less space.
Atomicity: It ensures that all statements or operations within the transaction unit
must be executed successfully. If one part of the transaction fails, the entire
transaction fails, and the database state is left unchanged. Its main features are
COMMIT, ROLLBACK, and AUTO-COMMIT.
Consistency: This property ensures that the data must meet all validation rules. In
simple words, we can say that the database changes state only when a transaction
will be committed successfully. It also protects data from crashes.
o A function should have a name, and the name cannot begin with a special character
such as @, $, #, or other similar characters.
o Functions can only work with the SELECT statements.
o Every time a function is called, it compiles.
o Functions must return value or result.
o Functions are always used with input parameters.
LOWER: This function is used to converts a given character into lowercase. The
following example will return the 'STEPHEN' as 'stephen':
UPPER: This function is used to converts a given character into uppercase. The
following example will return the 'stephen' as 'STEPHEN':
1. SELECT UPPER ('stephen') AS Case_Reault FROM dual;
INITCAP: This function is used to converts given character values to uppercase for
the initials of each word. It means every first letter of the word is converted into
uppercase, and the rest is in lower case. The following example will return the 'hello
stephen' as 'Hello Stephen':
A) CONCAT: This function is used to join two or more values together. It always
appends the second string into the end of the first string. For example:
Output: Information-technology
B) SUBSTR: It is used to return the portion of the string from a specified start point
to an endpoint. For example:
Output: Management
C) LENGTH: This function returns the string's length in numerical value, including
the blank spaces. For example:
Output: 16
D) INSTR: This function finds the exact numeric position of a specified character or
word in a given string. For example:
Output: 7
E) LPAD: It returns the padding of the left-side character value for right-justified
value. For example:
Output: ***200
F) RPAD: It returns the padding of the right-side character value for left-justified
value. For example:
Output: 200***
G) TRIM: This function is used to remove all the defined characters from the
beginning, end, or both. It also trimmed extra spaces. For example:
Output: BCDCB
Input: SELECT REPLACE ( 'It is the best coffee at the famous coffee shop.', 'coffee',
'tea');
56) What are the syntax and use of the COALESCE function?
The COALESCE() function evaluates the arguments in sequence and returns the first
NON-NULL value in a specified number of expressions. If it evaluates arguments as
NULL or not found any NON-NULL value, it returns the NULL result.
Example:
Suppose we have a table 'customer' containing eight records in which the name
column has some duplicate values.
If we want to get the name column without any duplicate values, the DISTINCT
keyword is required. Executing the below command will return a name column with
unique values.
58) What is the default ordering of data using the ORDER BY clause?
How could it be changed?
The ORDER BY clause is used to sort the table data either in ascending or
descending order. By default, it will sort the table in ascending order. If we want to
change its default behavior, we need to use the DESC keyword after the column
name in the ORDER BY clause.
We have taken a customer table in the previous example. Now, we will demonstrate
the ORDER BY clause on them as well.
In the below output, we can see that the first query will sort the table data in
ascending order based on the name column. However, if we run the second query
by specifying the DESC keyword, the table's order is changed in descending order.
59) Is the following query returns the output?
Answer: No. The above query does not return the output because we cannot use
the WHERE clause to restrict the groups. We need to use the HAVING clause instead
of the WHERE clause to get the correct output.
60) What is the difference between the WHERE and HAVING clauses?
The main difference is that the WHERE clause is used to filter records before any
groupings are established, whereas the HAVING clause is used to filter values from
a group. The below comparison chart explains the most common differences:
WHERE HAVING
It does not allow to work with aggregate functions. It can work with aggregate functions.
This clause can be used with the SELECT, UPDATE, This clause can only be used with the
and DELETE statements. SELECT statement.
SQL provides seven (7) aggregate functions, which are given below:
o AVG(): This function is used to returns the average value from specified columns.
o COUNT(): This function is used to returns the number of table rows, including rows
with null values.
o MAX(): This function is used to returns the largest value among the group.
o MIN(): This function is used to returns the smallest value among the group.
o SUM(): This function is used to returns the total summed values(non-null) of the
specified column.
o FIRST(): This function is used to returns the first value of an expression.
o LAST(): This function is used to returns the last value of an expression.
The DENSE_RANK function assigns a unique rank for each row within a partition as
per the specified column value without any gaps. It always specifies ranking in
consecutive order. If the two rows are assigned the same rank, this function will
assign it with the same rank, and the next rank being the next sequential number.
For example, if we have 3 records at rank 4, the next rank listed would be ranked 5.
Question 1 - What are 2 options to validate whether or not a backup will restore successfully?
o Restore the backup as a portion of a testing process or log shipping.
o Restore the backup with the Verify Only option.
Additional information - Verifying Backups with the RESTORE
VERIFYONLY Statement
Question 1 - Name as many native SQL Server performance monitoring and tuning tools that
you know of and their associated value.
o System objects - System objects such as sp_who2, sp_lock, fn_get_sql, etc.
provide a simple means to capture basic metrics related to locking, blocking,
executing code, etc.
Additional information - SQL Server Command Line Tools To Manage
Your Server
o Profiler - In a nutshell, Profiler provides the lowest common denominator of
activity on a SQL Server instance. Profiler captures per session code with the
ability to filter the data collection based on database, login, host name,
application name, etc. in order to assess the IO, CPU usage, time needed, etc.
Additional information - SQL Server Performance Statistics Using a
Server Side Trace
o Perfmon\System Monitor - Perfmon\System Monitor is responsible for macro
level metrics related to processes and sub systems.
Additional information - Free Microsoft Tools to Help Setup and Maintain
PerfMon
o Dynamic Management Views and Functions - New to SQL Server 2005 and
beyond, the Dynamic Management Views and Functions offer a real time view
into the SQL Server sub systems.
Additional information - Dynamic Management Views and Functions in
SQL Server 2005
o TYPEPERF.EXE - TYPEPERF.EXE is a command line tool included with the
Windows operating system that writes performance data to the command
window or to a file. It is necessary to capture performance data whenever you
are trying to diagnose performance issues on a server. Performance data
provides information on the server's utilization of the processor, memory, and
disk, as well as SQL Server-specific performance data.
Additional information - How To Collect Performance Data With
TYPEPERF.EXE
o SQL Server Management Studio Built-in Performance Reports - As part of the
installation of SQL Server 2005 and beyond a number of performance-related
reports are installed. To get to these reports open the SQL Server
Management Studio (SSMS) and connect to a SQL Server instance. If you don't
have an instance of Reporting Services installed then the icon will be disabled.
Additional information
Built-In Performance Reports in SQL Server 2005
o Additional resources for this question:
Tutorial - SQL Server Performance Monitoring and Tuning
Tip Category - SQL Server Performance Tuning
Answer: The SQL server offers 4 types of backups to suit the need of the administrator.
Complete backup :The complete back up is just zipping the content of the entire database in terms of the
different tables and procedures etc. This back up can server as an independent entity that can be restored in
different systems with just the base SQL server installed.
Transaction log backup: This is the mechanism of backing up the transaction logs that have been maintained in
the server. This way the details of the database getting updated is obtained. This cannot be a stand-alone back up
mechanism. But can save a lot of time if we already have the file system related to the DB backed up on the new
deployment server.
Differential backup: This is a subset of the complete backup, where only the modified datasets are backed up.
This can save the time when we are just trying to maintain a backup server to main server.
File backup: This is the quickest way to take the backup of entire database. Instead of taking in the data actually
stored in DB, the files are backed up and the file system thus obtained when combined with the transaction logs
of the original system will render the database that we are trying to back up.
.
Q What are the different levels of isolation?
Answer: The isolation represents the way of separating the database from the effects of network accesses,
thereby maintaining the consistency. The different levels of isolation are:
read committed: This level of isolation uses the shared locks and the reads to the database give the constant and
consistent values.
read uncommitted: No locks implemented. This is the least effective isolation level.
repeatable read: There are lock over the rows and values but the updates are maintained as a separate phantom
row which is the next set of values for the specific record. Values can change within a specific transaction of a SQL
function.
SERIALIZABLE reads: This is the implementation of pure lock mechanism where one specific transaction is not
allowed access to specific record before another one completes.
Q.What are the steps to take to improve performance of a poor performing query?
Answer: Maximum use of indexes, stored procures should be done. Avoid excessive use of complicated joins and
cursors. Avoid using conditional operators using columns of different tables. Make use of computed columns and
rewriting the query.
Q.What is normalization? Explain different levels of normalization?
Answer: Check out the article Q100139 from Microsoft knowledge base and of course, there's much more
information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book,
especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.
Q.What is denormalization and when would you go for it?
Answer: As the name indicates, denormalization is the reverse process of normalization. It's the controlled
introduction of redundancy in to the database design. It helps improve the query performance as the number of
joins could be reduced.
Q.How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
Answer: One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with
primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table
with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea
to read up a database designing fundamentals text book.
Q.What's the difference between a primary key and a unique key?
Answer: Both primary key and unique enforce uniqueness of the column on which they are defined. But by
default primary key creates a clustered index on the column, where are unique creates a nonclustered index by
default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.
Q.What are user defined datatypes and when you should go for them?
Answer: User defined datatypes let you extend the base SQL Server datatypes 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
datatype called Flight_num_type of varchar(8) and use it across all your tables.
Q.What is bit datatype and what's the information that can be stored inside a bit column?
Answer: Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit
datatype can represent a third state, which is NULL.
Q.Define candidate key, alternate key, composite key.
Answer: A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes
the primary key of the table. If the table has more than one candidate key, one of them will become the primary
key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called
composite key.
Q.What are defaults? Is there a column to which a default can't be bound?
Answer: A default is a value that will be used by a column, if no value is supplied to that column while inserting
data. IDENTITY columns and timestamp columns can't have defaults bound to them. Q.What is a transaction and
what are ACID properties? Answer: A transaction is a logical unit of work in which, all the steps must be
performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a
transaction. For more information and explanation of these properties, see SQL Server books online or any
RDBMS fundamentals text book.
Q.Explain different isolation levels
Answer: An isolation level determines the degree of isolation of data between concurrent transactions. The
default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of
isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for
an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you
customize the isolation level at the connection level.
Q.What type of Index will get created after executing the above statement?
Answer: Non-clustered index. Important thing to note: By default a clustered index gets created on the primary
key, unless specified otherwise.
Q.What's the maximum size of a row?
Answer: 8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'.
Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".
Q.What is lock escalation?
Answer: Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher
level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being
occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer
coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards
it's dynamically managed by SQL Server.
Q.What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
Answer: DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which
makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row,
instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE
can be rolled back.
Q.Explain the storage models of OLAP
Answer: Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation. What are the new
features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What
changed between the previous version of SQL Server and the current version?
Q.What are constraints? Explain different types of constraints.
Answer: Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you
to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY
Q.Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I
create a separate index on each column of a table. what are the advantages and disadvantages of this approach?
Answer: Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered
index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only
one clustered index per table. Non-clustered indexes have their own storage separate from the table data
storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes
having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending
up on the absence or presence of clustered index on the table. If you create an index on each column of a table, it
improves the query performance, as the query optimizer can choose from all the existing indexes to come up
with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE,
DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another
disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used. Database
administration
Q.What is RAID and what are different types of RAID configurations?
Answer: RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database
servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has
some information about RAID levels and for detailed information, check out the RAID advisory board's homepage
Q.What are the steps you will take to improve performance of a poor performing query?
Answer: This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of
date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET
NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage
of cursors and temporary tables. Some of the tools/ways that help you troubleshooting performance problems
are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows
NT /2000 Performance monitor, Graphical execution plan in Query Analyzer.
Q.What are the steps you will take, if you are tasked with securing an SQL Server?
Answer: Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the physical
database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL
Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling
auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web
server etc.
Q.What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Answer: Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of
the user processes is terminated. SQL Server detects deadlocks and terminates one user's process. 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.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the
article Q169960 from Microsoft knowledge base.
Q.What is blocking and how would you troubleshoot it?
Answer: Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.
Q.Explain CREATE DATABASE syntax
Answer: Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command:
CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the
other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why
being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for
more information.
Q.How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
Answer: SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user
mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online
for more parameters and their explanations.
Q.As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
Answer: DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG,
DBCC SHRINKDATABASE, DBCC SHRINKFILE etc .
Q.What are statistics, under what circumstances they go out of date, how do you update them?
Answer: Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these
indexes in determining whether to choose an index or not while executing a query. Some situations under which
you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of
data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has
changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3)
Database is upgraded from a previous version
Q.What are the different ways of moving data/databases between servers and databases in SQL Server?
Answer: There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP,
logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
Q.What is database replicaion? What are the different types of replication you can set up in SQL Server?
Answer: Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:
Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication
agents function, what are the main system tables used in replication etc. How to determine the service pack
currently installed on SQL Server? The global variable @@Version stores the build number of the sqlservr.exe,
which is used to determine the service pack installed. To know more about this process visit SQL Server service
packs and versions. Database programming (top)
Q.What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you
avoid cursors?
Answer: Cursors allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only,
Keyset-driven. See books online for more information. Disadvantages of cursors: Each time you fetch a row from
the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip,
however large the resultset is. Cursors are also costly because they require more resources and temporary
storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be
used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is
an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000
and 40000 -- 5000 hike Salary between 40000 and 55000 -- 7000 hike Salary between 55000 and 65000 -- 9000
hike In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or can be
combined in a single UPDATE statement as shown below: UPDATE tbl_emp SET salary = CASE WHEN salary
BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END Sql Server DBA Interview Questions Sql
Server DBA Interview Questions and Answers
Q.Write down the general syntax for a SELECT statements covering all the options.
Answer: Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax). SELECT select_list
FROM table_source ]
Q.What is a join and explain different types of joins.
Answer: 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.
Q.What is the system function to get the current user's user id?
Answer: USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER,
CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
Q. What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Answer: Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE
or DELETE operation takes place on a table. In SQL Server 6.5 you could define only 3 triggers per table, one for
INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could
create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In
SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder Triggers can't be
invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on
the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers
can also be used to extend the referential integrity checks, but wherever possible, use constraints for this
purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers fire only after the data
modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could
create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers. Also check out books
online for 'inserted table', 'deleted table' and COLUMNS_UPDATED() There is a trigger defined for INSERT
operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly
insterted rows to it for some custom processing. What do you think of this implementation? Can this be
implemented better? Instantiating COM objects is a time consuming process and since you are doing it from
within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This
scenario can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.
Q.What is a self join? Explain it with an example.
Answer: Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find
out the managers of all the employees, you need a self join. CREATE TABLE emp ( empid int, mgrid int, empname
char(10) ) INSERT emp SELECT 1,2,'Vyas' INSERT emp SELECT 2,3,'Mohan' INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar' INSERT emp SELECT 5,2,'Sourabh' SELECT t1.empname , t2.empname FROM
emp t1, emp t2 WHERE t1.mgrid = t2.empid Here's an advanced query using a LEFT OUTER JOIN that even returns
the employees without managers (super bosses) SELECT t1.empname , COALESCE(t2.empname, 'No manager')
FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid
Q.What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Answer: A deadlock occurs when two or more processes waits for a resource that is acquired by or is under the
control of another process. A live lock is similar to a deadlock except the process states keeps changing. The
result of such state is that none of the process will be complete. Deadlock detection finds and resolves deadlocks.
A WFG strategy is followed. WFG is wait for graph. In WFG, processes are represented by nodes while
dependencies are represented by edges. Thus, if process A is waiting for a resource held by process B, there is an
edge in the WFG from the node for process A to the node for process B. a cycle is this graph is a deadlock. WFG
constantly checks for cycles or when a process is blocked and adds a new edge to the WFG. When a cycle is
found, a victim is selected and aborted.
Q.What is blocking and how would you troubleshoot it?
Answer: Blocking occurs when two or more rows are locked by one SQL connection and a second connection to
the SQL server requires a conflicting on lock on those rows. This results in the second connection to wait until the
first lock is released. Troubleshooting blocking: SQL scripts can be written that constantly monitor the state of
locking and blocking on SQL Server The common blocking scenarios must be identified and resolved. The scripts
output must be checked constantly, The SQL profilers data must be examined regularly to detect blocking.
Q.Explain the different types of BACKUPs available in SQL Server.
Answer: Complete database backup: This type of backup will backup all the information in the database. Used
most commonly for disaster recovery and takes the longest time to backup. Differential databse backup: The
database is divided into partitions that have been modified since last complete backup. Most suitable for large
databases. The most recent differential backup contains the changes from previous backups. Transaction log
backups: Backups only the changes logged in the transaction log. The transaction log has all changes logged about
a database. Once the changes are accommodated on the database, the log is truncated or backed up. File/File
Group backups: used to recover individual files or file groups. Each filegroup can be individually backed up. This
helps in recovery only the required file or filegroup for disaster recovery.
Q.What is database isolation in SQL Server?
Answer: Isolation in database defines how and when changes made by one transaction can be visible to other
transactions. Different isolation levels are: Serializable Repeatable read Read committed Read uncommitted
Q.What is a Schema in SQL Server ? Explain how to create a new Schema in a Database?
Answer: A schema is used to create database objects. It can be created using CREATE SCHEMA statement. The
objects created can be moved between schemas. Multiple database users can share a single default schema.
CREATE SCHEMA sample; Table creation Create table sample.sampleinfo { id int primary key, name varchar(20) }
Q.Explain how to create a Scrollable Cursor with the SCROLL Option.
Answer: Using the SCROLL keyword while declaring a cursor allows fetching of rows in any sequence Example:
DECLARE employee_curs SCROLL CURSOR FOR SELECT * FROM employee; The active set of the cursor is stored
can be accessed in any order without the need of opening and closing the cursor. The Scroll cursors can be set for
select and function cursors but not insert or update statements.
Q.Explain how to create a Dynamic Cursor with the DYNAMIC Option.
Answer: When a cursor is declared as DYNAMIC, the cursor reflects all changes made to the base tables as the
cursor is scrolled around. Declare cursor_name cursor FOR select_statement The dynamic option does not
support ABSOLUTE FETCH.
Q.What are database files and filegroups?
Answer: Database files are used for mapping the database over some operating system files. Data and log
information are separate. SQL server database has three types of database files: Primary: starting point of a
database. It also points to other files in database. Extension: .mdf Secondary: All data files except primary data
file is a part of secondary files. Extension: .ndf Log files: All log information used to recover database.
Extension: .ldf
Q.Describe in brief Databases and SQL Server Databases Architecture.
Answer: SQL Server consists of a set of various components which fulfill data storage and data analysis needs for
enterprise applications. Database architecture: All the data is stored in databases which is organized into logical
components visible to the end users. It’s only the administrator who needs to actually deal with the physical
storage aspect of the databases, whereas users only deal with database tables. Every SQL Server instance has
primarily 4 system database i.e. master, model, tempdb and msdb. All other databases are user created
databases as per their needs and requirements. A single SQL Server instance is capable of handling thousands of
users working on multiple databases.
Q.How can you start the SQL Server in the single user mode and the minimal configuration mode?
Answer: The SQLServer.exe is the executable which can be called in the command prompt with the parameters -
m and -f. These are the options that will start the SQL server in the user mode and minimal configuration mode
respectively.
Q.How can you know that statistics should be updated?
Answer: Statistics represent the uniqueness for the indexes that are being used for selecting the records. This can
make the query execution pretty efficient. The tables that we are dealing with if truncated and repopulated,
there is a good chance that the indexes and statistics are out of sync and this is when we have to update the
statistics. There are also other situations like when the table has been modified and lot of rows have been added
recently or like when a server has been updated with different version of software. These also give us the reason
to use the UPDATE_STATISTICS, DBCC SHOW_STATISTICS etc to update it accordingly.
Q.What is replication in SQL Server?
Answer: Replication refers to the moving or copying of the database elements from one system to another. This
can be done in the SQL Server in one of the following methods:
Transactional.
Snapshop.
Merge replication.
Q.Can we initiate a external COM object from within SQL?
Answer: Yes we can use the stored procedure sp_OACreate to initiate the external COM object from the T-SQL.
Q.What is a schema? How is it useful in SQL Serers?
Answer: The Schema refers to the overall structure of the database with all related information like users, access
privileges, interaction information between the different tables etc. The CREATE SCHEMA is the command that
can be used to create the schema in the SQL Server. This when done can be used to re deploy the same database
in another system for demonstrative or test purposes. This holds intact the underlying framework over which the
database has been built.
Q.What is a write-ahead log?
Answer: The write-ahead log is the logging system that just updates the buffer cache of the database for the
transactions and updates the logs and only then the actual changes are incorporated in the actual database. This
is the reason why it is called “write ahead”. This helps in maintaining the consistency in the database. This can
also be useful in getting the actual database values even in case of failures.
Q.What is the use of check points in the transaction logs?
Answer: The check points are restoration points that indicate the specific state of the database. When there is
some failure int he database that is occurring before the next check point, the database can be reverted back to
the previous check point and thus the database would still be consistent.
Q.What is a column with identity?
Answer: The column with a defined identity in turn means that there is an unique value that the system assigns to
the specific column. This is similar to the AUTONumber property of the Access backend.
Q.What are the different components that constitute the SQL Server architecture?
Answer: The Logical component consists of the overall database structure definitions, users, groups, access
permissions, collations etc. The Physical component is the one that contains the physically represented form of
the database i.e the actual files. There are three types of files:
Primary data files: These contain the links to the other files. This file is the representation of the higher level of
the database. (.mdf)
Secondary data files: These contain the files that contain the values and actual data as in database.
Log files: These represent the different types of the logging output of the SQL Server, including the transaction
logs.
Answer: The scrollable cursors are the ones that can get the entire set of rows as single entity, within which all
the rows present can be accessed in any order without the open/close of cursor done for every row access. The
scrollable cursors are created with the keyword SCROLL added to the CREATE Cursor statements. The scrollable
cursors are useful for the access of information from different rows but not for the delete/insert of new rows.
Q.What is RAID? How does it help storage of databases?
Answer: The RAID stands for Redundant Array of Independent Disks. With its own RAID controllers, the RAID
implements a fail-safe storage mechanism with its own backup mechanisms. There are different configurations of
the RAID that all give us the ACID properties of storage along with other such facilities. This kind of storage will
make the SQL Server database to be fail-safe and stable. This can sometimes mean that the backup mechanisms
and other such reliability measures can be taken off from the SQL Server level of operations.
Q.How can you identify the version number of the SQL Server installed?
The global variable @@version has the build and version information for the SQL Server and the service packs.
Answer: The simplest answer to this is “Clustered and Non-Clustered Indexes”. There are other types of Indexes
what can be mentioned such as Unique, XML, Spatial and Filtered Indexes. More on these Indexes later.
In a clustered index, the leaf level pages are the actual data pages of the table. When a clustered index is created
on a table, the data pages are arranged accordingly based on the clustered index key. There can only be one
Clustered index on a table. In a Non-Clustered index, the leaf level pages does not contain data pages instread it
contains pointers to the data pages. There can multiple non-clustered indexes on a single table.
Q.How do you troubleshoot errors in a SQL Server Agent Job?
Answer: Inside SSMS, in Object explorer under SQL Server Agent look for Job Activity Monitor. The job activity
monitor displays the current status of all the jobs on the instance. Choose the particular job which failed, right
click and choose view history from the drop down menu. The execution history of the job is displayed and you
may choose the execution time (if the job failed multiple times during the same day). There would information
such as the time it took to execute that Job and details about the error occurred.
Q.What is the default Port No on which SQL Server listens?
Answer: 1433
Q. How many files can a Database contain in SQL Server?How many types of data files exists in SQL Server? How
many of those files can exist for a single database?
Answer: A Database can contain a maximum of 32,767 files. There are Primarily 2 types of data files Primary data
file and Secondary data file(s). There can be only one Primary data file and multiple secondary data files as long
as the total # of files is less than 32,767 files.
Q. What is DCL?
Answer: DCL stands for Data Control Language.
Q.What are the commands used in DCL?
Answer: GRANT, DENY and REVOKE.
Q.What is Fill Factor?
Answer: Fill Factor is a setting that is applicable to Indexes in SQL Server. The fill factor value determines how
much data is written to an index page when it is created / rebuilt.
Q.What is the default fill factor value?
Answer: By default the fill factor value is set to 0.
Q.Where do you find the default Index fill factor and how to change it?
Answer: The easiest way to find and change the default fill factor value is from Management Studio, Right click
the Server and choose properties. In the Server Properties, choose Database Settings. you should see the default
fill factor value in the top section. You can change to a desired value there. The other of viewing and changing
this value is using sp_configure.
Q.What is SQL Profiler. What are the default templates with it?
Answer: SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database
Engine or Analysis Services. You can capture and save data about each event to a file or table to analyze later.
Q.What are the DMVs?
Answer: Dynamic Management Views (DMV) return server state information that can be used to monitor the
health of a server instance, diagnose problems, and tune performance.
Q.What is the syntax to execute the sys.dm_db_missing_index_details?
Answer: Select * from sys.dm_db_missing_index_details
Sql server - is commonly used as the backend system for websites and corporate CRMs and can support
thousands of concurrent users.SQL Server is much more robust and scalable than a desktop database
management system such as Microsoft Access.
2. What are the System Database in Sql server 2005?
Master - Stores system level information such as user accounts, configuration settings, and info on all other
databases.
Model - database is used as a template for all other databases that are created
Msdb - Used by the SQL Server Agent for configuring alerts and scheduled jobs etc
Tempdb - Holds all temporary tables, temporary stored procedures, and any other temporary storage
requirements generated by SQL Server.
Master
Model
Msdb
Tempdb
Resource
8. What are the different locks in Sql Server?
Intent
Shared
Update
Exclusive
Schema
Bulk Update
9. What are the different types of Sub-Queries?
Constraints is a rule or restriction concerning a piece of data that is enforced at the data level. A Constraint
clause can constrain a single column or group of columns in a table.
There are five types of Constraint namely
Null / Not Null
Primary Key
Unique
Check or Validation
Foreign Key or References Key
1. What are the different types of BACKUPs avaialabe in SQL Server 2005?
The primary key is the columns used to uniquely identify each row of a table.
A table can have only one primary key.
No primary key value can appear in more than one row in the table.
14. What is cursors?
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,
instead of the typical SQL commands that operate on all the rows in the set at one time.
15. What is SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of
Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze
later.
A DELETE statement enables you to selectively remove data from a table, whereas
The TRUNCATE statement unconditionally removes all rows from a table.
17. What are the types of transaction levels in SQL SERVER?
18. What is the difference between a DDL trigger and a DML trigger?
A DDL trigger executes in response to a change to the structure of a database (for example, CREATE,
ALTER, DROP).
A DML trigger executes in response to a change in data (INSERT, UPDATE, DELETE).
19. What database does SQL Server use for temporary tables?
TempDB.
20. What is a linked server?
A linked server enables you to work with other SQL Servers as well as databases other than SQL
Server databases, right from within Management Studio.
Atomicity
Consistency
Isolation
Durability
22. Define Synonym?
Synonym is an alternative method to creating a view that includes the entire table or view from
another user it to create a synonym.
A synonym is a name assigned to a table or view that may thereafter be used to refer to it.
Full
Simple
Bulk Logged
27. What the difference between UNION and UNIONALL?
Union will remove the duplicate rows from the result set while Union all does’nt.
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as
Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF›s can be though of as views that take parameters and can be used in JOINs and other Rowset
operations.
30. What is the difference between a local and a global variable?
A Local temporary table exists only for the duration of a connection or, if defined inside a compound
statement, for the duration of the compound statement.
A Global temporary table remains in the database permanently, but the rows exist only within a given
connection. When connection are closed, the data in the global temporary table disappears. However, the table
definition remains with the database for access when database is opened next time.
38. Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.
39. What are the types of subscriptions in SQL Server replication?
41. What is the difference between system objects and user objects?
Unique key is a one or more column that must be unique for each row of the table.
It is similar to primary key. Primary key column will not accept a null. Whereas the unique key column will
accept a null values.
52. Define Joins?
A Join combines columns and data from two or more tables (and in rare cases, of one table with
itself).
Tables
Columns
Data types
Stored procedures
Triggers
Rules
Keys
Constraints
Defaults
Indexes
57. What is the difference between the HAVING clause and the WHERE clause?
SQL Server Express applies the HAVING clause after it summarizes the data, whereas it applies the
WHERE clause before it summarizes the data.
58. Name the three types of user-defined functions?
Scalar
Inline table–valued
Multi-statement table–valued.
59. What is an identity column?
Identity columns provide an autoincrementing value for a table.
60. What component installs the OLEDB and ODBC drivers?
The MDACs (Microsoft Data Access Components).
Collation In database:
Collations in SQL Server provide sorting rules, case, and accent sensitivity properties to data. A collation
defines bit patterns that represent each character in metadata of database. SQL Server supports storing objects
that have different collations in database.
(Or)
USE master
GO
ALTER DATABASE BPO SET EMERGENCY
GO
DBCC CHECKDB (BPO)
GO
ALTER DATABASE BPO SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
DBCC CHECKDB (BPO, REPAIR_ALLOW_DATA_LOSS)
GO
ALTER DATABASE BPO SET MULTI_USER
GO
A stored procedure in SQL is a group of SQL statements that are stored together in a database. Based on the
statements in the procedure and the parameters you pass, it can perform one or multiple DML operations on the
database, and return value, if any. Thus, it allows you to pass the same statements multiple times, thereby,
enabling reusability.
OLE:
Object Linking and Embedding Database (OLE DB) is a group of APIs (Application Programming Interface) used to
facilitate and abstract access to application data of different file formats, including spreadsheets, structured
query language (SQL)-based database management systems (DBMS), indexed-sequential files, and personal
databases.
OLE DB is based on the Component Object Model (COM) and is part of the Microsoft Data Access Components
(MDAC) software package, which is used to read and write data.
A checkpoint writes the current in-memory modified pages (known as dirty pages) and transaction log
information from memory to disk and, also records the information in the transaction log.
The Database Engine supports several types of checkpoints: automatic, indirect, manual, and internal.