Вы находитесь на странице: 1из 38

Question: What is Cascade and Restrict when we use DROP table in SQL SERVER ?

Answer:- When we are using Drop table in SQL the syntax is simple.
Drop table table_name(CASCADE / RESTRICT)
We use cascade to drop table although it have some dependencies just like
triggers,stroeprocrdure,primarykey,foreignkey it will delete first.
But if we use restrict a error message is shown on using of DROP if the table have relation

Question: Some Tips when Optimizing Sql Server 2005 Query ?

Answer: Here are some important tips regarding Sql server 2005 query.
1. Turn on the execution plan, and statistics
2. Use Clustered Indexes
3. Use Indexed Views
4. Use Covering Indexes
5. Keep your clustered index small. 6. Avoid cursors
7. Archive old data
8. Partition your data correctly
9. Remove user-defined inline scalar functions
10. Use APPLY
11. Use computed columns
12. Use the correct transaction isolation level

Question: What is SQL whats its uses and its component ?

Answer: The Structured Query Language (SQL) is foundation for all relational database systems.
Most of the large-scale databases use the SQL to define all user and administrator interactions. QL is
Non-Procedural language . Its allow the user to concentrate on specifying what data is required rather
than concentrating on the how to get it.

The DML component of SQL comprises four basic statements:

* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables

Question: What is SQL Cache Dependency in ASP.NET 2.0?

Answer: SQL cache dependencies is new technique in ASP.NET 2.0 which can automatically
invalidate a cached data object just like a Dataset. when the related data is modified in the database.
So for instance if you have a dataset which is tied up to a database tables any changes in the
database table will invalidate the cached data object which can be a dataset or a data source.To
enable this we need a syntax that is as follows:- aspnet_regsql -ed -E -d Northwind

Question: How many kind of User-Defined Functions can be created in Sql Server-2000 ?
Answer: There are three types of User-Defined functions in SQL Server 2000 and they are Scalar,
Inline Table-Valued and Multi-statement Table-valued.A Scalar user-defined function returns one of
the scalar data types.An Inline Table-Value user-defined function returns a table data type.A Multi-
Statement Table-Value user-defined function returns a table.

Question: How many types of local tables in SQL SERVER ?

Answer: There are 2 types of temporary tables, local and global. Local temporary tables are created
using a single pound (#) sign and are visible to a single connection and automatically dropped when
that connection ends. Global temporary tables are created using a double pound (##) sign and are
visible across multiple connections and users and are automatically dropped when all SQL sessions
stop referencing the global temporary table.

Question: How to load .NET code in SQL SERVER 2005 ?

Answer: First of all write managed code and compile it to DLL/Assembly.Now we can load the
assembly in SQL SERVER.Here i have given a example of SQL SERVER. CREATE ASSEMBLY
percode FROM 'c:/percode.dll'
Question: Where .NET CLR and SQL SERVER run ?
Answer: All .net realtes application and Sql Server runs in same process or we can say that on same
address because there is no issue of speed because if these two process are run in different process
then there may be a speed issue created one process goes fast and other slow may create the

Question: What are Checkpoint in SQL Server ?

Answer: When we done operation on SQL SERVER that is not commited directly to the database.All
operation must be logged in to Transaction Log files after that they should be done on to the main
database.CheckPoint are the point which alert Sql Server to save all the data to main database if no
check point is there then log files get full we can use Checkpoint command to commit all data in the
SQL SERVER.When we stop the SQL Server it will take long time because Checkpoint is also fired.

Question: Can You explain integration between SQL Server 2005 and Visual Studio 2005 ?
Answer: This intergration provide wider range of development with the help of CLR for database
server.Becasue CLR helps developers to get flexibility for developing database applications and also
provides language interoperability just like Visual C++, Visual Basic .Net and Visual C# .Net. The
CLR helps developers to get the arrays, classes and exception handling available through
programming languages such as Visual C++ or Visual C# which is use in stored procedures,
functions and triggers for creating database application dynamically and also provide more efficient
reuse of code and faster execution of complex tasks. We particularly liked the error-checking powers
of the CLR environment, which reduces run-time errors

Question: What is the diffrence between SQL and Pl/Sql ?

Answer: We can get modify, Retrieve by single command or statement in SQL but PL/SQL process
all SQL statements one at a time. With PL/SQL, an entire block of statements process in a single
command line.sql is structured query language ,various queries are used to handle the database in a
simplified manner. while pl/sql is procedural language contains various types of variable,functions
and procedures and other major diffrence is Sql as the name suggest it is just structured query
language wheareas PLSQL is a commbination of Programming language & SQL.

Question: What is DTS in SQL Server ?

Answer: If a organization is big then it is also there that there is multiple option to store data some
people are using EXCEL some are using ACCESS and some of they are using SQL SERVER and in
some other format also but there a problem is arise that how to merge that data into one format there
is diffrent tool are there for doing this funtion. One of product of SQL SERVER-2000 DTS helps in this
problem it provides a set of tool from that tool we can customise are database acording to our need
DTSRun is a command-prompt utility used to execute existing DTS packages.

Question: What is the difference between UNION ALL Statement and UNION ?
Answer:- The main difference between UNION ALL statement and UNION is UNION All statement is
much faster than UNION,the reason behind this is that because UNION ALL statement does not look
for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or
not they exist.

Question: Write some disadvantage of Cursor ?

Answer:- Cursor plays there row quite nicely but although there are some disadvantage of Cursor .
Because we know cursor doing roundtrip it will make network line busy and also make time
consuming methods. First of all select query gernate output and after that cursor goes one by one so
roundtrip happen.Another disadvange of cursor are ther are too costly because they require lot of
resources and temporary storage so network is quite busy.

Question: What is Log Shipping and its purpose ?

Answer: In Log Shipping the transactional log file from one server is automatically updated in backup
database on the other server and in the case when one server fails the other server will have the
same DB and we can use this as the DDR(disaster recovery) plan.
Question: What are the null values in SQL SERVER ?
Answer: Before understand the null values we have some overview about what the value is. Value is
the actual data stored in a particular field of particular record. But what is done when there is no
values in the field.That value is something like <null>.Nulls present missing information. We can also
called null propagation.

Question: What is difference between OSQL and Query Analyzer ?

Answer: Both are same for functioning but there is a little difference OSQL is command line tool
which execute query and display the result same a Query Analyzer do but Query Analyzer is
graphical.OSQL have not ability like Query Analyzer to analyze queries and show statistics on speed
of execution .And other useful thing about OSQL is that its helps in scheduling which is done in Query
Analyzer with the help of JOB.

Question: Write a Role of Sql Server 2005 in XML Web Services?

Answer:- SQL Server 2005 create a standard method for getting the database engine using SOAP
via HTTP. By this method, we can send SOAP/HTTP requests to SQL Server for executing T-SQL
batch statements, stored procedures, extended stored procedures, and scalar-valued user-defined
functions may be with or without parameters.

Question: What are the different types of Locks ?

Answer: There are three main types of locks that SQL Server
(1)Shared locks are used for operations that does not allow to change or update data, such as a
SELECT statement.
(2)Update locks are used when SQL Server intends to modify a page, and later promotes the update
page lock to an exclusive page lock before actually making the changes.
(3)Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or

Question: Explain some SQL Server 2000 Query?

Answer: Here are some sql server 2000 query like Sql Insert Query, Delete Sql Query, Update Sql
Query and Sql Create Query:
1) Sql Insert Query:
a) How to encrypt data by using Sql Insert Query.
--: insert into table_name(Tablecolumn1, tablecolumn2,. . . . .) values ('value1',
pwdencrypt('value'),. . . .)

b) How to copy data from one table to another with the help of Sql Insert Query.
--: insert into table_name(column1,column2,. . . . ) select column1, column2, . . . . from table_name2

c) Sql Insert Query using where clause

--: insert into tablename(column1,column2) select column1,column2 from tablename2 where

Question: What is 'Write-ahead log' in Sql Server 2000 ?

Answer: Before understanding it we must have an idea about the transaction log files. These files are
the files which holds the data for change in database .
Now we explain when we are doing some Sql Server 2000 query or any Sql query like Sql insert
query,delete sql query,update sql query and change the data in sql server database it cannot change
the database directly to table .Sql server extracts the data that is modified by sql server 2000 query or
by sql query and places it in memory.Once data is stores in memory user can make changes to that a
log file is gernated this log file is gernated in every five mintues of transaction is done. After this sql
server writes changes to database with the help of transaction log files. This is called Write-ahead

Question: What do u mean by Extents and types of Extends ?

Answer: An Extent is a collection of 8 sequential pages to hold database from becoming fregmented.
Fragment means these pages relates to same table of database these also holds in indexing. To
avoid for fragmentation Sql Server assign space to table in extents. So that the Sql Server keep upto
date data in extents. Because these pages are continously one after another. There are usually two
types of extends:-Uniform and Mixed.
Uniform means when extent is own by a single object means all collection of 8 ages hold by a single
extend is called uniform.
Mixed mean when more then one object is comes in extents is known as mixed extents.

Question: What is different in Rules and Constraints ?

Answer: Rules and Constraints are similar in functionality but there is a An little diffrence between
them.Rules are used for backward compatibility . One the most exclusive diffrence is that we an bind
rules to a datatypes whereas constraints are bound only to columns.So we can create our own
datatype with the help of Rules and get the input according to that.

Question: What is defaults in Sql Server and types of Defaults ?

Answer: Defaults are used when a field of columns is allmost common for all the rows for example in
employee table all living in delhi that value of this field is common for all the row in the table if we set
this field as default the value that is not fill by us automatically fills the value in the field its also work
as intellisense means when user inputing d it will automatically fill the delhi . There are two types of
defaults object and definations.
Object deault:-These defaults are applicable on a particular columns . These are usually deined at
the time of table designing.When u set the object default field in column state this column in
automatically field when u left this filed blank.
Defination default:-When we bind the datatype with default let we named this as dotnet .Then every
time we create column and named its datatype as dotnet it will behave the same that we set for
dotnet datatype.

Question: What Is Database ?

Answer: A database is similar to a data file in that it is a storage place for data. Like a data file, a
database does not present information directly to a user; the user runs an application that accesses
data from the database and presents it to the user in an understandable format.Database systems
are more powerful than data files in that data is more highly organized. In a well-designed database,
there are no duplicate pieces of data that the user or application must update at the same time.
Related pieces of data are grouped together in a single structure or record, and relationships can be
defined between these structures and records.When working with data files, an application must be
coded to work with the specific structure of each data file. In contrast, a database contains a catalog
that applications use to determine how data is organized. Generic database applications can use the
catalog to present users with data from different databases dynamically, without being tied to a
specific data format. A database typically has two main parts: first, the files holding the physical
database and second, the database management system (DBMS) software that applications use to
access data. The DBMS is responsible for enforcing the database structure, including: · Maintaining
relationships between data in the database. Ensuring that data is stored correctly, and that the rules
defining data relationships are not violated. · Recovering all data to a point of known consistency in
case of system failures.

Question: what is Relational Database ?

Answer: Although there are different ways to organize data in a database, relational databases are
one of the most effective. Relational database systems are an application of mathematical set theory
to the problem of effectively organizing data. In a relational database, data is collected into tables
(called relations in relational theory). A table represents some class of objects that are important to an
organization. For example, a company may have a database with a table for employees, another
table for customers, and another for stores. Each table is built of columns and rows (called attributes
and tuples in relational theory). Each column represents some attribute of the object represented by
the table. For example, an Employee table would typically have columns for attributes such as first
name, last name, employee ID, department, pay grade, and job title. Each row represents an
instance of the object represented by the table. For example, one row in the Employee table
represents the employee who has employee ID 12345. When organizing data into tables, you can
usually find many different ways to define tables. Relational database theory defines a process called
normalization, which ensures that the set of tables you define will organize your data effectively.
Question: What is COMMIT & ROLLBACK statement in SQL ?
Answer: Commit statement helps in termination of the current transaction and do all the changes that
occur in transaction persistent and this also commits all the changes to the database.COMMIT we
can also use in store procedure.
ROLLBACK do the same thing just terminate the currenct transaction but one another thing is that the
changes made to database are ROLLBACK to the database.

Question:-What is diffrence between OSQL and Query Analyzer ?

Answer:-Both are the same but ther eis little diffrence OSQL is command line tool whic is execute
qery and display the result same a query analyzer but query analyzer is graphical and OSQL is a
command line tool.OSQL have not ability like query analyzer to analyze queries and show statics on
speed of execution and other usefull thing about OSQL is that its helps in scheduling.

Question: What is Data Integrity and it's categories ?

Answer: Enforcing data integrity ensures the quality of the data in the database. For example, if an
employee is entered with an employee_id value of 123, the database should not allow another
employee to have an ID with the same value. If you have an employee_rating column intended to
have values ranging from 1 to 5, the database should not accept a value of 6. If the table has a
dept_id column that stores the department number for the employee, the database should allow only
values that are valid for the department numbers in the company. Two important steps in planning
tables are to identify valid values for a column and to decide how to enforce the integrity of the data in
the column. Data integrity falls into these categories:
1) Entity integrity
2) Domain integrity
3) Referential integrity
4) User-defined integrity
Entity Integrity: Entity integrity defines a row as a unique entity for a particular table. Entity integrity
enforces the integrity of the identifier column(s) or the primary key of a table (through indexes,
UNIQUE constraints, PRIMARY KEY constraints, or IDENTITY properties).
Domain Integrity: Domain integrity is the validity of entries for a given column. You can enforce
domain integrity by restricting the type (through data types), the format (through CHECK constraints
and rules), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints,
DEFAULT efinitions, NOT NULL definitions, and rules).
Referential Integrity: Referential integrity preserves the defined relationships between tables when
records are entered or deleted. In Microsoft® SQL Server™ 2000, referential integrity is based on
relationships between foreign keys and primary keys or between foreign keys and unique keys
(through FOREIGN KEY and CHECK constraints). Referential integrity ensures that key values are
consistent across tables. Such consistency requires that there be no references to nonexistent values
and that if a key value changes, all references to it change consistently throughout the database.
When you enforce referential integrity, SQL Server prevents users from:
· Adding records to a related table if there is no associated record in the primary table.
· Changing values in a primary table that result in orphaned records in a related table.
· Deleting records from a primary table if there are matching related records.
For example, with the sales and titles tables in the pubs database, referential integrity is based on the
relationship between the foreign key (title_id) in the sales table and the primary key (title_id) in the
titles table.
User-Defined: Integrity User-defined integrity allows you to define specific business rules that do not
fall into one of the other integrity categories. All of the integrity categories support user-defined
integrity (all column- and table-level constraints in CREATE TABLE, stored procedures, and triggers).

Question: SQL Server runs on which TCP/IP port and From where can you change the default
Answer: SQL Server runs on port 1433 but we can also change it for better security and From the
network Utility TCP/IP properties -->Port number.both on client and the server.

Question: What is the use of DBCC commands?

Answer: DBCC stands for database consistency checker. We use these commands to check the
consistency of the databases, i.e., maintenance, validation task and status checks.DBCC CHECKDB
- Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC To
check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current
usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for
any damage.

Question: What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Answer: Having Clause is basically used only with the GROUP BY function in a query. WHERE
Clause is applied to each row before they are part of the GROUP BY function in a query.

Question: When do you use SQL Profiler?

Answer: SQL Profiler utility allows us to basically track Connections to the SQL Server and also
determine activities such as which SQL Scripts are running, failed jobs etc.

Question: Can you explain the role of each service?

Answer: SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs,
DB Maintenance, Backups DTC - Is for linking and connecting to other SQL Servers.

Question: What is Normalization ?

Answer: The logical design of the database, including the tables and the relationships between them,
is the core of an optimized relational database. A good logical database design can lay the foundation
for optimal database and application performance. A poor logical database design can impair the
performance of the entire system.

Normalizing a logical database design involves using formal methods to separate the data into
multiple, related tables. A greater number of narrow tables (with fewer columns) is characteristic of a
normalized database. A few wide tables (with more columns) is characteristic of an nonnomalized
database. Reasonable normalization often improves performance. When useful indexes are
available, the Microsoft® SQL Server™ 2000 query optimizer is efficient at selecting rapid, efficient
joins between tables.

Some of the benefits of normalization include:

·Faster sorting and index creation.
·A larger number of clustered indexes. For more information, Narrower and more compact indexes.
·Fewer indexes per table, which improves the performance of INSERT, UPDATE, and DELETE
·Fewer null values and less opportunity for inconsistency, which increase database compactness.

As normalization increases, so do the number and complexity of joins required to retrieve data. Too
many complex relational joins between too many tables can hinder performance. Reasonable
normalization often includes few regularly executed queries that use joins involving more than four

Sometimes the logical database design is already fixed and total redesign is not feasible. Even then,
however, it might be possible to normalize a large table selectively into several smaller tables. If the
database is accessed through stored procedures, this schema change could take place without
affecting applications. If not, it might be possible to create a view that hides the schema change from
the applications.

Question: Can you explain what View is in SQL ?

Answer: View is just a virtual table nothing else which is based or we can say devlop with SQL
SELECT query.So we can say that its a real database table (it has columns and rows just like a
regular table),but one difference is that real tables store data,but views can’t. View data is generated
dynamically when the view is referenced.And view can also references one or more existing
database tables or other views. We can say that it is filter of database.

Question: How to get which Process is Blocked in SQL SERVER ?

Answer:- There are two ways to get this sp_who and sp_who2 . You cannot get any detail about the
sp_who2 but its provide more information then the sp_who . And other option from which we can find
which process is blocked by other process is by using Enterprise Manager or Management Studio,
these two commands work much faster and more efficiently than these GUI-based front-ends.

Question: Can you tell me the difference between DELETE &TRUNCATE commands?
Answer: Delete command removes the rows from a table based on the condition that we provide
with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no
data in the table after we run the truncate command.

Emp Table
Cloumn Name Data Type
Name Varchar(50)
ID Int
Address Varchar(100)
Sex Char

Question: Write an Sql Query to Database Integrity for Databases of Server ?

Answer: EXEC sp_msforeachdb ‘DBCC CHECKDB(”?”)’

Question: Write an Sql Query for getting detail of database and rows ?

Question: Write an Sql Query using case ?

Answer: SELECT * FROM tablename WHERE name ='Pervej' ORDER BY CASE WHEN
@OrderDirection = ‘DESC’ THEN OrderQty END DESC, CASE WHEN @OrderDirection = ‘ASC’

Question: Write an Sql Query to get total rows and detail of table rows ?

Question: Write an Sql Insert Query ?

Answer: Insert SQL query:- Insert queries are designed to insert new rows of data in a table.This
insert queries use T-SQL insert statement to insert data.Insert statement is simple then the other two
DML statement Delete and update statement. Insert statement can isert multiple rows of data if we
use derived table to get the record from he other table.
Example of Insert Sql Query:

Inserting Rows.
The INSERT statement has two distinct variations the first, and simplest, inserts a single row into the
named table. Here are some simple Insert query to insert data in Emp table:

(I) INSERT INTO tablename [( column-list )] VALUES ( constant-list ) ;

Inset into emp(name,id,address,sex) values(‘DotNet’,1,’New York’,’M’);

Inset into emp(name,id,address,sex) values(‘Net’,2,’India’,’F’);
Inset into emp(name,id,address,sex) values(‘Question’,3,’England’,’M’);
after executing we get the records in the table.

we use single ' ' to insert char or varchar type datatype in the table.Onse more thing about insert
query if we not supply column list in the query sql insert values into every column in the table.

Emp Table
Name ID Address Sex
DotNet 1 New York M
Net 2 India F
Question 3 England M

Insert multiple rows from one table to another table:

(II) Insert into table_name(name,id,address,sex) select name,id,address,sex from emp;

Question: Write an Update Sql Query ?

Answer: Update Sql Query:- Update statement logged if we are replacing or modifying large blocks
of text or image data, use the WRITETEXT or UPDATETEXT statement instead of the UPDATE
statement. The WRITETEXT and UPDATETEXT statements (by default) are not logged.

Update Sql query is used to modify some records in the table and also use some condition:-
The UPDATE statement consists of three clauses:
UPDATE table_name
SET column-list(for update)
WHERE cond-expression ;

(i)Update emp set name=’Pervej’,address=’sonipat’,sex=’M’ where id=1;

Emp Table
Name ID Address Sex
Pervej 1 Sonipat M
Net 2 India F
Question 3 England M

Question: Write an Delete Sql Query ?

Answer: Delete SQL query:- DELETE only affect one table at a time, you cannot use DELETE with a
view that has a FROM clause naming more than one table.

Deleting Rows:

The general form of the DELETE statement is

DELETE FROM tablenameWHERE conditional-expression

The DELETE statement removes those rows from a given table that satisfy the condition specified in
the WHERE clause.

(I)delete from emp where id=2;

after executing we get the output.

Emp Table
Name ID Address Sex
DotNet 1 New York M
Question 3 England M

Here i have explain two functions ROW_NUMBER() ,RANK(),DENSE_RANK()

1 2
2 3
3 3
4 4
5 5

select COL1,COL2,row_number() over (order by COL2) as rownumber from DOTNET (output 1)

select COL1,COL2,rank() over (order by COL2) as rownumber from DOTNET(output 2)
select COL1,COL2,dense_rank() over (order by COL2) as rownumber from DOTNET(output 3)
and its

COL1 COL2 rownumber
1 2 1
2 3 2
3 3 3
4 4 4
5 5 5
output for the first query which relates to row_number()

COL1 COL2 rownumber
1 2 1
2 3 2
3 3 2
4 4 4
5 5 5
output for the first query which relates to rank()

COL1 COL2 rownumber
1 2 1
2 3 2
3 3 2
4 4 3
5 5 4
output for the first query which relates to dense_rank()

To delete all the records from table

(II)delete from emp;

Question: Write an query to count number of row in table (count)?

Answer:- (i)select count(*) from emp
(ii)SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2
we can also put column name in place of '*'.
Question: How to know how many tables contains name as a column in a database ?
Answer:- SELECT COUNT(*) AS Counter FROM syscolumns WHERE (name = 'name') '.

Question: Write a query to convert all the letters in a word to upper case ?
Answer:- SELECT UPPER('dotnet').

Question: Write query to round up a number. For example even if the user enters 4.1 it should
be rounded up to 5?
Answer:- SELECT CEILING (4.1).

Question: Write query to get datetime in different format ?

Answer:- select convert(varchar, getdate(), 1)
Output:- 12/30/06
select convert(varchar, getdate(), 2)
Output:- 06.12.30
select convert(varchar, getdate(), 3)
Output:- 30/12/06
select convert(varchar, getdate(), 4)
select convert(varchar, getdate(), 5)
select convert(varchar, getdate(), 6)
Output:-30 Dec 06
select convert(varchar, getdate(), 7)
Output:-Dec 30, 06
select convert(varchar, getdate(), 10)
select convert(varchar, getdate(), 11)
select convert(varchar, getdate(), 101)
select convert(varchar, getdate(), 102)
select convert(varchar, getdate(), 103)
select convert(varchar, getdate(), 104)
select convert(varchar, getdate(), 105)
select convert(varchar, getdate(), 106)
Output:-30 Dec 2006
select convert(varchar, getdate(), 107)
Output:-Dec 30, 2006
select convert(varchar, getdate(), 110)
select convert(varchar, getdate(), 111)
select convert(varchar, getdate(), 8)
select convert(varchar, getdate(), 9)
Output:- Dec 30 2006 12:38:54:840AM
select convert(varchar, getdate(), 14)
Output:- 00:38:54:840

Question: Write a query when we need a common row between two tables ?
Answer:- We use intersect to do this
SELECT col1,col2,col3 FROM table1
SELECT col1,col2,col3 FROM table2

Question: Write a query when we need a copy structure of one table to another table or you
can say example of cloneing ?
Answer:- select * into tabel1 from table2

Question: Write a query when we need a row that are not common between two tables ?
Answer:- We use EXCEPT to do this
SELECT col1,col2,col3 FROM table1
SELECT col1,col2,col3 FROM table2

Question: Find top salary among two tables (table1,table2) ?

MAX(sal) AS sal FROM table2) a ORDER BY sal DESC

Question: Write an query to get Max,Min,Second max number from the table?
Answer:- (i) select max(id) from emp
we can get the max id value from this query .
(ii) select min(id) from emp
we can get min id value fom the table emp.
(iii)select max(id) from emp where id<(select max(id) from emp)
this query is combinination of two sql query.

Q.1 What is the Maximum number of input and output parameters in Stored procedure in SQL
Server 2000 ?
A. 1024

Q.2 how many system datatypes are in SQL Server.

A. 27

Q.3 What ODS API Stands For ?

A. Open Data Services API

Q.4 What are the difference in MSSQL Server 2000 and its previous version 7.0?
A. there are many differences which can be seen in "whats new in SQL Server 2000" topic of the
BOL available wid MSSQL Server 2000 installation , few major are given below

• OLAP services in 7.0 is now names SQL Server 2000 Analysis Services , Analysis Services
also includes a new data mining component
• SQL Server 2000 introduces support for XML
• The programmability of Transact-SQL can be extended by creating your own Transact-SQL
functions. A user-defined function can return either a scalar value or a table
• INSTEAD OF and AFTER Triggers
INSTEAD OF triggers are executed instead of the triggering action (for example, INSERT,
UPDATE, DELETE). They can also be defined on views, in which case they greatly extend
the types of updates a view can support. AFTER triggers fire after the triggering action. SQL
Server 2000 introduces the ability to specify which AFTER triggers fire first and last.
• Cascading Referential Integrity Constraints
You can control the actions SQL Server 2000 takes when you attempt to update or delete a
key to which existing foreign keys point. This is controlled by the new ON DELETE and ON
UPDATE clauses in the REFERENCES clause of the CREATE TABLE and ALTER TABLE
• Support for multiple instances
SQL Server 2000 supports running multiple instances of the relational database engine on the
same computer. Each computer can run one instance of the relational database engine from
SQL Server version 6.5 or 7.0, along with one or more instances of the database engine from
SQL Server 2000. Each instance has its own set of system and user databases
• Support for creating indexes on Computed Columns
• 64 GB Memory Support
Microsoft SQL Server 2000 Enterprise Edition can use the Microsoft Windows 2000 Advanced
Windows Extension (AWE) API to support up to 64 GB of physical memory (RAM) on a

Q.5 How many dataype SQL Server 2000 Supports for date & time
A SQL server 2000 supports two datatypes for storing date and time :
datetime and smalldatetime

Q.6 How can you generate GUID in in Transact-SQL ?

A. GUIDs can be generated using the NEWID function.

Q.7 How many type of authentication method are there in SQL Server 2000
A. There are two type of authentication method in SQL Server 2000

Q.8 Whats the Difference between datetime and smalldatetime datatype in SQL Server 2000 .
A . The main difference between these two datatypes is in the amount of space they occupy.
datetime occupies eight bytes and smalldatetime only four. The difference in size is due to a
difference in precision. The precision of smalldatetime is one minute, and it covers dates from
January 1, 1900 , through June 6, 2079 , which is usually more than enough. The precision of
datetime is 3.33 ms, and it covers dates from January 1, 1753 , to December 31, 9999 .

Q.9. Can a user defined function return table ?

A. it is possible to design a user-defined function that returns a table.

Q.10. Whats is the nesting limit of Sql Server stored procedure.

A. SQL Server 2000 have a limit of 32 stored procedure nesting levels.

Q.11 How many type of triggers are there in Sql Server 2000.
A. There are two type of triggers
• After Triggers
• Instead of Triggers

Q.12 In how many ways you can recieve information from stored procedure
A. there are 4 ways to receive information from a stored procedure:
Resultset , Parameters , Return value , A global cursor that can be referenced outside the stored

Q.13 What are the limits of Sql Server 2000.

A.When you are creating or changing a stored procedure,please keep in mind that
The name of the procedure is a standard Transact-SQL identifier. The maximum length of any
identifier is 128 characters.
Stored procedures may contain up to 1,024 input and output parameters.
The body of the stored procedure consists of one or more
Transact-SQL statements. The maximum size of the body of the stored procedure is 128MB.

Q.14 Whats the limitation of user defined funtion ?

A User-defined functions have one serious limitation. They cannot have side effects. A function side
effect is any permanent change to resources (such as tables) that have a scope outside of the
function (such as a non-temporary table that is not declared in the function). Basically, this
requirement means that a function should return a value while changing nothing in the database. it
means in short that "user defined function can not use UPDATE / DELETE on permament table
objects in MSSQL"
Q.15 what is @@Fetch_status ?
A. @@fetch_status is a function (or global variable) that returns the success code of the last Fetch
statement executed during the current connection. It is often used as an exit criterion in loops that
fetch records from a cursor.

Q.16 How you can trap error in Sql Server 2000

A. by using @@error .
After each Transact-SQL statement, the server sets the variable to an integer value:
0—if the statement was successful
Error number—if the statement has failed

Q.17 How many type of Contraints are in MSSQL.

A. SQL Server 2000 supports five classes of constraints.

Q.18 How you can get the last identity value inserted in any table ?
A. SQL Server 2000 has a System Variable @@IDENTITY which gives the last identity element
value inserted in any table

Q.19 How many type of indexes are there ?

A. there are two type of indexes Clustered and Non-Clustured

Q.20 How many Index can be created on a table

A. 249 Non Clustured and 1 Clustered index

PS: the obove question answers are from various books and articles available on internet .
please use them on your own risk. [Last updated : 26-july-2006]

Q.1. What is the maximum size of an SQL Server 2000 Database?

A. The maximum size for SQL Server 2000 databases is 1,048,516 TB. Each database can contain
up to 32,767 files, and the maximum size of each file is 32TB

Q.2. how many database can be created on MSSQL Server 2000

A. 32767

Q.3. A database is consists of how many type of files ??

A. A database can consist of three types of file :
Primary file , Seconday file and transaction logs
The primary data file is the starting point of the database and points to any other files in the database.
If the primary file is not large enough to hold all the data in the database, then secondary files are
required.Transaction logs files hold records of updates to the data files, and can be used to recover
the database after an error. Every database has at least one transaction log file, and some databases
may have more than one.

Q.4. What are the extensions of these three type of file in above question.
A. The recommended file name extension for primary data files is .mdf.
The recommended file name extension for secondary data files is .ndf.
The recommended file name extension for log files is .ldf
Q.5. How many transaction Isolation Level are there in MSSQL Server 2000?
A.There are four isolation levels

Q.6. How many type of Locks are there ?

A. There are three main types of locks that SQL Server 7.0/2000 uses
Shared locks
Update locks
Exclusive locks

Q.7. What is a Dead Lock ?

A . Deadlock occurs when two users have locks on separate objects and each user wants a lock on
the other's object. For example, User1 has a lock on object "A" and wants a lock on object "B" and
User2 has a lock on object "B" and wants a lock on object "A". In this case, SQL Server ends a
deadlock by choosing the user, who will be a deadlock victim. After that, SQL Server rolls back the
breaking user's transaction, sends message number 1205 to notify the user's application about
breaking, and then allows the nonbreaking user's process to continue.
Note. To reduce the chance of a deadlock, you should minimize the size of transactions and
transaction times.

Q.8. How many instances can be there on a single machine of SQL Server ?
A. On a Single machine there can be 16 Instances running at a time.

Q.9. How many Recovery model are in SQL Server ?

A. There are thre recovery model in MSSQL Server 2000
• Simple Recovery Model .
• Full Recovery Model.
• Bulk Logged Recovery Model.

Q.10. what does the term Orphan user means ??

A.An orphan user is a user in a database with a SID that does not exist in the syslogins table in the
master database. Also if the SID stored in the database sysusers table, differs from SID stored in the
syslogin table for the matching database user, then the database user is also considered an orphan

Q.11 Whats is Log Shipping ?

A. Llog shipping is the process of backing up of database and transaction log files on a production
SQL server, and then restoring them onto a standby server. The key feature of log shipping is that it
will automatically backup transaction logs throughout the day (for whatever interval you specify) and
automatically restore them on the standby server. This in effect keeps the two SQL Servers in
"synch". Should the production server fail, all you have to do is point the users to the new server, and
you are all set. Well, its not really that easy, but it comes close if you put enough effort into your log
shipping setup.

Q.12. How many typf of backups are supported by MSSQL ?

A. there are three type of backup

• Full Database Backup.

• Transaction Log Backup
• Differential Backup

Q.13. What is replication ?

A. Replication is a process which enables data and database objects to be copied and modified from
one database to another across different networks and platforms.the physical seperation of the
databases and latency are integral part of the design process in replication. MSSQL Server 2000
permits 3 different kind of replication. they are snapshot,transactional and merge.

Q.14 What are the default databases in MSSQL Server Instance after Fresh installation
A. there are 4 default databases .

• Master
This is your most critical database, and is the core of your SQL Server implementation.
Limit changes and access to this database as much as possible. Without the master
database, your SQL Server instance will not start up.
This database contains tables that control and track the elements of the SQL Server
Agent, as well as replication, log shipping (Enterprise Edition), database backup and
restore history, database maintenance plan configurations and history, and a subset of
tables participating in replication status and jobs. DTS packages saved to SQL Server are
also stored within this database.
• Model
The model database is a template database, which, when modified, will affect the default
values of databases that are created in the future. For example, if a table is added to the
model database, future databases created for the SQL Server instance will include this
• Tempdb
The tempdb database is used to hold all temporary tables and temporary stored
procedures. SQL Server also uses it for internal sorting and query operations (called
work tables, or spooling). This database is re-created each time SQL Server is started,
and cannot be used to store permanent tables.

Q.15. How many access mode of database are in MSSQL

A there are three access mode of a database SINGLE_USER , RESTRICTED_USER and
MULTI_USER . SINGLE_USER mode restricts database access to one user Connection.
RESTRICTED_USER mode restricts database access to db_owner, dbcreator, and sysadmin roles.
All other users are disconnected.MULTI_USER mode lets all users with proper access connect to the

Q.16. What is mean by suspect status of a database ?

A. SQL Server gives a database 'suspect' status when it is unable to recover the database . reasons
may be many , may be a torn page detection , may be datafile location no found.

Q.17. What is mean by Torn Page?

A. SQL Server pages are 8KB. Windows 2000 disk I/O operations, however, use 512 byte sectors. If
an unexpected outage or power failure occurs, a 'torn' page can result, with the 8KB-page write not
completely written. Enabling the TORN_PAGE_DETECTION option allows SQL Server to detect
incomplete I/O operations. If a torn page occurs when the database is online, an I/O error is raised
and the connection is killed;

Q.18. how you can rename a database ?

A. To rename a database first get the database into Single user mode . by using the query below
( run these query in query analyzer)


then rename the database using sp_rename

sp_renamedb 'DBMydb', 'DBmydb_new'

then change the access mode of the database to multiuser


Q.19. How you can trap error in Sql Server 2000

A. by using @@error .
After each Transact-SQL statement, the server sets the variable to an integer value:
0—if the statement was successful
Error number—if the statement has failed

What are different normalization forms?

Answer Description:

1. 1NF: Eliminate Repeating Groups

Each set of related attributes should be in separate table, and give each table a primary key. Each
field contains at most one value from its attribute domain.

2. 2NF: Eliminate Redundant Data

1. Table must be in 1NF.

2. All fields are dependent on the whole of the primary key, or a relation is in 2NF if it is in 1NF
and every non-key attribute is fully dependent on each candidate key of the relation. If an attribute
depends on only part of a multi‐valued key, remove it to a separate table.

3. 3NF: Eliminate Columns Not Dependent On Key

1. The table must be in 2NF.

2. Transitive dependencies must be eliminated. All attributes must rely only on the primary key. If
attributes do not contribute to a description of the key, remove them to a separate table. All attributes
must be directly dependent on the primary key.

4. BCNF: Boyce‐Codd Normal Form

for every one of its non-trivial functional dependencies X → Y, X is a superkey—that is, X is either a
candidate key or a superset thereof. If there are non‐trivial dependencies between candidate key
attributes, separate them out into distinct tables.

5. 4NF: Isolate Independent Multiple Relationships

No table may contain two or more 1:n or n:m relationships that are not directly related.

For example, if you can have two phone numbers values and two email address values, then you
should not have them in the same table.

6. 5NF: Isolate Semantically Related Multiple Relationships

A 4NF table is said to be in the 5NF if and only if every join dependency in it is implied by the
candidate keys. There may be practical constrains on information that justify separating logically
related many‐to‐many relationships.

Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first
fulfill all the criteria of a 2NF and 1NF database.
(Q) What is a Database or Database Management System (DBMS)?

Twist: What is the difference between a file and a database? Can files qualify as a database?

Note: Probably these questions are too basic for experienced SQL SERVER guys. But from a
fresher’s point of view, it can be a difference between getting a job and being jobless.

1. Database provides a systematic and organized way of storing, managing and retrieving from a
collection of logically related information.
2. Secondly, the information has to be persistent, that means even after the application is closed
the information should be persisted.
3. Finally, it should provide an independent way of accessing data and should not be dependent
on the application to access the information.

Ok, let me spend a few more sentences on explaining the third aspect. Below is a simple figure of a
text file that has personal detail information. The first column of the information is Name, second
Address and finally Phone Number. This is a simple text file, which was designed by a programmer
for a specific application.

Figure 1.1: Non-Uniform Text File

It works fine in the boundary of the application. Now, some years down the line a third party
application has to be integrated with this file. In order for the third party application to be integrated
properly, it has the following options:

• Use the interface of the original application.

• Understand the complete details of how the text file is organized, example the first column is
Name, then Address and finally Phone Number. After analyzing, write a code which can read
the file, parse it etc. Hmm, lot of work, right.

That’s what the main difference is between a simple file and a database; database has an
independent way (SQL) of accessing information while simple files do not (That answers my twisted
question defined above). File meets the storing, managing and retrieving part of a database, but not
the independent way of accessing data.

Note: Many experienced programmers think that the main difference is that file cannot provide multi-
user capabilities which a DBMS provides. But if you look at some old COBOL and C programs where
files were the only means of storing data, you can see functionalities like locking, multi-user etc.
provided very efficiently. So it’s a matter of debate. If some interviewers think of this as a main
difference between files and database, accept it… going in to debate means probably losing a job.

(Just a note for fresher’s: Multi-user capabilities mean that at one moment of time more than one user
should be able to add, update, view and delete data. All DBMS' provides this as in-built
functionalities, but if you are storing information in files, it’s up to the application to write logic to
achieve these functionalities).

(Q) What is the Difference between DBMS and RDBMS?

As mentioned before, DBMS provides a systematic and organized way of storing, managing and
retrieving from a collection of logically related information. RDBMS also provides what DBMS
provides, but above that, it provides relationship integrity. So in short, we can say:


For example, in the above Figure 1.1, every person should have an Address. This is a referential
integrity between Name and Address. If we break this referential integrity in DBMS and files, it will not
complain, but RDBMS will not allow you to save this data if you have defined the relation integrity
between person and addresses. These relations are defined by using “Foreign Keys” in any RDBMS.

Many DBMS companies claimed that their DBMS product was RDBMS compliant, but according to
industry rules and regulations, if the DBMS fulfills the twelve CODD rules, it’s truly a RDBMS. Almost
all DBMS (SQL SERVER, ORACLE etc.) fulfill all the twelve CODD rules and are considered truly as

Note: One of the biggest debates is whether Microsoft Access is an RDBMS? We will be answering
this question in later section.

(DB)What are CODD Rules?

Twist: Does SQL SERVER support all the twelve CODD rules?

Note: This question can only be asked on two conditions when the interviewer is expecting you to be
at a DBA job or you are complete fresher, yes and not to mention the last one he treats CODD rules
as a religion. We will try to answer this question from the perspective of SQL SERVER.

In 1969, Dr. E. F. Codd laid down 12 rules, which a DBMS should adhere to in order to get the logo of
a true RDBMS.

Rule 1: Information Rule

"All information in a relational database is represented explicitly at the logical level and in exactly one
way - by values in tables."

In SQL SERVER, all data exists in tables and are accessed only by querying the tables.

Rule 2: Guaranteed Access Rule

"Each and every datum (atomic value) in a relational database is guaranteed to be logically
accessible by resorting to a combination of table name, primary key value and column name."

In flat files, we have to parse and know the exact location of field values. But if a DBMS is truly an
RDBMS, you can access the value by specifying the table name, field name, for instance
Customers.Fields [‘Customer Name’].
SQL SERVER also satisfies this rule. In ADO.NET we can access field information using table name
and field names.

Rule 3: Systematic Treatment of Null Values

"Null values (distinct from the empty character string or a string of blank characters and distinct from
zero or any other number) are supported in fully relational DBMS for representing missing information
and inapplicable information in a systematic way, independent of data type.”

In SQL SERVER, if there is no data existing, NULL values are assigned to it. Note NULL values in
SQL SERVER do not represent spaces, blanks or a zero value; it is a distinct representation of
missing information and thus satisfies rule 3 of CODD.

Rule 4: Dynamic On-line Catalog Based on the Relational Model

"The database description is represented at the logical level in the same way as ordinary data, so that
authorized users can apply the same relational language to its interrogation as they apply to the
regular data."

The Data Dictionary is held within the RDBMS. Thus, there is no need for off-line volumes to tell you
the structure of the database.

Rule 5: Comprehensive Data Sub-language Rule

"A relational system may support several languages and various modes of terminal use (for example,
the fill-in-the-blanks mode). However, there must be at least one language whose statements are
expressible, per some well-defined syntax, as character strings and that is comprehensive in
supporting all the following items:

• Data Definition
• View Definition
• Data Manipulation (Interactive and by program)
• Integrity Constraints
• Authorization
• Transaction boundaries ( Begin, commit and rollback)"

SQL SERVER uses SQL to query and manipulate data, which has a well-defined syntax and is being
accepted as an international standard for RDBMS.

Note: According to this rule, CODD has only mentioned that some language should be present to
support it, but not necessary that it should be SQL. Before the 80’s, different’s database vendors
were providing their own flavor of syntax until in 1980, ANSI-SQL came in to standardize this
variation between vendors. As ANSI-SQL is quite limited, every vendor including Microsoft introduced
their additional SQL syntax in addition to the support of ANSI-SQL. You can see SQL syntax varying
from vendor to vendor.

Rule 6: View-updating Rule

"All views that are theoretically updatable are also updatable by the system."

In SQL SERVER, not only views can be updated by the user, but also by SQL SERVER itself.

Rule 7: High-level Insert, Update and Delete

"The capability of handling a base relation or a derived relation as a single operand applies not only
to the retrieval of data, but also to the insertion, update and deletion of data."
SQL SERVER allows you to update views that in turn affect the base tables.

Rule 8: Physical Data Independence

"Application programs and terminal activities remain logically unimpaired whenever any changes are
made in either storage representations or access methods."

Any application program (C#, VB.NET, VB6, VC++ etc) does not need to be aware of where the SQL
SERVER is physically stored or what type of protocol it is using, the database connection string
encapsulates everything.

Rule 9: Logical Data Independence

"Application programs and terminal activities remain logically unimpaired when information-preserving
changes of any kind that theoretically permit un-impairment are made to the base tables."

Application programs written in C# or VB.NET do not need to know about any structure changes in
SQL SERVER database. Example: adding of new field etc.

Rule 10: Integrity Independence

"Integrity constraints specific to a particular relational database must be definable in the relational
data sub-language and storable in the catalog, not in the application programs."

In SQL SERVER, you can specify data types (integer, nvarchar, Boolean etc.) which put in data type
checks in SQL SERVER rather than through application programs.

Rule 11: Distribution Independence

"A relational DBMS has distribution independence."

SQL SERVER can spread across more than one physical computer and across several networks; but
from application programs, it has not a big difference but just specifying the SQL SERVER name and
the computer on which it is located.

Rule 12: Non-subversion Rule

"If a relational system has a low-level (single-record-at-a-time) language, that low level cannot be
used to subvert or bypass the integrity Rules and constraints expressed in the higher level relational
language (multiple-records-at-a-time)."

In SQL SERVER whatever integrity rules are applied on every record are also applicable when you
process a group of records using application program in any other language (example: C#, VB.NET,
J# etc.).

Readers can see from the above explanation that SQL SERVER satisfies all the CODD rules, some
database gurus consider SQL SERVER as not truly being an RDBMS, but that’s a matter of debate.

(Q) Is Access Database a RDBMS?

Access fulfills all rules of CODD, so from this point of view, yes it’s truly an RDBMS. However, many
people can contradict it as a large community of Microsoft professionals think that Access is not an

(Q) What is the Main Difference between ACCESS and SQL SERVER?
As mentioned before, Access fulfills all the CODD rules and behaves as a true RDBMS. But there’s a
huge difference from an architecture perspective, due to which many developers prefer to use SQL
SERVER as the major database rather than Access. Following is the list of architecture differences
between them:

• Access uses file server design and SQL SERVER uses the Client / Server model. This forms
the major difference between SQL SERVER and ACCESS.
Note: Just to clarify what is client server and file server I will make a quick description of
widely accepted architectures. There are three types of architectures:
o Main frame architecture (This is not related to the above explanation but just
mentioned as it can be useful during an interview and also for comparing with other
o File sharing architecture (Followed by ACCESS)
o Client Server architecture (Followed by SQL SERVER).

In Main Frame architecture, all the processing happens on central host server. User interacts through
a dumb terminal that only sends keystrokes and information to the host. All the main processing
happens on the central host server. So the advantage in such type of architecture is that you need
least configuration clients. But the disadvantage is that you need a robust central host server like
Main Frames.

In File sharing architecture, which is followed by Access database, all the data is sent to the client
terminal and then processed. For instance, if you want to see customers who stay in India, in File
Sharing architecture all customer records will be sent to the client PC regardless whether the
customer belongs to India or not. On the client PC customer records from India are sorted/filtered out
and displayed, in short all processing logic happens on the client PC. Therefore, in this architecture,
the client PC should have heavy configuration and it increases network traffic as a lot of data is sent
to the client PC. However, the advantage of this architecture is that your server can be of a low

Figure 1.2: File Server Architecture of Access

In client server architecture, the above limitation of the file server architecture is removed. In client
server architecture, you have two entities, client and the database server. File server is now replaced
by database server. Database server takes up the load of processing any database related activity
and the client does any validation aspect of database. As the work is distributed between the entities
it increases scalability and reliability. Second, the network traffic also comes down as compared to file
server. For example if you are requesting customers from India, database server will sort/ filter and
send only Indian customer details to the client, thus bringing down the network traffic tremendously.
SQL SERVER follows the client-server architecture.

Figure 1.3: Client Server Architecture of SQL SERVER

• The second issue comes in terms of reliability. In Access, the client directly interacts with the
Access file, in case there is some problem in the middle of a transaction, there are chances
that an Access file can get corrupt. But in SQL SERVER, the engine sits in between the client
and the database, so in case of any problems in the middle of a transaction, it can revert back
to its original state.
Note: SQL SERVER maintains a transaction log by which you can revert back to your original
state in case of any crash.
• When your application has to cater to a huge load demand, highly transactional environment
and high concurrency, then its better to go for SQL SERVER or MSDE.
• But when it comes to cost and support, Access stands better than SQL SERVER. In case of
SQL SERVER, you have to pay for per client license, but Access runtime is free.

Summarizing: SQL SERVER gains points in terms of network traffic, reliability and scalability
whereas Access gains points in terms of cost factor.

(Q) What is the Difference between MSDE and SQL SERVER 2000?

MSDE is a royalty free, redistributable and cut short version of the giant SQL SERVER database. It is
primarily provided as a low cost option for developers who need a database server, which can easily
be shipped and installed. It can serve as a good alternative for Microsoft Access database as it
overcomes quite a few problems which Access has.

Below is a complete list, which can give you a good idea of the differences:

• Size of database: Microsoft Access and MSDE have a limitation of 2GB while SQL SERVER
has 1,048,516 TB1.
• Performance degrades in MSDE 2000 when maximum number of concurrent operations goes
above 8 or is equal to 8. It does not mean that you cannot have more than eight concurrent
operations but the performance degrades. Eight-connection performance degradation is
implemented by using SQL SERVER 2000 workload governor (we will be looking into more
detail of how it works). As compared to SQL SERVER 2000, you can have 32,767 concurrent
• MSDE does not provide OLAP and Data warehousing capabilities.
• MSDE does not have support facility for SQL mail.
• MSDE 2000 does not have GUI administrative tool such as enterprise manager, Query
analyzer or Profiler. But there are roundabout ways by which you can manage MSDE 2000:
o Old command line utility OSQL.EXE
o VS.NET IDE Server Explorer: Inside VS.NET IDE, you have a functionality which can
give you a nice GUI administrative tool to manage IDE.
o SQL SERVER WEB Data administrator installs a web based GUI which you can use to
manage your database.
For any details refer here.
• SQL-DMO objects can be used to build your custom UI
• There are many third party tools, which provide administrative capability GUI, which is out of
scope of the book as it is only meant for interview questions.
• MSDE does not support Full text search.

Summarizing: There are two major differences: The first is the size limitation (2 GB) of the database
and second is the concurrent connections (eight concurrent connections) which are limited by using
the workload governor. During an interview, this answer will suffice if the interviewer is really testing
your knowledge.

(Q) What is SQL SERVER Express 2005 Edition?

Twist: What is the difference between SQL SERVER Express 2005 and MSDE 2000?

Note: Normally comparison is when the product is migrating from one version to other version. When
SQL SERVER 7.0 was migrating to SQL 2000, asking differences was one of the favorite questions.

SQL SERVER Express edition is a scaled down version of SQL SERVER 2005 and the next
evolution of MSDE.

Listed below are some major differences between them:

• MSDE maximum database size is 2GB while SQL SERVER Express has around 4GB.
• In terms of programming language support MSDE has only TSQL, but SQLSERVER Express
has TSQL and .NET. In SQL SERVER Express 2005, you can write your stored procedures
using .NET.
• SQL SERVER Express does not have connection limitation, which MSDE had and was
controlled through the workload governor.
• There was no XCOPY support for MSDE, SQL SERVER Express has it.
• DTS is not present in SQL SERVER express while MSDE has it.
• SQL SERVER Express has reporting services while MSDE does not.
• SQL SERVER Express has native XML support and MSDE does not.

Note: Native XML support means now in SQL SERVER 2005:

• You can create a field with data type XML.

• You can provide SCHEMA to the SQL SERVER fields with XML data type.
• You can use new XML manipulation techniques like XQUERY also called as XML QUERY.

There is a complete chapter on SQL SERVER XML Support, so till then this will suffice.
Summarizing: The major difference is the database size (2 GB and 4 GB), support of .NET support
in stored procedures and native support for XML. This much can convince the interviewer that you
are clear about the differences.

(DB) What is SQL Server 2000 Workload Governor?

Workload governor limits the performance of SQL SERVER Desktop engine (MSDE) if the SQL
engine receives more load than what is meant for MSDE. MSDE was always meant for trial purpose
and non-critical projects. Microsoft always wanted companies to buy their full blow version of SQL
SERVER, so in order that they can put limitation on MSDE performance and number of connections,
they introduced Workload governor.

Workload governor sits between the client and the database engine and counts the number of
connections per database instance. If Workload governor finds that the number of connections
exceeds eight connections, it starts stalling the connections and slowing down the database engine.

Note: It does not limit the number of connections but makes the connection request go slow. By
default 32,767 connections are allowed both for SQL SERVER and MSDE. But it just makes the
database engine go slow above eight connections.

What is the Difference between SQL SERVER 2000 and 2005?

Twist: What is the difference between Yukon and SQL SERVER 2000?

Note: This question will be one of the favorites during SQL SERVER interviews. I have marked the
points which should be mentioned by developers as PG and DBA for Database Administrator.

Following are some major differences between the two versions:

• (PG) The most significant change is the .NET integration with SQL SERVER 2005. Stored
procedures, user-defined functions, triggers, aggregates, and user-defined types can now be
written using your own favorite .NET language (VB.NET, C#, J# etc.). This support was not
there in SQL SERVER 2000 where the only language was T-SQL. In SQL 2005, you have
support for two languages T-SQL and .NET.
• (PG) SQL SERVER 2005 has reporting services for reports which is a newly added feature
and does not exist for SQL SERVER 2000. It was a separate installation for SQL Server 2000.
• (PG) SQL SERVER 2005 has introduced two new data types varbinary (max) and XML. If you
remember in SQL SERVER 2000, we had image and text data types. Problem with image and
text data types is that they assign the same amount of storage irrespective of what the actual
data size is. This problem is solved using varbinary (max) which acts depending on amount of
data. One more new data type is included XML which enables you to store XML documents
and does schema verification. In SQL SERVER 2000, developers used varchar or text data
type and all validation had to be done programmatically.
• (PG) SQL SERVER 2005 can now process direct incoming HTTP request without IIS Web
server. In addition, stored procedure invocation is enabled using the SOAP protocol.
• (PG) Asynchronous mechanism is introduced using server events. In Server event model the
server posts an event to the SQL Broker service, later the client can come and retrieve the
status by querying the broker.
• For huge databases, SQLSERVER has provided a cool feature called “Data partitioning”. In
data partitioning, you break a single database object such as a table or an index into multiple
pieces. But for the client application accessing the single database object, “partitioning” is
• In SQL SERVER 2000, if you rebuilt clustered indexes even the non-clustered indexes where
rebuilt. But in SQL SERVER 2005 building the clustered indexes does not build the non-
clustered indexes.
• Bulk data uploading in SQL SERVER 2000 was done using BCP (Bulk copy program’s)
format files. Now in SQL SERVER 2005 bulk, data uploading uses XML file format.
• In SQL SERVER 2000 there were maximum 16 instances, but in 2005 you can have up to 50
• SERVER 2005 has support of “Multiple Active Result Sets” also called as “MARS”. In previous
versions of SQL SERVER 2000 in one connection, you could only have one result set. Now in
one SQL connection, you can query and have multiple results set.
• In previous versions of SQL SERVER 2000, system catalog was stored in the master
database. In SQL SERVER 2005, it’s stored in a resource database which is stored as sys
object. You cannot access the sys object directly as in the older version we were accessing
the master database.
• This is one of the hardware benefits which SQL SERVER 2005 has over SQSERVER 2000 –
support of hyper threading. WINDOWS 2003 supports hyper threading; SQL SERVER 2005
can take advantage of the feature unlike SQL SERVER 2000 which did not support hyper
Note: Hyper threading is a technology developed by INTEL which creates two logical
processors on a single physical hardware processor.
• SMO will be used for SQL Server Management.
• AMO (Analysis Management Objects) to manage Analysis Services servers, data sources,
cubes, dimensions, measures, and data mining models. You can mapm AMO in old SQL
SERVER with DSO (Decision Support Objects).
• Replication is now managed by RMO (Replication Management Objects).
Note: SMO, AMO and RMO are all using .NET Framework.
• SQL SERVER 2005 uses current user execution context to check rights rather than ownership
link chain, which was done in SQL SERVER 2000.
Note: There is a question on this later see for execution context questions.
• In previous versions of SQL SERVER the schema and the user name was same, but in
current, the schema is separated from the user. Now the user owns schema.
Note: There are questions on this, refer “Schema” later.
Note: Ok below are some GUI changes.
• Query analyzer is now replaced by query editor.
• Business Intelligence development studio will be used to create Business intelligence
• OSQL and ISQL command line utility is replaced by SQLCMD utility.
• SQL SERVER Enterprise manager is now replaced by SQL SERVER Management studio.
• SERVER Manager which was running in system tray is now replaced by SQL Computer
• Database mirror concept is supported in SQL SERVER 2005, which was not present in SQL
SERVER 2000.
• In SQL SERVER 2005 Indexes can be rebuilt online when the database is in actual
production. If you look back in SQL SERVER 2000, you cannot do insert, update, and delete
operations when you are building indexes.
• (PG) Other than Serializable, Repeatable Read, Read Committed, and Read Uncommitted
isolation levels, there is one more new isolation level “Snapshot Isolation level”.
Note: We will see “Snapshot Isolation level” in detail in the coming questions.

Summarizing: The major significant difference between SQL SERVER 2000 and SQL SERVER
2005 is in terms of support of .NET Integration, Snap shot isolation level, Native XML support,
handling HTTP request, Web service support and Data partitioning. You do not have to really say all
the above points during an interview. A sweet summary and you will rock.

(Q) What are E-R diagrams?

E-R diagram also termed as Entity-Relationship diagram shows the relationship between various
tables in the database. Example: Tables Customer and Customer Addresses have a one to many
relationship (i.e. one customer can have multiple addresses) this can be shown using the ER
diagram. ER diagrams are drawn during the initial stages of a project to forecast how the database
structure will shape up. Below is a screen shot of a sample ER diagram of “Asset Management”
which ships free with Access.
Figure 1.4: Asset management ER diagram.

(Q) How many Types of Relationship Exist in Database Designing?

There are three major relationship models:

• One-to-one

Figure 1.5: One-to-One relationship ER diagram

• One-to-many
In this many records in one table correspond to the one record in another table.
Example: Every one customer can have multiple sales. So there exist one-to-many
relationships between customer and sales table.

One Asset can have multiple Maintenance. So Asset entity has one-to-many relationship
between them as the ER model shows below.

Figure 1.6: One-to-Many Relationship ER diagram

• Many-to-many
In this, one record in one table corresponds to many rows in another table and also vice-
For instance: In a company, one employee can have many skills like Java , C# etc. and also
one skill can belong to many employees.

Given below is a sample of many-to-many relationship. One employee can have knowledge of
multiple Technology. So in order to implement this, we have one more table Employee
Technology which is linked to the primary key of Employee and Technology table.

Figure 1.7: Many-to-Many Relationship ER diagram

(Q) What is Normalization? What are the Different Types of Normalization?

Note: A regular .NET programmer working on projects often stumbles on this question, which is but
obvious. The bad part is sometimes the interviewer can take this as a very basic question to be
answered and it can be a turning point for the interview. So let's cram it.

It is set of rules that have been established to aid in the design of tables that are meant to be
connected through relationships. This set of rules is known as Normalization.

Benefits of Normalizing your database include:

• Avoiding repetitive entries

• Reducing required storage space
• Preventing the need to restructure existing tables to accommodate new data
• Increased speed and flexibility of queries, sorts, and summaries

Note: During an interview, people expect to answer a maximum of three normal forms and that's what
is expected practically. Actually you can normalize database to fifth normal form. But believe this
book, answering three normal forms will put you in a decent shape during an interview.

The three normal forms as follows:

First Normal Form

For a table to be in first normal form, data must be broken up into the smallest units possible. In
addition to breaking data up into the smallest meaningful values, tables in first normal form should not
contain repetitions groups of fields.

Figure 1.8: Repeating groups example

In the above example, city1 and city2 are repeating. In order for these tables to be in First normal
form, you have to modify the table structure as follows. Also note that the Customer Name is now
broken down to first name and last name (First normal form data should be broken down to the
smallest unit).

Figure 1.9: Customer table normalized to first normal form

Second Normal Form

The second normal form states that each field in a multiple field primary key table must be directly
related to the entire primary key. In other words, each non-key field should be a fact about all the
fields in the primary key.

In the above table of customer, city is not linked to any primary field.

Figure 1.10: Normalized customer table.

Figure 1.11: City is now shifted to a different master table.

That takes our database to a second normal form.

Third Normal Form

A non-key field should not depend on another Non-key field. The field Total is dependent on Unit
price and qty.

Figure 1.12: Fill third normal form

So now the Total field is removed and is the multiplication of Unit price * Qty.

(Q) What is Denormalization?

Denormalization is the process of putting one fact in numerous places (it is vice-versa of
normalization). Only one valid reason exists for denormalizing a relational design - to enhance
performance. The sacrifice to performance is that you increase redundancy in a database.

(DB) Can you Explain Fourth Normal Form?

Note: Whenever the interviewer is trying to go above the third normal form, there can be two
reasons, ego or to fail you. Three normal forms are really enough, practically anything more than that
is an overdose.

In fourth normal form, it should not contain two or more independent multi-valued facts about an
entity and it should satisfy “Third Normal form”.

So let us try to see what multi-valued facts are. If there are two or more many-to-many relationship in
one entity and they tend to come to one place, it is termed as “multi-valued facts”.
Figure 1.13: Multi-valued facts

In the above table, you can see that there are two many-to-many relationships between Supplier /
Product and “Supplier / Location (or in short multi-valued facts). In order for the above example to
satisfy the fourth normal form, both the many-to-many relationships should go in different tables.

Figure 1.14: Normalized to Fourth Normal form.

(DB) Can you Explain Fifth Normal Form?

Note: UUUHHH if you get this question after joining the company, do ask him if he himself really uses

Fifth normal form deals with reconstructing information from smaller pieces of information. These
smaller pieces of information can be maintained with less redundancy.

Example: Dealers sell Product which can be manufactured by various Companies. Dealers in order to
sell the Product should be registered with the Company. So these three entities have a mutual
relationship within them.

Figure 1.15: Not in Fifth Normal Form.

The above table shows some sample data. If you observe closely, a single record is created using lot
of small information. For instance: JM Associate can sell sweets under the following two conditions:

• JM Associate should be an authorized dealer of Cadbury

• Sweets should be manufactured by Cadbury company

These two smaller bits of information form one record of the above given table. So in order for the
above information to be “Fifth Normal Form” all the smaller information should be in three different
places. Below is the complete fifth normal form of the database.
Figure 1.16: Complete Fifth Normal Form

(DB) What is the Difference between Fourth and Fifth normal form?

Note: There is a huge similarity between Fourth and Fifth normal form, i.e. they address the problem
of “Multi-Valued facts”.

“Fifth normal form” multi-valued facts are interlinked and “Fourth normal form” values are
independent. For instance in the above two questions Supplier/Product and Supplier/Location are not
linked. While in fifth form, the Dealer/Product/Companies are completely linked.

(DB) Have you Heard about Sixth Normal Form?

Note: Arrrrggghhh yes there exists a sixth normal form also. But note guys you can skip this
statement. Just in case you want to impress the interviewer...

If you want a relational system in conjunction with time, you use sixth normal form. At this moment
SQL Server does not support it directly.

(Q) What is Extent and Page?

Twist: What is the relationship between Extent and Page?

Extent is a basic unit of storage to provide space for tables. Every extent has a number of data
pages. As new records are inserted new data, pages are allocated. There are eight data pages in an
extent. So as soon as the eight pages are consumed, it allocates a new extent with data pages.

While extent is basic unit storage from a database point of view, page is a unit of allocation within

(DB) What are the Different Sections in Page?

Page has three important sections:

• Page header
• Actual data i.e. Data row
• Row pointers or Row offset

Page header has information like timestamp, next page number, previous page number etc.

Data rows are where your actual row data is stored. For every data row, there is a row offset which
points to that data row.
Figure 1.17: General view of a Extent

(Q) What are Page Splits?

Pages are contained in extent. Every extent will have around eight data pages. But all the eight data
pages are not created at once; they are created depending on data demand. So when a page
becomes full it creates a new page, this process is called as “Page Split”.

(Q) In which Files does SQL Server Actually Store Data?

Any SQL Server database is associated with two kinds of files: *.mdf and *.ldf. *.mdf files are actual
physical database files where your data is stored finally. *.ldf (LOG) files are actually data, which is
recorded from the last time data was committed in the database.
Figure 1.18: MDF and LDF files.

(Q) What is Collation in SQL Server?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is
sorted using rules that define the correct character sequence, with options for specifying case-
sensitivity, accent marks, kana character types, and character width.

Figure 1.19: Collation according to language

Note: Different languages will have different sort orders.

Case Sensitivity

If A and a, B and b, etc. are treated in the same way, then it is case-insensitive. A computer treats A
and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65,
while a is 97. The ASCII value of B is 66 and b is 98.
Accent Sensitivity

If a and A, o and O are treated in the same way, then it is accent-insensitive. A computer treats a and
A differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and A
225. The ASCII value of o is 111 and O is 243.

Kana Sensitivity

When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana

Width Sensitivity

When a single-byte character (half-width) and the same character when represented as a double-
byte character (full-width) are treated differently then it is width sensitive.

(DB) Can We Have a Different Collation for Database and Table?

Yes, you can specify different collation sequence for both the entities differently.

What is Index?

Answer Description:

A database index is a data structure which use to improve the speed of operations on a database table.
It’s a physical structure containing pointers to the data. Indices can be created using one or more
columns of a database table. Indices are created in an existing table to quickly and efficiently lookups.
It is possible to create an index on one or more columns of a table, and each index is given a
name. Best way to improve performance in a database application is effective indexes.

There are two type of index available.

1. Clustered index

Clustered index are physical form of sorting. Therefore only one clustered index can be created on
each table because the data rows themselves can only be sorted in one order.

2. Non Clustered index

Non clustered indexes are logical form of sorting. Therefore more than one Non clustered indexes can
be created on each table.

Can UNIQUE KEY in SQL Server 2005 have two or more NULL?

Answer Description:

SQL server 2005 can not have more then one NULL, because in SQL server 2005 every null is having
same value. UNIQUE KEY in ORACLE can have more then one NULL values as every NULL in
ORACLE is having unique value.
What is SQL Server ?
SQL Server is a DBMS system provided by Microsoft. SQL Server is sometimes mistakenly referred
to as SQL.

Error severity 13 indicates what?

Transactional deadlock errors.
This level of error severity indicates a transaction deadlock error.

In which order do you perform an upgrade to SQL Server 2005 for replicated databases?
Distributor, Publisher, then Subscriber.
You always perform an upgrade in this order: distributor, publisher, subscriber.

How many Service Packs will be released for SQL Server 2005 in 2007?
Explanation: The answer is up in the air and this is more of a poll than a real QOD. Based on the ways
things are going, the staff here sees just 1, though our hope would be that 3 or 4 would be released.

You setup a linked server from a SQL Server 2000 server to your new SQL Server 2005 server
(with defaults), however you cannot execute procedures on the 2005 server. Why not?
You need to enable RPC.
By default, RPC is disabled in SQL Server 2005. You need to set the "remote access option" in your
server configuration to 1 to allow the execution of stored procedures from a remote server.

What is the recommended way to send mail from SQLAgent in SQL Server 2005?
Database Mail
You can use either Database Mail or SQLMail with SQL Agent in SQL Server 2005. However since
SQLMail will be removed, it is recommended that you use Database Mail.

When you create a new Message Type in the SQL Server 2005 Service Broker, what does the
Authorization parameter signify?
The owner of the message type.
This parameter determines the owner of the message type. This defaults to the current user.

What the heck does ATN2 do?

The angle between the x-axis and a ray.
This is a mathematical function that returns the angle between the positive x-axis and the ray that
passes through the two coordinates passed in. The angle is in radians.

How does a differential backup know which extents have changed so that it can be very quickly
The DCM tracks changes. The differential backup reads the extents from this structure.
A differential backup uses the Differential Change Map to determine which extents have changed and
need to be include in the backup. This greatly speeds the differential backup process.

How many rows are returned by these two select statements?

2 and 2
Each select statement actually returns 2 rows. You can use this script to check this:
create table mytable
( id int identity(1,1)
, mychar varchar(20)
insert mytable select null
insert mytable select ''
insert mytable select ' '
set ansi_nulls on
set ansi_null_dflt_on on
select * from mytable
where mychar is not null
select * from mytable
where mychar <> '' and mychar is not null
select * from mytable
where mychar <> ' ' and mychar is not null
select * from mytable where mychar = ''
select * from mytable where mychar = ' '
set ansi_null_dflt_on off
set ansi_nulls off
drop table mytable

What does the Queue Reader Agent do in SQL Server 2005 replication?
This agent reads the subscriber logs and moves changes back to the publisher.
This agent is used when the queued update model is chosen with transactional replication. It moves
changes from the subscribers back to the publishers.

What are the three possible functions of the plus (+) operator in SQL Server 2005, the base
installed T-SQL?
Add, string concatenation, unary plus
The three functions are Add, String Concatenation, and Unary Plus.

The Sort component in SQL Server 2005 Integration Services is what type of component?
Blocking Transformation
The Sort component is a blocking transformation meaning that it needs all rows in order to perform its

If you received a "Performance Critical" status in the SQL Server 2005 replication monitor,
what does this mean?
The latency between transaction commits at the publisher and subscriber exceeds the warning level.
This status can actually mean two different things. Either the latency between the commit of a
transaction at the publisher and the same commit at the subscriber is exceeding some level in a
transactional level or not enough rows are being processed in a merge replication scenario.

Which of the following modules within SQL Server 2005 cannot be signed with a digital
DDL triggers
DDL triggers cannot be signed, but all the other objects can.

What does this return?

declare @i int
select @i = -5
select +@i

This will return -5 as the result. The + operator functions as a unary plus operator, which means that it
performs no operation on the value it preceeds.
You have installed a US English SQL Server 2000 instance with the default options, collation,
and sorting. What does this return:
create table MyTable
( Mychar varchar(20))
insert Mytable select 'Apple'
insert Mytable select 'ant'
insert Mytable select 'Ball'
select * from MyTable where Mychar like '[^a]%'

This should return "Ball" only since the ^ operator means not matching the next character. In this case,
the first character should not be an "A".

What is the Service Broker Identifier ?

A GUID that identifies the database on which Service Broker is running.
Each database has a Service Broker identifier. This is a GUID in the service_broker_GUID column
that identifies the databases on which Service Broker is running. It ensure that messages are delivered
to the right database.

You are looking to import a large amount of data from a remote OLEDB data source that is not
a text file. Which of the following techniques can you use?
Use the select * from OPENROWSET(BULK...) command.
SQL Server 2005 includes a new option with the OPENROWSET command for getting large amounts
of data from an OLEDB data source. It is the BULK option and works similar to the BULK INSERT