|
1. What are the steps you will take to improve performance of a poor performing query?
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.
2. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
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.
3. What is blocking and how would you troubleshoot it?
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.
Read up the following topics in SQL Server books online: Understanding and avoiding
blocking, Coding efficient transactions.
4. How to restart SQL Server in single user mode? How to start SQL Server in minimal
configuration mode?
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.
5. What are statistics, under what circumstances they go out of date, how do you
update them?
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
Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats
6. What are the different ways of moving data/databases between servers and databases
in SQL Server?
There are lots of options available. Some of the options are: BACKUP/RESTORE,
dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT,
SELECT...INTO, creating INSERT scripts to generate data.
7. Explain different types of BACKUPs avaialabe in SQL Server? Given a particular
scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database
backup, differential database backup, transaction log backup, filegroup backup.
Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared
to write the commands in your interview. Books online also has information on detailed
backup/restore architecture and when one should go for a particular kind of backup.
8. What is database replicaion? What are the different types of replication you can
set up in SQL Server?
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
9. 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.
10. What are cursors? Explain different types of cursors. What are the disadvantages
of cursors? How can you avoid cursors?
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
Another situation in which developers tend to use cursors: You need to call a stored
procedure when a column in a particular row meets certain condition. You don't have
to use cursors for this. This can be achieved using WHILE loop, as long as there
is a unique key to identify each row. For examples of using WHILE loop for row by
row processing, check out the 'My code library' section of my site or search for
WHILE.
11. Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online
for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
12. What is a join and explain different types of joins.
Joins are used in queries to explain how different tables are related.
Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified
as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
For more information see pages from books online titled: "Join Fundamentals" and
"Using Joins".
13. Can you have a nested transaction?
Yes
14. What is an extended stored procedure? Can you instantiate a COM object by using
T-SQL?
An extended stored procedure is a function within a DLL (written
in a programming language like C, C++ using Open Data Services (ODS) API) that can
be called from T-SQL, just the way we call normal stored procedures using the EXEC
statement. See books online to learn how to create extended stored procedures and
how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from
T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod,
sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM
object in VB and calling it from T-SQL, see 'My code library' section of this site.
15. What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(),
SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
16. What are triggers? How many triggers you can have on a table? How to invoke a
trigger on demand?
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.
17. What is a self join? Explain it with an example.
Self join is just like any other join, except that two instances
of the same table will be joined in the query.
18. Why are my insert, update statements failing with the following error?
Server: Msg 8152, Level 16, State 9, Line 1
String or binary data would be truncated.
The statement has been terminated.
This error occurs, when the length of the value entered by you
into a char, varchar, nchar, nvarchar column is longer than the maximum length of
the column. For example, inserting 'FAQ' into a char(2) column would result in this
error.
19. What is the T-SQL equivalent of IIF (immediate if/ternary operator) function
of other programming languages?
CASE is the equivalent of IIF function. See SQL Server Books Online
for more information. Here's a quick example: CREATE TABLE People ( [ID] int PRIMARY
KEY, [Name] varchar(25) NOT NULL, Sex bit NULL )
INSERT INTO People ([ID],[Name], Sex) VALUES (1,'John Dykes', 1)
INSERT INTO People ([ID],[Name], Sex) VALUES (2,'Deborah Crook', 0)
INSERT INTO People ([ID],[Name], Sex) VALUES (3,'P S Subramanyam', NULL)
SELECT [ID], [Name], CASE Sex WHEN 1 THEN 'Male' WHEN 0 THEN 'Female' ELSE 'Not
specified' END AS Sex FROM People
20. How to programmatically find out when the SQL Server service started?
Everytime SQL Server starts, it recreates the tempdb database.
So, the creation date and time of the tempdb database tells us the date and time
at which SQL Server service started. This information is stored in the crdate column
of the sysdatabases table in master database. Here's the query to find that out:
SELECT crdate FROM master.dbo.sysdatabases WHERE name = 'tempdb'
SQL Server error log also has this information (This is more accurate) and the error
log can be queried using xp_readerrorlog
21. How to get rid of the time part from the date returned by GETDATE function?
We have to use the CONVERT function to strip the time off the date.
Any of the following commands will do this:
SELECT CONVERT(char,GETDATE(),101)
SELECT CONVERT(char,GETDATE(),102)
SELECT CONVERT(char,GETDATE(),103)
SELECT CONVERT(char,GETDATE(),1)
22. How to get the first day of the week, last day of the week and last day of the
month using T-SQL date functions?
DECLARE @Date datetime
SET @Date = '2001/08/31'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the week'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 7),@Date) AS 'Last day of the week'
SELECT DAY(DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS 'Last day
of the month'
23. How to pass a table name, column name etc. to the stored procedure so that I
can dynamically select from a table?
Basically, SELECT and other commands like DROP TABLE won't let
you use a variable instead of a hardcoded table name. To overcome this problem,
you have to use dynamic sql. But dynamic SQL has some disadvantages. It's slow,
as the dynamic SQL statement needs to be parsed everytime it's executed. Further,
the user who is executing the dynamic SQL string needs direct permissions on the
tables, which defeats the purpose of having stored procedures to mask the underlying
tables. Having said that, here are some examples of dynamic SQL: (Also see sp_executesql
in SQL Server Books Online)
CREATE PROC SelectTable @Table sysname AS EXEC ('SELECT * FROM ' + @Table)
GO
EXEC SelectTable 'MyTable'
24. How to save the output of a query/stored procedure to a text file using T-SQL?
T-SQL by itself has no support for saving the output of queries/stored
procedures to text files. But you could achieve this using the command line utilities
like isql.exe and osql.exe. You could either invoke these exe files directly from
command prompt/batch files or from T-SQL using the xp_cmdshell command. Here are
the examples:
From command prompt:
osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC sp_who2" -o "E:\output.txt"
From T-SQL:
EXEC master..xp_cmdshell 'osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC
sp_who2" -o "E:\output.txt"'
Query Analyzer lets you save the query output to text files manually. The output
of stored procedures that are run as a part of a scheduled job, can also be saved
to a text file.
BCP and Data Transformation Services (DTS) let you export table data to text files.
25. How to join tables from different databases?
You just have to qualify the table names in your SELECT queries
with database name, followed by table owner name. In the following example, Table1
from pubs database and Table2 from northwind database are being joined on the column
i. Both tables are owned by dbo.
SELECT a.i, a.j FROM pubs.dbo.Table1 a INNER JOIN northwind.dbo.Table2 b ON a.i
= b.i
26. How to join tables from different servers?
To be able to join tables between two SQL Servers, first you have
to link them. After the linked servers are setup, you just have to prefix your tables
names with server name, database name, table owner name in your SELECT queries.
The following example links SERVER_01 to SERVER_02. Execute the following commands
in SERVER_02:
EXEC sp_addlinkedserver SERVER_01
GO
/* The following command links 'sa' login on SERVER_02 with the 'sa' login of SERVER_01
*/
EXEC sp_addlinkedsrvlogin @rmtsrvname = 'SERVER_01', @useself = 'false', @locallogin
= 'sa', @rmtuser = 'sa', @rmtpassword = 'sa password of SERVER_01'
GO
SELECT a.title_id FROM SERVER_01.pubs.dbo.titles a INNER JOIN SERVER_02.pubs.dbo.titles
b ON a.title_id = b.title_id
GO
27. How to convert timestamp data to date data (datetime datatype)?
The name timestamp is a little misleading. Timestamp data has nothing
to do with dates and times and can not be converted to date data. A timestamp is
a unique number within the database and is equivalent to a binary(8)/varbinary(8)
datatype. A table can have only one timestamp column. Timestamp value of a row changes
with every update of the row. To avoid the confusion, SQL Server 2000 introduced
a synonym to timestamp, called rowversion.
|