SQL Interview Questions 1

Back to Notes on .NET

C# General Interview Questions

C# Questions on properties, events etc

Questions on XML, ADO.NET etc

C# Rapid Fire Questions 1

C# Rapid Fire Questions 2

SQL Interview Questions 1

SQL Interview Questions 2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1. What are the different types of Joins?
Ans. Joins as used to combine the contents of
two or more tables and produce a result set
that incorporates rows and columns from each
table. Tables are typically joined using data
that they have in common Join conditions can
be specified in either the FROM or WHERE
clauses; specifying them in the FROM clause
is recommended. WHERE and HAVING clauses can
also contain search conditions to further
filter the rows selected by the join conditions.

Joins can be categorized as:

Inner joins - (the typical join operation, which
uses some comparison operator like = or <>). An
inner join is a join in which the values in the
columns being joined are compared using a
comparison operator
Inner joins use a comparison operator to match
rows from two tables based on the values in
common columns from each table.

Equi Join - It returns all the columns in both
tables, and returns only the rows for which
there is an equal value in the join column

( SELECT * FROM authors AS a INNER JOIN
publishers AS p ON a.city = p.city ORDER
BY a.au_lname DESC )

Self Join - A table can be joined to itself
in a self-join

Outer joins - Outer joins can be a left,
right, or full outer join. Outer joins are
specified with one of the following sets of
keywords when they are specified in the FROM
clause:

LEFT JOIN or LEFT OUTER JOIN -
The result set of a left outer join includes
all the rows from the left table specified in
the LEFT OUTER clause, not just the ones in
which the joined columns match. When a row in
the left table has no matching rows in the
right table, the associated result set row
contains null values for all select list
columns coming from the right table.

RIGHT JOIN or RIGHT OUTER JOIN -
 A right outer join is the reverse of a left
outer join. All rows from the right table are returned.
Null values are returned for the left table any time
a right table row has no matching row in the left
table.

FULL JOIN or FULL OUTER JOIN
 A full outer join returns all rows in
both the left and right tables. Any time a row
has no match in the other table, the select
list columns from the other table contain null
values. When there is a match between the tables,
the entire result set row contains data values
from the base tables.

Cross joins - Cross joins return all rows from
the left table, each row from the left table
is combined with all rows from the right table.
Cross joins are also called Cartesian products.

2. What is diff. between left and Right
outer Join?
Ans. The result set of a left outer join
includes all the rows from the left table
specified in the LEFT OUTER clause , while in case
of Right outer join all the rows from the
right table are returned in the result set.

3. Why we use Unicode In Sql server?
Ans.Using Unicode data types, a column can store
any character that is defined by the Unicode
Standard, which includes all of the characters
that are defined in the various character sets.
Unicode data types take twice as much storage
space as non-Unicode data types.

Unicode data is stored using the nchar, nvarchar,
and ntext data types in SQL Server. Use these
data types for columns that store characters
from more than one character set. The SQL Server
Unicode data types are based on the National
Character data types in the SQL-92 standard

4.What is Fill Factor and its value when the
index is created.
Ans.An option used when creating an index to
reserve free space on each page of the index.
FILLFACTOR accommodates future expansion of
table data and reduces the potential for page
splits. FILLFACTOR is a value from 1 through
100 that specifies the percentage of the index
page to be left empty.Default is 0.

A fill factor value of 0 does not mean that
pages are 0 percent full. It is treated s
imilarly to a fill factor value of 100 in that
SQL Server creates clustered indexes
with full data pages and nonclustered indexes
with full leaf pages.If you set fill factor to
100, SQL Server creates both clustered and
nonclustered indexes with each page 100 percent
full. Setting fill factor to 100 is suitable
only for read-only tables, to which additional
data is never added.

5.What are the different types of Filebackup
options
?
Ans. All data and objects in the database, such
as tables, stored procedures, triggers, and
views, are stored only within the following
operating system files:

Primary
 This file contains the startup
information for the database and is used to store
data. Every database has one primary data file.

Secondary
 These files hold all of the data that
does not fit in the primary data file. If the
primary file can hold all of the data in the
database, databases do not need to have
secondary data files. Some databases may be
large enough to need multiple secondary data
files or to use secondary files on separate
disk drives to spread data across multiple disks.

Transaction Log
These files hold the log information used to
recover the database. There must be at least
one log file for each database. File groups
allow files to be grouped together for
administrative and data allocation/placement
purposes

Rules of Files and Filegroups
Rules for designing files and filegroups
include:
•A file or filegroup cannot be used by more
than one database. For example, file sales.mdf
and sales.ndf, which contain data and objects from
the sales database, cannot be used by any other
database.
•A file can be a member of only one filegroup.
•Data and transaction log information cannot be
part of the same file or filegroup.
•Transaction log files are never part of any
filegroups.

Types of BackUP
Database
Transaction log
Differential
Filegroup & Backup

6.What is Differential File group backup?
Ans.Differential database backup records only
those data changes made to the database after
the last full database backup. A differential
database backup is smaller and takes less time
to complete than a database backup. By creating
differential database backups more frequently than
database backups, you can decrease the amount of
data you risk losing.

7.What is Collate?
Ans.A clause that can be applied to a database
definition or a column definition to define the
collation, or to a character string expression to
apply a collation cast. The COLLATE clause can be
applied only for the char, varchar, text, nchar,
nvarchar, and ntext data types. The physical storage
of character strings in Microsoft® SQL Server™ 2000
is controlled by collations. A collation specifies
the bit patterns that represent each character and
the rules by which characters are sorted and compared

8. What is Code Page?
Ans.A character set that a computer uses to interpret
and display characters, often to handle international
characters. Essentially, it is a table of characters
and corresponding numbers in memory that the computer
uses to display data properly. Different languages and
locales may use different code pages.

9.When we should go for with Recompile option in
Stored Procedures?
Ans.When stored procedures take parameters whose
values differ widely between executions of the
stored procedure, resulting in different execution
plans to be created each time.  If the parameter you
are supplying is atypical or if the data has
significantly changed since the stored procedure was
created. Use of this option is uncommon, and causes
the stored procedure to execute more slowly because
the stored procedure must be recompiled each time
it is executed. Creating a stored procedure that
specifies the WITH RECOMPILE option in its definition
 indicates that SQL Server does not cache a plan for
this stored procedure; the stored procedure is
recompiled each time it is executed.

10.What is difference between Having and Group
by
Clause?
Ans. The HAVING clause sets conditions on the
GROUP BY clause similar to the way WHERE interacts
with SELECT. The WHERE search condition is applied
before the grouping operation occurs; the HAVING
search condition is applied after the grouping
operation occurs. The HAVING syntax is exactly like
the WHERE syntax, except HAVING can contain aggregate
functions.
HAVING clauses can reference any of the items that
appear in the select list.
•The WHERE clause is used to filter the rows that
result from the operations specified in the
FROM clause.
•The GROUP BY clause is used to group the output
of the WHERE clause.
•The HAVING clause is used to filter rows from the
grouped result

Where – Groupby – Having – Order By

11.What are Isolation levels?
Ans.An isolation level determines the degree to
which data is isolated for use by one process and
guarded against interference from other processes.

Read Committed -
SQL Server acquires a share lock while reading a
row into a cursor but frees the lock immediately
after reading the row. Because a shared lock request
is blocked by an exclusive lock, a cursor is
prevented from reading a row that another task has
updated but not yet committed. Read committed is
the default isolation level setting for both SQL
Server and ODBC.

Read Uncommitted -
SQL Server requests no locks while reading a row
into a cursor and honors no exclusive locks. Cursors
can be populated with values that have already been
updated but not yet  committed. The user is
bypassing all of SQL Server’s locking transaction
control mechanisms.

Repeatable Read or Serializable -
SQL Server requests a shared lock on each row as it
is read into the cursor as in READ COMMITTED, but
if the cursor is opened within a transaction, the
shared locks are held until the end of the
transaction instead of being freed after the row
is read. This has the same effect as specifying
HOLDLOCK on a SELECT statement.

12.When should we go for NOLOCK hint?
Ans.A range of table-level locking hints can be
specified using the SELECT, INSERT, UPDATE, and
DELETE statements to direct Microsoft® SQL Server™
2000 to the type of locks to be used. Table-level
locking hints can be used when a finer control of
the types of locks acquired on an object is requ
ired. These locking hints override the current
transaction isolation level for the session.

NOLOCK
 Do not issue shared locks and do not
honor exclusive locks. When this option is in
effect, it is possible to read an uncommitted
transaction or a set of pages that are rolled
back in the middle of a read. Dirty reads are
possible. Only applies to the SELECT statement.


13. What are diff. types of Database import?
Ans.BCP, DTS, BulkCopy Command

14.Diff. between BCP and DTS, which one is
advantageous?
Ans. BCP is a command prompt utility. bcp provides
for running bulk copies in .bat and .cmd scripts.
bcp is used to bulk copy large files into tables
or views in SQL Server databases. BCP is non
logged operation.

DTS allows the user to program transformations
through two different interfaces.

BCP is extremely fast and has a minimal overhead,
but it also has a very rigid (and sometimes
unforgiving) syntax. Then along came Data
Transformation Services (DTS), an improved
method for importing and exporting data between
heterogeneous data sources. Whether you want to
move data from a legacy system on a onetime basis
or continually move data back and forth for data
warehousing, DTS should be your first choice. With
DTS you don't need to struggle with BCP anymore.
DTS is extremely flexible and surprisingly fast,
and you can use the technology to copy and transform
data to or from any OLE DB or ODBC data source.


BCP is designed to work with flat files, while DTS
can work with "any" database. using BCP, you have
a much more mature tool, and clearer error messages
than with DTS.

15.What are DBCC COMMANDS?
Ans.The Transact-SQL programming language provides
DBCC statements that act as the “database consistency
checker” for Microsoft® SQL Server™. These statements
check the physical and logical consistency of a
database. Many DBCC statements can fix detected
problems. These database consistency-checking
statements are grouped into these categories.

Maintenance Statements:
Maintenance tasks on a database, index, or filegroup.

DBCC DBREPAIR
DBCC SHRINKFILE
DBCC DBREINDEX
DBCC UPDATEUSAGE
DBCC SHRINKDATABASE   

Miscellaneous Statements:
Miscellaneous tasks such as enabling row-level
locking or removing a dynamic-link library (DLL)
from memory

DBCC dllname (FREE)
DBCC TRACEOFF
DBCC HELP
DBCC TRACEON
DBCC PINTABLE
DBCC UNPINTABLE
DBCC ROWLOCK  

Status Statements:
Status Checks

DBCC INPUTBUFFER
DBCC SHOW_STATISTICS
DBCC OPENTRAN
DBCC SQLPERF
DBCC OUTPUTBUFFER
DBCC TRACESTATUS
DBCC PROCCACHE
DBCC USEROPTIONS
DBCC SHOWCONTIG  

Validation Statements:
Validation operations on a database, table, index,
catalog, filegroup, system tables, or allocation of
database pages.

DBCC CHECKALLOC
DBCC CHECKTABLE
DBCC CHECKCATALOG
DBCC NEWALLOC
DBCC CHECKDB
DBCC TEXTALL
DBCC CHECKFILEGROUP
DBCC TEXTALLOC
DBCC CHECKIDENT  

16.What are System Stored Procedures?
SQL Server-supplied, precompiled collection of
Transact-SQL statements. System stored procedures
are provided as shortcuts Ans.for retrieving
information from system tables or mechanisms
for accomplishing database administration and other
tasks that involve updating system tables. The names
of all system stored procedures begin with sp_.
System stored procedures are located in the master
database and are owned by the system administrator,
but many of them can be run from any database.
If a system stored procedure is executed in a
database other than master, it operates on the system
tables in the database from which it is executed.

17.Can we prefix user defined SP's with sp_, if so
what will happen if u call that SP?
Ans.SQL Server always looks for stored procedures
beginning with sp_ in this order:
i. Look for the stored procedure in the
master database first.
ii. Look for the stored procedure based on
any qualifiers provided (database name or owner).
iii. Look for the stored procedure using dbo as
the owner, if one is not specified.

Therefore, although the user-created stored procedure
 prefixed with sp_ may exist in the current database,
 the master database is always checked first, even
if the stored procedure is qualified with the database
name
Important : If any user-created stored procedure
has the same name as a system stored procedure,
the user-created stored procedure will never
be executed

18. What are Indexes?
Ans.Microsoft SQL Server index is a structure associated
with a table that speeds retrieval of the rows in the
table.
An index contains keys built from one or more col
umns in the table. These keys are stored in a
structure that allows SQL Server to find the row or
rows associated with the key values quickly and
efficiently. If a table is created with no indexes,
the data rows are not stored in any particular order.
This structure is called a heap.

The two types of SQL Server indexes are:
•Clustered
Clustered indexes sort and store the data rows in the
 table based on their key values. Because the data
rows are stored in sorted order on the clustered index
key, clustered indexes are efficient for finding rows.
 There can only be one clustered index per table,
because the data rows themselves can only be sorted
in one order. The data rows themselves form the lowest
level of the clustered index.

The only time the data rows in a table are stored in
sorted order is when the table contains a clustered
index. If a table has no clustered index, its data
rows are stored in a heap.

•Nonclustered
Nonclustered indexes have a structure that is
completely separate from the data rows. The
lowest rows of a nonclustered index contain the
nonclustered index key values and each key value
entry has pointers to the data rows containing
the key value. The data rows are not stored in
order based on the nonclustered key. The pointer
from an index row in a nonclustered index to a
data row is called a row locator. The structure
of the row locator depends on whether the data
pages are stored in a heap or are clustered. For
a heap, a row locator is a pointer to the row. For
a table with a clustered index, the row
locator is the clustered index key

19.When will we go for clustered and
Non-clustered Indexes?
Ans.
Indexes assist when a query:
•Searches for rows that match a specific search
key value (an exact match query). An exact match
comparison is one in which the query uses the WHERE
 statement to specify a column entry with a given
value.
For example: WHERE emp_id = 'VPA30890F'

•Searches for rows with search key values in a
range of values (a range query). A range query is
one in which the query specifies any entry whose value
is between two values.
For example: WHERE job_lvl BETWEEN 9 and 12
or,
WHERE job_lvl >= 9 and job_lvl <= 12

•Searches for rows in a table T1 that match, based
on a join predicate, a row in another table T2
(an index nested loops join).

•Produces sorted query output without an explicit
sort operation, in particular for sorted dynamic
cursors.

•Scans rows in a sorted order to permit an
order-based operation, such as merge join and
stream aggregation, without an explicit sort
operation.

•Scans all rows in a table with better performance than
a table scan, due to the reduced column set and overall
data volume to be scanned
 (a covering index for the query at hand).
•Searches for duplicates of new search key values in
insert and update operations, to enforce PRIMARY KEY
and UNIQUE constraints.

•Searches for matching rows between two tables
for which a FOREIGN KEY constraint is defined.
Queries using LIKE comparisons can benefit from
an index if the pattern starts with a specific
character string,
for example 'abc%', but not if the pattern starts
with a wildcard search, for example '%xyz'.

•Columns that contain a high number of distinct values,
such as a combination of last name and first name
(if a clustered index is used for other columns). If
there are very few distinct values, such as only 1
and 0, no index should be created.

•Queries that do not return large result sets.

•Columns frequently involved in search conditions
of a query (WHERE clause) that return exact matches.

•Decision Support System applications for which
joins and grouping are frequently required. Create
multiple nonclustered indexes on columns involved in
join and grouping operations, and a clustered index
on any foreign key columns.

•Columns that contain a limited number of distinct
values, such as a state column that contains only
50 distinct state codes. However, if there are very
few distinct values, such as only 1 and 0, no index
should be created.

•Queries that return a range of values using operators
such as BETWEEN, >, >=, <, and <=.

•Columns that are accessed sequentially.

•Queries that return large result sets.

•Columns that are frequently accessed by queries
involving join or GROUP BY clauses; typically these
are foreign key columns. An index on the column(s)
specified in the ORDER BY or GROUP BY clause eliminates
the need for SQL Server to sort the data because
the rows are already sorted. This improves query
performance.

•OLTP-type applications where very fast single
row lookup is required, typically by means of the
primary key. Create a clustered index on the
primary key.

Clustered indexes are not a good choice for:
•Columns that undergo frequent changes because
this results in the entire row moving (because
SQL Server must keep the row’s data values in
physical order). This is an important consideration
in high-volume transaction processing systems where
data tends to be volatile.

•Covered queries. The more columns within the
search key, the greater the chance for the data
in the indexed column to change, resulting in
additional I/O.

20. What is Referential Integrity?
Ans.Referential integrity preserves the defined
relationships between tables when records are
entered or deleted. In SQL Server, referential
integrity is based on relationships between foreign
keys and primary keys or between foreign keys and unique
keys. 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.

21.What are the Features of Normalized and
De-normalized Databases?
Ans.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 unnormalized database. Some of
the benefits of normalization include:
•Faster sorting and index creation.
•A larger number of clustered indexes.
•Narrower and more compact indexes.
•Fewer indexes per table, which improves the
performance of INSERT, UPDATE, and DELETE statements.
•Fewer NULL values and less opportunity for
inconsistency, which increase database compactness.
 
22. When will you go for De-normalization?
Ans.To introduce redundancy into a table in order to
incorporate data from a related table. The related
table can then be eliminated. Denormalization can
improve efficiency and performance by reducing
complexity in a data warehouse schema.

23.Union and Union ALL, which will give better
performance and why?
Ans.The UNION operator allows you to combine the
results of two or more SELECT statements into a
single result set. The result sets combined using
UNION must all have the same structure. They must
have the same number of columns, and the
corresponding result set columns must have compatible
data types.
 The result set column names of a UNION are
the same as the column names in the result set of
the first SELECT statement in the UNION. The result
set column names of the other SELECT statements are
ignored.
 By default, the UNION operator removes
duplicate rows from the result set. If you use ALL,
all rows are included in the results and duplicates
are not removed
UNION ALL is faster because it doesn't try to
eliminate the duplicates. In fact, as a "duplicate"
is only determined by comparing the whole row (all
the columns returned), you should use UNION ALL all
the time, except if you WANT to eliminate the
duplicates by using UNION

24.What is the Diff. between drop and detach database?
Ans. Drop Database: Removes one or more databases from
SQL Server. Removing a database deletes the database and
the disk files used by the database.

A database that has been dropped can be re-created
only by restoring a backup. You cannot drop a database
currently in use (open for reading or writing by any
user). Whenever a database is dropped, the master
database should be backed up .

Detach Database
Detaches a database from a server and, optionally,
runs UPDATE STATISTICS on all tables before detaching.
Detaching a database removes the database from SQL
Server, but leaves the database intact within the data
and transaction log files that compose the database.
These data and transaction log files can then be used
to attach the database to any computer running SQL Server,
including the server from which the database was detached.
This makes the database available in exactly the same
state it was in when it was detached.

25.What are Instead of Triggers?
Ans.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.
The trigger executes in place of the triggering action.
INSTEAD OF triggers can be specified on both tables and
views. You can define only one INSTEAD OF trigger for
each triggering action (INSERT, UPDATE, and DELETE).
INSTEAD OF triggers can be used to perform enhance
integrity checks on the data values supplied in INSERT
and UPDATE statements. INSTEAD OF triggers also let you
specify actions that allow views, which would normally
not support updates, to be updatable.

NEXT