SQL Server Interview Questions

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 14

SQL Server Interview Questions

1. Explain the use of WITH ENCRYPTION keyword. Create a store procedure with
encryption.

It is a way to convert the original text of the stored procedure into encrypted form.

The stored procedure gets modified and once it is encrypted then it is not possible to get
original text of the stored procedure from stored procedure itself.
CREATE PROCEDURE abc
WITH ENCRYPTION
AS
<< SELECT statement>>
GO

2. What is a linked server in SQL Server?


It enables SQL server database engine to execute commands against OLE DB data
source.
It allows the remote server access and has the ability to issue distributed queries,
updates, commands and transactions.
3. What are the features and concepts of Analysis Services?

Analysis Services is a middle tier server of OLAP (online analytical processing) and Data
mining.

It manages multidimensional cubes of data and provides access to the heaps of


information including the aggregation of data which can create data mining models from
data sources and use it for business intelligence.

Some of the key features are:


-

Ease of use with a lot of wizards and designers.


Flexible data model creation and management.
Scalable architecture to handle OLAP.
Provides integration of administration tools, data sources, security, caching, and
reporting etc.
Provides extensive support for custom applications.

4. What is analysis service repository?

Every analysis server has a repository to store metadata for the objects like cubes, data
sources etc.

It is by default stored in a MS-Access database which can be also migrated to a SQL


Server database.

5. What is SQL service broker?

Service broker allows internal and external processes to send and receive guaranteed
asynchronous messages.

Messages can also be sent to remote servers that are hosting databases as well.

The concept of queues is used by the broker to put a message in a queue and continue
with other applications asynchronously.

This enables client applications to process messages at their leisure without blocking the
broker.

Service Broker uses the concepts of message ordering, coordination, multithreading and
receiver management to solve some major message queuing problems.

It allows for loosely coupled services for database applications.

6. What are the user defined data types and when are they used?

User defined data types are based on the system data types.

They should be used when multiple tables need to store the same type of data in a column
and you need to ensure that all these columns are exactly the same including length, and
nullability.

Parameters for user defined data type:


Name: System data type on which user defined data type is based upon.
Nullability: For example, a user-defined data type called post_code that could
be created based on char system data type.

7. What is a bit data type?

A bit data type is an integer data type which can store either a 0 or 1 or null value.
8. Describe the XML support SQL server extends.
The SQL Server (server-side) support has 3 major elements are as follows:

Creation of XML fragments: This is done from the relational data using FOR XML to the
select query.
Ability to shared XML data to be stored in the database.
Finally, storing the XML data.

Client-side XML support in SQL Server is in the form of SQLXML. It can be described in
terms of:

XML Views: Providing bidirectional mapping between XML schemas and relational
tables.
Creation of XML Templates: It allows creation of dynamic sections in XML.

9. What is SQL Server English Query?

English query allows accessing the relational databases through English Query
applications. Such applications permit the users to ask the database to fetch the data
which is based on simple English instead of using SQL statements.

10. What is the purpose of SQL Profiler in SQL server?

SQL profiler is a tool which monitors the performance of various stored procedures.

It is used to debug the queries and procedure which is based on the performance.

It identifies the slow executing queries.

If there is any problem, then it captures the events on the production environment so that
they can be solved.

11. What is XPath?

XPath is an expression to select the xml node in an XML document.

It allows the navigation on the XML document to the straight element where we need to
reach and access the attributes.

12. What are the authentication modes in SQL Server?

Windows Authentication Mode (Windows Authentication): It uses user windows


account.

Mixed Mode (Windows Authentication and SQL Server Authentication): It uses


either windows or SQL server.

13. Explain Data Definition Language (DDL), Data Control Language (DCL) and Data
Manipulation Language (DML).
1. Data Definition Language (DDL) - It defines the database structure.
Example:
CREATE: It is used to create a table in a database.
ALTER: It is used to add, delete or modify columns in an existing table.
DROP: It is used to remove a table definition and all the data, indexes, triggers,
constraints, and permission specifications for that table. (Note: You have to be careful
while using this command because once a table is deleted then all the information
available in the table would also be lost forever.)
TRUNCATE: This command is used to delete complete data from an existing table.
COMMENT: It adds comment to the table, view or column-level data dictionary objects.
RENAME: It is used to rename a table.
2. Data Manipulation Language (DML) It is used for manipulate or edit the data.
Example:
SELECT Retrieve data from the database.
INSERT Insert data into the table.
UPDATE Modify the existing data within a table.
DELETE It is used to delete data from a table. This command can also be used
with condition to delete a particular row.
MERGE It is used to select rows from one or more sources for update or insertion
into a table or view. You can specify conditions to determine whether to update or
insert into the target table or view.
CALL It calls a PL/SQL or Java subprogram.
EXPLAIN PLAN These statements are supported in PL/SQL only when executed
dynamically.
LOCK TABLE Control concurrency.
3. Data Control Language (DCL) - These statements to take care of the security and
authorization. It is used to create privileges to allow users access and manipulation of the
database.
Examples:
GRANT To grant a privilege to a user.

REVOKE To revoke (remove) a privilege from a user.

14. What are the steps to process a single SELECT statement?


Steps:

The select statement is broken into logical units.

A sequence tree is built and it is based on the keywords and expressions in the form of the
logical units.

Query optimizer checks for various permutations and combinations to figure out the
fastest way of using minimum resources to access the source tables. The best found way
is called as an execution plan.

Relational engine executes the plan and process the data

15. Explain GO Command.

It is a signal command which is used to execute the entire batch of SQL statements after
previous Go command.

16. What is the significance of NULL value and why should it be avoided for permitting
null values?

NULL value means that no entry has been made into the column.

It states that the corresponding value is either unknown or undefined and it is different
from zero (0) or " ".

They should be avoided for the complexity in select & update queries and also because
columns which have constraints like primary or foreign key constraints which cannot
contain a NULL value.

17. What is the difference between UNION and UNION ALL?


UNION:
- It selects only distinct values.
Syntax:

SELECT column_names FROM table_name1


UNION
SELECT column_names FROM table_name2
UNION ALL:
- It selects all values and not just distinct ones.
Syntax:
SELECT column_names FROM table_name1
UNION ALL
SELECT column_names FROM table_name2
18. What is the use of DBCC Commands?

DBCC (Database Consistency Checker) acts as a database console commands for SQL
Server to check database consistency.

They are grouped as:


-

Maintenance
Miscellaneous
Informational
Validation

Maintenance: Maintenance tasks on a database, file group, index.


Maintenance Commands:
DBCC CLEANTABLE
DBCC INDEXDEFRAG
DBCC DBREINDEX
DBCC SHRINKDATABASE
DBCC DROPCLEANBUFFERS
DBCC SHRINKFILE
DBCC FREEPROCCACHE
DBCC UPDATEUSAGE

Miscellaneous: Miscellaneous tasks such as enabling trace flags or removing DLL file
from memory.
Miscellaneous Commands:
DBCC dllname
DBCC HELP

DBCC FREESESSIONCACHE
DBCC TRACEOFF
DBCC FREESYSTEMCACHE
DBCC TRACEON
Informational: Informational tasks that gather and display various types of information.
Informational Commands:
DBCC INPUTBUFFER
DBCC SHOWCONTIG
DBCC OPENTRAN
DBCC SQLPERF
DBCC OUTPUTBUFFER
DBCC TRACESTATUS
DBCC PROCCACHE
DBCC USEROPTIONS
DBCC SHOW_STATISTICS
Validation: Validation operations on a database, index, table, catalog etc.
Validation Commands:
DBCC CHECKALLOC
DBCC CHECKFILEGROUP
DBCC CHECKCATALOG
DBCC CHECKIDENT
DBCC CHECKCONSTRAINTS
DBCC CHECKTABLE
DBCC CHECKDB
19. What is Log shipping?

Log shipping defines the process for automatically taking backup of the database and
transaction files on a SQL Server and then restoring them on a standby/backup server.

This keeps the two SQL Server instances in sync with each other.

In case the production server fails, user simply needs to be pointed to the standby/backup
server.

Log shipping primarily consists of 3 operations:


1. Backup transaction logs of the production server.
2. Copy these logs on the standby/backup server.
3. Restore the log on standby/backup server.

20. What is the difference between a Local and a Global temporary table?

Temporary tables are used to allow short term use of the data in SQL Server.

They are of two types:


1. Local temporary table
2. Global temporary table.

Local temporary table


It is only available to the current database
connection for the current user.
They are cleared when the connection is
closed.
Multiple users cannot share a local temporary
table.

Global temporary table


Global temporary table is available to any
connection once it is created.
They are cleared when the last connection is
closed.
It can be shared by multiple users.

21. What is the STUFF? And how does it differ from the REPLACE function?
STUFF function:

The STUFF function inserts a string into another string.


It deletes a specified length of characters in the first string at the start position and then
inserts the second string into the first string at the start position.

STUFF Syntax:
STUFF (character_expression, start, length, replaceWith_expression)
REPLACE function:

The REPLACE function replaces all occurrences of a specified string value with another
string value.

Both STUFF and REPLACE function are used to replace the characters in a string.

REPLACE Syntax:
REPLACE (string_expression, string_pattern, string_replacement)
22. What are the rules to use the ROWGUIDCOL property to define a globally unique
identifier column?

Only one column can exist per table that is attached with ROWGUIDCOL property. One
can then use $ROWGUID instead of column name in select list.

23. What are the actions used to prevent once the referential integrity is enforced?
Actions prevented are:

Breaking of the relationship is used to prevent once the referential integrity is enforced on
a database.
Cannot delete a row from primary table if there are related rows in a secondary table.
Cannot update primary tables primary key if row being modified has related rows in
secondary table.
Cannot insert a new row in the secondary table if there are not related rows in the primary
table.
Cannot update secondary tables foreign key if there is no related row in the primary
table.

24. What are the commands available for summarizing the data in the SQL Server?
Commands for summarizing data in SQL Server:
Command
SUM

GROUP BY

Description
Returns the total sum of a
numeric value.
Returns the average value of a
numeric column.
Returns the number of rows of
a resultset.
Returns the maximum value
from a resultset.
Returns the minimum value
from a resultset.
Arrange resultset in groups.

ORDER BY

It sorts the resultset

AVG
COUNT
MAX
MIN

Syntax/Example
SELECT SUM(Sal) as Tot
from Table1;
SELECT AVG(Sal) as
Avg_Sal from Table1;
SELECT COUNT(*) from
Table1;
SELECT MAX(Sal) from
Table1;
SELECT MIN(Sal) from
Table1;
SELECT ZIP, City FROM
Emp GROUP BY ZIP
SELECT ZIP, City FROM
Emp ORDER BY City

25. List out the difference between CUBE operator and ROLLUP operator
CUBE Operator
It is an additional switch to GROUP BY

ROLLUP Operator
It is an extension to GROUP BY clause. It is

clause. It can be applied to all aggregation


functions to return cross tabular resultsets.
Produces all possible combinations of subtotal.

used to extract statistical and summarized


information from resultsets. It creates
groupings and then applies aggregation
functions on them.
Produces only some possible combinations of
subtotal.

26. What are the guidelines to use bulk copy program (BCP) utility of SQL Server?

BCP utility is an API that allows interacting with SQL Server to export/import data in one
of the two data formats.

To import data into a table, you must either use a format file created for that table or
understand the structure of the table and the types of data that are valid for its columns.

Bulk copy needs sufficient system credentials.


-

Need INSERT permissions on destination table while importing.


Need SELECT permissions on source table while exporting.
Need SELECT permissions on sysindexes, sysobjects and syscolumns tables.

27. What are the capabilities of cursors?


Capabilities of cursors:

Cursor reads every row one by one.


Cursors can be used to update a set of rows or a single specific row in a resultset
Cursors can be positioned to specific rows.
Cursors can be parameterized and hence are flexible.
Cursors lock row(s) while updating them.

28. What are the ways to control the cursor behavior?


There are two ways to control Cursor behavior:
1. Cursor types: The data access APIs usually specify the behavior of cursors by dividing
them into four cursor types:
1. Forward-only
2. Static
3. Keyset-driven
4. Dynamic

2. Cursor behaviors: The keywords such as SCROLL and INSENSITIVE along with the
cursor declaration define scrollability and sensitivity of the cursor.
29. What are the advantages of stored procedures?
Advantages of stored procedures:

They are easier to maintain and troubleshoot as they are modular.


Stored procedures are enabled for better tuning of performance.
Using stored procedure is much easier from a GUI end than building or using complex
queries.
They can be a part of separate layer which allows separating the concerns. Hence
Database layer can be handled by separate developers proficient in database queries.
It helps in reducing network usage.
It provides more scalability to an application.
Reusable and hence reduce code.

30. What are the ways to code efficient transactions?

Do not ask for an input from a user during a transaction.


Get all the input needed for a transaction before starting the transaction.
Transaction should be atomic.
Transaction should be as short and small as possible.
Rollback a transaction if a user intervenes and re-starts the transaction.
Transaction should involve a small amount of data as it needs to lock the number of rows
involved.
Avoid transactions while browsing through data.

31. What are the differences among batches, stored procedures, and triggers?
Batch
Collection or group of SQL
statements. All statements of a
batch are compiled into one
executional unit called
execution plan.

Stored Procedure
It is a collection or group of
SQL statements that is
compiled once but used many
times.

Triggers
It is a type of Stored procedure
that cannot be called directly.
Instead it fires when a row is
updated, deleted or inserted.

32. What security features are available for stored procedures?

Security features for stored procedures:

Grant user permission to execute a stored procedure irrespective of the related tables.
Grant user permission to work with a stored procedure to access a restricted set of data
yet no give them permissions to update or select underlying data.
Stored procedures can be granted and execute the permissions rather than setting
permissions on data itself.
It provides more granular security control through the stored procedures rather than
complete the control on underlying data in tables.

33. What are the instances when triggers are fire?


Scenarios for using triggers:

To create an audit log of database activity.


To apply business rules.
To apply some calculation on data from tables that is not stored in database.
To enforce referential integrity.
To alter the data in a third party application.
To execute the SQL statements as a result of an event or condition automatically.

34. What are the restrictions applicable while creating views?


Restrictions applicable while creating views:

A view cannot be indexed.


A view cannot be altered or renamed. Its columns cannot be renamed.
To alter a view, it must be dropped and re-created.
ANSI_NULLS and QUOTED_IDENTIFIER options should be turned on to create a
view.
All tables referenced in a view must be a part of the same database.
Any user defined functions referenced in a view must be created with
SCHEMABINDING option.
Cannot use ROWSET, UNION, TOP, ORDER BY, DISTINCT, COUNT (*), COMPUTE,
COMPUTE BY in views.

35. What are the events recorded in a transaction log?

Events recorded in a transaction log:

Broker event: It includes event produced by service broker.


Cursor event: It includes cursor operation events.
CLR event: It includes event fired by .Net CLR objects.
Database event: It includes events of data.log files shrinking or growing on their own.
Errors and Warning event: It includes SQL Server warnings and errors.
Full text event: It includes event that has occurred when text searches are started,
interrupted, or stopped.
Locks event: It includes event that are caused when a lock is acquired, released, or
cancelled.
Object event: It includes event of database objects which is being created, updated or
deleted.
OLEDB event: It includes event that are caused by OLEDB calls.
Performance event: It includes event that are caused by DML operators.
Progress report event: It includes online index operation events.
Scans event: It includes event notifying table/index scanning.
Security audit event: It includes audit server activities.
Server event: It includes server events.
Sessions event: It includes connecting and disconnecting events of clients to the SQL
Server.
Stored procedures event: It includes event of execution of stored procedures.
Transactions event: It includes event which is related to the transactions.
T-SQL event: It includes event that are generated while executing the T-SQL statements.
User configurable event: It includes user defined events.

36. Describe when checkpoints are created in a transaction log?


Activities causing checkpoints are:

When a checkpoint is explicitly executed.


A logged operation is performed on the database.
Database files have been altered using alter database command.
SQL Server has been stopped explicitly or on its own.
SQL Server periodically generates checkpoints.
Backup of a database is taken.

37. Define Truncate and Delete commands.

TRUNCATE
This is also a logged operation but in terms of
deallocation of data pages.
Cannot TRUNCATE a table that has foreign
key constraints.
It resets identity column to the default starting
value.
It removes all rows from a table.
Cannot be Rolled back.
DDL command

DELETE
This is a logged operation for every row.
Any row not violating a constraint can be
deleted.
It does not reset the identity column. Starts
where it left from last.
It is used to delete all or selected rows from a
table based on WHERE clause.
Need to Commit or Rollback
DML command

For more questions with answers, follow the link below:


http://www.careerride.com/SQLServer-Interview-Questions.aspx
We do not warrant the correctness of content. The risk from using it lies entirely with the user.
While using this document, you agree to have read and accepted the terms of use and privacy
policy.

You might also like