SQL SEVER Faq
SQL SEVER Faq
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5.in worst cases Denormalization
• Every index increases the time in takes to perform INSERTS, UPDATES and DELETES,
so the number of indexes should not be very much. Try to use maximum 4-5 indexes on
one table, not more. If you have read-only table, then the number of indexes may be
increased.
• Keep your indexes as narrow as possible. This reduces the size of the index and reduces
the number of reads required to read the index.
• Try to create indexes on columns that have integer values rather than character values.
• If you create a composite (multi-column) index, the order of the columns in the key are
very important. Try to order the columns in the key as to enhance selectivity, with the
most selective columns to the leftmost of the key.
• If you want to join several tables, try to create surrogate integer keys for this purpose and
create indexes on their columns.
• Create surrogate integer primary key (identity for example) if your table will not have
many insert operations.
• Clustered indexes are more preferable than nonclustered, if you need to select by a
range of values or you need to sort results set with GROUP BY or ORDER BY.
• If your application will be performing the same query over and over on the same table,
consider creating a covering index on the table.
• You can use the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large
Tables" trace to determine which tables in your database may need indexes. This trace
will show which tables are being scanned by queries instead of using an index.
• You can use sp_MSforeachtable undocumented stored procedure to rebuild all
indexes in your database. Try to schedule it to execute during CPU idle time and slow
production periods.
sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"
T-SQL Queries
1. 2 tables
EmployeePhone
empid
empname empid
salary phnumber
mgrid
2. Select all employees who doesn't have phone?
SELECT empname
FROM Employee
WHERE (empid NOT IN
(SELECT DISTINCT empid
FROM phone))
3. Select the employee names who is having more than one phone numbers.
SELECT empname
FROM employee
WHERE (empid IN
(SELECT empid
FROM phone
GROUP BY empid
HAVING COUNT(empid) > 1))
4. Select the details of 3 max salaried employees from employee table.
SELECT TOP 3 empid, salary
FROM employee
ORDER BY salary DESC
5. Display all managers from the table. (manager id is same as emp id)
SELECT empname
FROM employee
WHERE (empid IN
(SELECT DISTINCT mgrid
FROM employee))
6. Write a Select statement to list the Employee Name, Manager Name under a particular
manager?
SELECT e1.empname AS EmpName, e2.empname AS ManagerName
FROM Employee e1 INNER JOIN
Employee e2 ON e1.mgrid = e2.empid
ORDER BY e2.mgrid
7. 2 tables emp and phone.
emp fields are - empid, name
Ph fields are - empid, ph (office, mobile, home). Select all employees who doesn't have
any ph nos.
SELECT *
FROM employee LEFT OUTER JOIN
phone ON employee.empid = phone.empid
WHERE (phone.office IS NULL OR phone.office = ' ')
AND (phone.mobile IS NULL OR phone.mobile = ' ')
AND (phone.home IS NULL OR phone.home = ' ')
8. Find employee who is living in more than one city.
Two Tables:
Emp City
Empid Empid
empName City
Salary
SELECT empname, fname, lname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city
GROUP BY empid
HAVING COUNT(empid) > 1))
9. Find all employees who is living in the same city. (table is same as above)
SELECT fname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city a
WHERE city IN
(SELECT city
FROM city b
GROUP BY city
HAVING COUNT(city) > 1)))
10. There is a table named MovieTable with three columns - moviename, person and role.
Write a query which gets the movie details where Mr. Amitabh and Mr. Vinod acted and
their role is actor.
SELECT DISTINCT m1.moviename
FROM MovieTable m1 INNER JOIN
MovieTable m2 ON m1.moviename = m2.moviename
WHERE (m1.person = 'amitabh' AND m2.person = 'vinod' OR
m2.person = 'amitabh' AND m1.person = 'vinod') AND (m1.role =
'actor') AND (m2.role = 'actor')
ORDER BY m1.moviename
11. There are two employee tables named emp1 and emp2. Both contains same structure
(salary details). But Emp2 salary details are incorrect and emp1 salary details are correct.
So, write a query which corrects salary details of the table emp2
update a set a.sal=b.sal from emp1 a, emp2 b where a.empid=b.empid
12. Given a Table named “Students” which contains studentid, subjectid and marks. Where
there are 10 subjects and 50 students. Write a Query to find out the Maximum marks
obtained in each subject.
13. In this same tables now write a SQL Query to get the studentid also to combine with
previous results.
14. Three tables – student , course, marks – how do go @ finding name of the students who
got max marks in the diff courses.
SELECT student.name, course.name AS coursename, marks.sid,
marks.mark
FROM marks INNER JOIN
student ON marks.sid = student.sid INNER JOIN
course ON marks.cid = course.cid
WHERE (marks.mark =
(SELECT MAX(Mark)
FROM Marks MaxMark
WHERE MaxMark.cID = Marks.cID))
15. There is a table day_temp which has three columns dayid, day and temperature. How do
I write a query to get the difference of temperature among each other for seven days of a
week?
SELECT a.dayid, a.dday, a.tempe, a.tempe - b.tempe AS Difference
FROM day_temp a INNER JOIN
day_temp b ON a.dayid = b.dayid + 1
OR
Select a.day, a.degree-b.degree from temperature a, temperature b
where a.id=b.id+1
16. There is a table which contains the names like this. a1, a2, a3, a3, a4, a1, a1, a2 and
their salaries. Write a query to get grand total salary, and total salaries of individual
employees in one query.
SELECT empid, SUM(salary) AS salary
FROM employee
GROUP BY empid WITH ROLLUP
ORDER BY empid
17. How to know how many tables contains empno as a column in a database?
SELECT COUNT(*) AS Counter
FROM syscolumns
WHERE (name = 'empno')
18. Find duplicate rows in a table? OR I have a table with one column which has many
records which are not distinct. I need to find the distinct values from that column
and number of times it’s repeated.
SELECT sid, mark, COUNT(*) AS Counter
FROM marks
GROUP BY sid, mark
HAVING (COUNT(*) > 1)
19. How to delete the rows which are duplicate (don’t delete both duplicate records).
SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1
AND b.age1 = a.age1) > 1
DATA TYPES
38. What are the data types in SQL
bigint Binary bit char cursor
datetime Decimal float image int
money Nchar ntext nvarchar real
smalldatetime Smallint smallmoney text timestamp
tinyint Varbinary Varchar uniqueidentifier
39. Difference between char and nvarchar / char and varchar data-type?
char[(n)] - Fixed-length non-Unicode character data with length of n bytes. n must be a
value from 1 through 8,000. Storage size is n bytes. The SQL-92 synonym for char is
character.
nvarchar(n) - Variable-length Unicode character data of n characters. n must be a value
from 1 through 4,000. Storage size, in bytes, is two times the number of characters
entered. The data entered can be 0 characters in length. The SQL-92 synonyms for
nvarchar are national char varying and national character varying.
varchar[(n)] - Variable-length non-Unicode character data with length of n bytes. n must
be a value from 1 through 8,000. Storage size is the actual length in bytes of the data
entered, not n bytes. The data entered can be 0 characters in length. The SQL-92
synonyms for varchar are char varying or character varying.
40. GUID datasize?
128bit
41. How GUID becoming unique across machines?
To ensure uniqueness across machines, the ID of the network card is used (among
others) to compute the number.
42. What is the difference between text and image data type?
Text and image. Use text for character data if you need to store more than 255 characters
in SQL Server 6.5, or more than 8000 in SQL Server 7.0. Use image for binary large
objects (BLOBs) such as digital images. With text and image data types, the data is not
stored in the row, so the limit of the page size does not apply.All that is stored in the row
is a pointer to the database pages that contain the data.Individual text, ntext, and image
values can be a maximum of 2-GB, which is too long to store in a single data row.
JOINS
43. What are joins?
Sometimes we have to select data from two or more tables to make our result complete.
We have to perform a join.
44. How many types of Joins?
Joins can be categorized as:
Inner joins (the typical join operation, which uses some comparison operator like
= or <>). These include equi-joins and natural joins.
Inner joins use a comparison operator to match rows from two tables based on
the values in common columns from each table. For example, retrieving all rows
where the student identification number is the same in both the students and
courses tables.
Outer joins. Outer joins can be a left, a 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. (A Cartesian join will get you a Cartesian product. A
Cartesian join is when you join every row of one table to every row of another
table. You can also get one by joining every row of a table to every row of itself.)
2. What is self join?
A table can be joined to itself in a self-join.
3. What are the differences between UNION and JOINS?
A join selects columns from 2 or more tables. A union selects rows.
4. Can I improve performance by using the ANSI-style joins instead of the old-
style joins?
Code Example 1:
select o.name, i.name
from sysobjects o, sysindexes i
where o.id = i.id
Code Example 2:
select o.name, i.name
from sysobjects o inner join sysindexes i
on o.id = i.id
You will not get any performance gain by switching to the ANSI-style JOIN
syntax.
Using the ANSI-JOIN syntax gives you an important advantage: Because the join
logic is cleanly separated from the filtering criteria, you can understand the query
logic more quickly.
The SQL Server old-style JOIN executes the filtering conditions before executing
the joins, whereas the ANSI-style JOIN reverses this procedure (join logic
precedes filtering).
Perhaps the most compelling argument for switching to the ANSI-style JOIN is
that Microsoft has explicitly stated that SQL Server will not support the old-style
OUTER JOIN syntax indefinitely. Another important consideration is that the
ANSI-style JOIN supports query constructions that the old-style JOIN syntax
does not support.
5. What is derived table?
Derived tables are SELECT statements in the FROM clause referred to by an
alias or a user-specified name. The result set of the SELECT in the FROM clause
forms a table used by the outer SELECT statement. For example, this SELECT
uses a derived table to find if any store carries all book titles in the pubs
database:
SELECT ST.stor_id, ST.stor_name
FROM stores AS ST,
(SELECT stor_id, COUNT(DISTINCT title_id) AS
title_count
FROM sales
GROUP BY stor_id
) AS SA
WHERE ST.stor_id = SA.stor_id
AND SA.title_count = (SELECT COUNT(*) FROM titles)
STORED PROCEDURE
6. What is Stored procedure?
A stored procedure is a set of Structured Query Language (SQL) statements that
you assign a name to and store in a database in compiled form so that you can
share it between a number of programs.
They allow modular programming.
They allow faster execution.
They can reduce network traffic.
They can be used as a security mechanism.
7. What are the different types of Storage Procedure?
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.
calling proc.
DECLARE @factorial int
EXEC dbo.sp_calcfactorial 4, @factorial OUT
SELECT @factorial
10. Nested Triggers
Triggers are nested when a trigger performs an action that initiates another
trigger, which can initiate another trigger, and so on. Triggers can be nested up to
32 levels, and you can control whether triggers can be nested through the nested
triggers server configuration option.
11. What is an extended stored procedure? Can you instantiate a COM object
by using T-SQL?
An extended stored procedure is a function within a DLL (written in a
programming language like C, C++ using Open Data Services (ODS) API) that
can be called from T-SQL, just the way we call normal stored procedures using
the EXEC statement.
12. Difference between view and stored procedure?
Views can have only select statements (create, update, truncate, delete
statements are not allowed) Views cannot have “select into”, “Group by”
“Having”, ”Order by”
13. What is a Function & what are the different user defined functions?
Function is a saved Transact-SQL routine that returns a value. User-defined
functions cannot be used to perform a set of actions that modify the global
database state. User-defined functions, like system functions, can be invoked
from a query. They also can be executed through an EXECUTE statement like
stored procedures.
1. Scalar Functions
Functions are scalar-valued if the RETURNS clause specified one of the scalar
data types
2. Inline Table-valued Functions
If the RETURNS clause specifies TABLE with no accompanying column list, the
function is an inline function.
3. Multi-statement Table-valued Functions
If the RETURNS clause specifies a TABLE type with columns and their data
types, the function is a multi-statement table-valued function.
2. What are the difference between a function and a stored procedure?
1. Functions can be used in a select statement where as procedures cannot
2. Procedure takes both input and output parameters but Functions takes only input
parameters
3. Functions cannot return values of type text, ntext, image & timestamps where as
procedures can
4. Functions can be used as user defined datatypes in create table but procedures
cannot
***Eg:-create table <tablename>(name varchar(10),salary getsal(name))
Here getsal is a user defined function which returns a salary type, when table is
created no storage is allotted for salary type, and getsal function is also not
executed, But when we are fetching some values from this table, getsal function
get’s executed and the return
Type is returned as the result set.
TRIGGER
3. What is Trigger? What is its use? What are the types of Triggers? What are
the new kinds of triggers in sql 2000? When should one use "instead of
Trigger"?
Microsoft® SQL Serve 2000 triggers are a special class of stored procedure
defined to execute automatically when an UPDATE, INSERT, or DELETE
statement is issued against a table or view. Triggers are powerful tools that sites
can use to enforce their business rules automatically when data is modified.
The CREATE TRIGGER statement can be defined with the FOR UPDATE, FOR
INSERT, or FOR DELETE clauses to target a trigger to a specific class of data
modification actions. When FOR UPDATE is specified, the IF UPDATE
(column_name) clause can be used to target a trigger to updates affecting a
particular column.
You can use the FOR clause to specify when a trigger is executed:
AFTER - The trigger executes after the statement that triggered it completes. If
the statement fails with an error, such as a constraint violation or syntax error, the
trigger is not executed. AFTER triggers cannot be specified for views, they can
only be specified for tables. You can specify multiple AFTER triggers for each
triggering action (INSERT, UPDATE, or DELETE). If you have multiple AFTER
triggers for a table, you can use sp_settriggerorder to define which AFTER
trigger fires first and which fires last. All other AFTER triggers besides the first
and last fire in an undefined order which you cannot control. AFTER is the default
in SQL Server 2000. You could not specify AFTER or INSTEAD OF in SQL
Server version 7.0 or earlier, all triggers in those versions operated as AFTER
triggers.
INSTEAD OF -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.
An INSTEAD OF trigger can take actions such as:
• Ignoring parts of a batch.
• Not processing a part of a batch and logging the problem rows.
• Taking an alternative action if an error condition is encountered.
In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for
UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone,
and you could create multiple triggers per each action. But in 7.0 there's no way to control
the order in which the triggers fire. In SQL Server 2000 you could specify which trigger
fires first or fires last using sp_settriggerorder.
Triggers can't be invoked on demand. They get triggered only when an associated action
(INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be
used to extend the referential integrity checks, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0,
triggers fire only after the data modification operation happens. So in a way, they are
called post triggers. But in SQL Server 2000 you could create pre triggers also.
LOCK
4. What are locks?
Microsoft® SQL Server™ 2000 uses locking to ensure transactional integrity and
database consistency. Locking prevents users from reading data being changed
by other users, and prevents multiple users from changing the same data at the
same time. If locking is not used, data within the database may become logically
incorrect, and queries executed against that data may produce unexpected
results.
5. What are the different types of locks?
SQL Server uses these resource lock modes.
Lock mode Description
Used for operations that do not change or update data (read-only operations), such as
Shared (S)
a SELECT statement.
Used on resources that can be updated. Prevents a common form of deadlock that
Update (U) occurs when multiple sessions are reading, locking, and potentially updating
resources later.
Exclusive Used for data-modification operations, such as INSERT, UPDATE, or DELETE.
(X) Ensures that multiple updates cannot be made to the same resource at the same time.
Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS),
Intent
intent exclusive (IX), and shared with intent exclusive (SIX).
Used when an operation dependent on the schema of a table is executing. The types
Schema
of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Bulk Update
Used when bulk-copying data into a table and the TABLOCK hint is specified.
(BU)
6. What is a dead lock? Give a practical sample? How you can minimize the
deadlock situation? What is a deadlock and what is a live lock? How will
you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of
data, attempt to acquire a lock on the other's piece. Each process would wait
indefinitely for the other to release the lock, unless one of the user processes is
terminated. SQL Server detects deadlocks and terminates one user's process.
A livelock is one, where a request for an exclusive lock is repeatedly denied
because a series of overlapping shared locks keeps interfering. SQL Server
detects the situation after four denials and refuses further shared locks. A livelock
also occurs when read transactions monopolize a table or page, forcing a write
transaction to wait indefinitely.
7. nolock?
Locking Hints 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 required.
These locking hints override the current transaction isolation level for the
session.
Note The SQL Server query optimizer automatically makes the correct
determination. It is recommended that table-level locking hints be used to change
the default locking behavior only when necessary. Disallowing a locking level can
affect concurrency adversely.
VIEW
10. What is View? Use? Syntax of View?
A view is a virtual table made up of data from base tables and other views, but
not stored separately.
Views simplify users perception of the database (can be used to present only the
necessary information while hiding details in underlying relations)
Views improve data security preventing undesired accesses
Views facilite the provision of additional data independence
11. Does the View occupy memory space?
No
12. Can u drop a table if it has a view?
Views or tables participating in a view created with the SCHEMABINDING clause
cannot be dropped, unless the view is dropped or changed so that it no longer
has schema binding. In addition, ALTER TABLE statements on tables that
participate in views having schema binding will fail if these statements affect the
view definition.
If the view is not created using SCHEMABINDING, then we can drop the table.
13. Why doesn't SQL Server permit an ORDER BY clause in the definition of a
view?
SQL Server excludes an ORDER BY clause from a view to comply with the ANSI
SQL-92 standard. Because analyzing the rationale for this standard requires a
discussion of the underlying structure of the structured query language (SQL)
and the mathematics upon which it is based, we can't fully explain the restriction
here. However, if you need to be able to specify an ORDER BY clause in a view,
consider using the following workaround:
USE pubs
GO
CREATE VIEW AuthorsByName
AS
SELECT TOP 100 PERCENT *
FROM authors
ORDER BY au_lname, au_fname
GO
The TOP construct, which Microsoft introduced in SQL Server 7.0, is most useful
when you combine it with the ORDER BY clause. The only time that SQL Server
supports an ORDER BY clause in a view is when it is used in conjunction with
the TOP keyword. Note that the TOP keyword is a SQL Server extension to the
ANSI SQL-92 standard.
TRANSACTION
14. What is Transaction?
A transaction is a sequence of operations performed as a single logical unit of
work. A logical unit of work must exhibit four properties, called the ACID
(Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a
transaction:
Atomicity - A transaction must be an atomic unit of work; either all of its data
modifications are performed or none of them is performed.
Consistency - When completed, a transaction must leave all data in a consistent
state. In a relational database, all rules must be applied to the transaction's
modifications to maintain all data integrity. All internal data structures, such as B-
tree indexes or doubly-linked lists, must be correct at the end of the transaction.
Isolation - Modifications made by concurrent transactions must be isolated from
the modifications made by any other concurrent transactions. A transaction either
sees data in the state it was in before another concurrent transaction modified it,
or it sees the data after the second transaction has completed, but it does not
see an intermediate state. This is referred to as serializability because it results in
the ability to reload the starting data and replay a series of transactions to end up
with the data in the same state it was in after the original transactions were
performed.
Durability - After a transaction has completed, its effects are permanently in
place in the system. The modifications persist even in the event of a system
failure.
15. After one Begin Transaction a truncate statement and a RollBack
statements are there. Will it be rollbacked? Since the truncate statement
does not perform logged operation how does it RollBack?
It will rollback.
**
16. Given a SQL like
Begin Tran
Select @@Rowcount
Begin Tran
Select @@Rowcount
Begin Tran
Select @@Rowcount
Commit Tran
Select @@Rowcount
RollBack
Select @@Rowcount
RollBack
Select @@Rowcount
What is the value of @@Rowcount at each stmt levels?
Ans : 0 – zero.
@@ROWCOUNT - Returns the number of rows affected by the last statement.
@@TRANCOUNT - Returns the number of active transactions for the current
connection.
Each Begin Tran will add count, each commit will reduce count and ONE rollback
will make it 0.
OTHER
17. What are the constraints for Table Constraints define rules regarding the
values allowed in columns and are the standard mechanism for enforcing
integrity. SQL Server 2000 supports five classes of constraints.
NOT NULL
CHECK
UNIQUE
PRIMARY KEY
FOREIGN KEY
18. There are 50 columns in a table. Write a query to get first 25 columns
Ans: Need to mention each column names.
19. How to list all the tables in a particular database?
USE pubs
GO
sp_help
20. What are cursors? Explain different types of cursors. What are the
disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the result sets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in
a network roundtrip, where as a normal SELECT query makes only one
roundtrip, however large the result set is. Cursors are also costly because they
require more resources and temporary storage (results in more IO operations).
Further, there are restrictions on the SELECT statements that can be used with
some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an
example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike
In this situation many developers tend to use a cursor, determine each employee's
salary and update his salary according to the above formula. But the same can be
achieved by multiple update statements or can be combined in a single UPDATE
statement as shown below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
Another situation in which developers tend to use cursors: You need to call a stored
procedure when a column in a particular row meets certain condition. You don't have to
use cursors for this. This can be achieved using WHILE loop, as long as there is a unique
key to identify each row. For examples of using WHILE loop for row by row processing,
check out the 'My code library' section of my site or search for WHILE.
Eliminate duplicative columns from the same table. Clearly, the Subordinate1-
Subordinate4 columns are duplicative. What happens when we need to add or remove a
subordinate?
Subordinate
Bob Jim
Bob Mary
Bob Beth
Mary Mike
Mary Jason
Mary Carol
Mary Mark
Jim Alan
Create separate tables for sets of values that apply to multiple records.
Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound
key, if necessary).
For example, consider a customer's address in an accounting system. The address is
needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts
Receivable, and Collections tables. Instead of storing the customer's address as a
separate entry in each of these tables, store it in one place, either in the Customers table
or in a separate Addresses table.
Another Example:
CustNum FirstName LastName Address City State ZIP
1 John Doe 12 Main Street Sea Cliff NY 11579
2 Alan Johnson 82 Evergreen Tr Sea Cliff NY 11579
A brief look at this table reveals a small amount of redundant data. We're storing the "Sea
Cliff, NY 11579" and "Miami, FL 33157" entries twice each. Additionally, if the ZIP code for
Sea Cliff were to change, we'd need to make that change in many places throughout the
database. Our new table (let's call it ZIPs) might look like this:
Values in a record that are not part of that record's key do not belong in the table. In
general, any time the contents of a group of fields may apply to more than a single record
in the table, consider placing those fields in a separate table.
For example, in an Employee Recruitment table, a candidate's university name and
address may be included. But you need a complete list of universities for group mailings.
If university information is stored in the Candidates table, there is no way to list
universities with no current candidates. Create a separate Universities table and link it to
the Candidates table with a university code key.
Another Example :
The total can be derived by multiplying the unit price by the quantity, therefore it's not fully
dependent upon the primary key. We must remove it from the table to comply with the
third normal form:
http://databases.about.com/library/weekly/aa091601a.htm
Domain/key normal form (DKNF). A key uniquely identifies each row in a table. A
domain is the set of permissible values for an attribute. By enforcing key and domain
restrictions, the database is assured of being freed from modification anomalies. DKNF is
the normalization level that most designers aim to achieve.
**
Remember, these normalization guidelines are cumulative. For a database to be in 2NF,
it must first fulfill all the criteria of a 1NF database.
46. If a database is normalized by 3 NF then how many number of tables it
should contain in minimum? How many minimum if 2NF and 1 NF?
47. What is denormalization and when would you go for it?
As the name indicates, denormalization is the reverse process of normalization.
It's the controlled introduction of redundancy in to the database design. It helps
improve the query performance as the number of joins could be reduced.
48. How can I randomly sort query results?
To randomly order rows, or to return x number of randomly chosen rows, you can
use the RAND function inside the SELECT statement. But the RAND function is
resolved only once for the entire query, so every row will get same value. You can
use an ORDER BY clause to sort the rows by the result from the NEWID
function, as the following code shows:
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
49. sp_who
Provides information about current Microsoft® SQL Server™ users and
processes. The information returned can be filtered to return only those
processes that are not idle.
50. Have you worked on Dynamic SQL? How will You handled “ (Double
Quotes) in Dynamic SQL?
51. How to find dependents of a table?
Verify dependencies with sp_depends before dropping an object
52. What is the difference between a CONSTRAINT AND RULE?
Rules are a backward-compatibility feature that perform some of the same
functions as CHECK constraints. CHECK constraints are the preferred, standard
way to restrict the values in a column. CHECK constraints are also more concise
than rules; there can only be one rule applied to a column, but multiple CHECK
constraints can be applied. CHECK constraints are specified as part of the
CREATE TABLE statement, while rules are created as separate objects and then
bound to the column.
53. How to call a COM dll from SQL Server 2000?
sp_OACreate - Creates an instance of the OLE object on an instance of
Microsoft® SQL Server
Syntax
sp_OACreate progid, | clsid,
objecttoken OUTPUT
[ , context ]
context - Specifies the execution context in which the newly created OLE object runs. If
specified, this value must be one of the following:
1 = In-process (.dll) OLE server only
4 = Local (.exe) OLE server only
5 = Both in-process and local OLE server allowed
Examples
A. Use Prog ID - This example creates a SQL-DMO SQLServer object by using its ProgID.
B. Use CLSID - This example creates a SQL-DMO SQLServer object by using its CLSID.
TOOLS
63. Have you ever used DBCC command? Give an example for it.
The Transact-SQL programming language provides DBCC statements that act as
Database Console Commands for Microsoft® SQL Serve 2000. These
statements check the physical and logical consistency of a database. Many
DBCC statements can fix detected problems. Database Console Command
statements are grouped into these categories.
Statement category Perform
Maintenance statements Maintenance tasks on a database, index, or filegroup.
Miscellaneous statements Miscellaneous tasks such as enabling row-level locking or removing a dynamic-link library (
Status statements Status checks.
Validation statements Validation operations on a database, table, index, catalog, filegroup, system tables, or allocati
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTI
SHRINKDATABASE, DBCC SHRINKFILE etc.
64. How do you use DBCC statements to monitor various aspects of a SQL
server installation?
65. What is the output of DBCC Showcontig statement?
Displays fragmentation information for the data and indexes of the specified
table.
66. How do I reset the identity column?
You can use the DBCC CHECKIDENT statement, if you want to reset or reseed
the identity column. For example, if you need to force the current identity value in
the jobs table to a value of 100, you can use the following:
USE pubs
GO
DBCC CHECKIDENT (jobs, RESEED, 100)
GO
67. About SQL Command line executables
Utilities
bcp
console
isql
sqlagent
sqldiag
sqlmaint
sqlservr
vswitch
dtsrun
dtswiz
isqlw
itwiz
odbccmpt
osql
rebuildm
sqlftwiz
distrib
logread
replmerg
snapshot
scm
regxmlss
68. What is DTC?
The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction
manager that allows client applications to include several different sources of
data in one transaction. MS DTC coordinates committing the distributed
transaction across all the servers enlisted in the transaction.
69. What is DTS? Any drawbacks in using DTS?
Microsoft® SQL Server™ 2000 Data Transformation Services (DTS) is a set of
graphical tools and programmable objects that lets you extract, transform, and
consolidate data from disparate sources into single or multiple destinations.
70. What is BCP?
The bcp utility copies data between an instance of Microsoft® SQL Server™
2000 and a data file in a user-specified format.
C:\Documents and Settings\sthomas>bcp
usage: bcp {dbtable | query} {in | out | queryout | format}
datafile
[-m maxerrors] [-f formatfile] [-e errfile]
[-F firstrow] [-L lastrow] [-b batchsize]
[-n native type] [-c character type] [-w wide character
type]
[-N keep non-text native] [-V file format version] [-q
quoted identifier]
[-C code page specifier] [-t field terminator] [-r row
terminator]
[-i inputfile] [-o outfile] [-a packetsize]
[-S server name] [-U username] [-P password]
[-T trusted connection] [-v version] [-R regional enable]
[-k keep null values] [-E keep identity values]
[-h "load hints"]
71. How can I create a plain-text flat file from SQL Server as input to another
application?
One of the purposes of Extensible Markup Language (XML) is to solve
challenges like this, but until all applications become XML-enabled, consider
using our faithful standby, the bulk copy program (bcp) utility. This utility can do
more than just dump a table; bcp also can take its input from a view instead of
from a table. After you specify a view as the input source, you can limit the output
to a subset of columns or to a subset of rows by selecting appropriate filtering
(WHERE and HAVING) clauses.
More important, by using a view, you can export data from multiple joined tables.
The only thing you cannot do is specify the sequence in which the rows are
written to the flat file, because a view does not let you include an ORDER BY
clause in it unless you also use the TOP keyword.
If you want to generate the data in a particular sequence or if you cannot predict
the content of the data you want to export, be aware that in addition to a view,
bcp also supports using an actual query. The only "gotcha" about using a query
instead of a table or view is that you must specify queryout in place of out in the
bcp command line.
For example, you can use bcp to generate from the pubs database a list of
authors who reside in California by writing the following code:
bcp "SELECT * FROM pubs..authors WHERE state = 'CA'"
queryout c:\CAauthors.txt -c -T -S
72. What are the different ways of moving data/databases between servers and
databases in SQL Server?
There are lots of options available, you have to choose your option depending
upon your requirements. Some of the options you have are:
BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP,
logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to
generate data.
73. How will I export database?
Through DTS - Import/Export wizard
Backup - through Complete/Differential/Transaction Log
74. How to export database at a particular time, every week?
Backup - Schedule
DTS - Schedule
Jobs - create a new job
75. How do you load large data to the SQL server database?
bcp
76. How do you transfer data from text file to database (other than DTS)?
bcp
77. What is OSQL and ISQL utility?
The osql utility allows you to enter Transact-SQL statements, system
procedures, and script files. This utility uses ODBC to communicate with the
server.
The isql utility allows you to enter Transact-SQL statements, system procedures,
and script files; and uses DB-Library to communicate with Microsoft® SQL
Server™ 2000.
All DB-Library applications, such as isql, work as SQL Server 6.5–level clients
when connected to SQL Server 2000. They do not support some SQL Server
2000 features.
The osql utility is based on ODBC and does support all SQL Server 2000
features. Use osql to run scripts that isql cannot run.
78. What Tool you have used for checking Query Optimization? What is the use
of profiler in sql server? What is the first thing u look at in a SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor
events in an instance of Microsoft® SQL Server™. You can capture and save
data about each event to a file or SQL Server table to analyze later. For example,
you can monitor a production environment to see which stored procedures is
hampering performance by executing too slowly.
Use SQL Profiler to:
Monitor the performance of an instance of SQL Server.
Debug Transact-SQL statements and stored procedures.
Identify slow-executing queries.
Test SQL statements and stored procedures in the development phase of a
project by single-stepping through statements to confirm that the code works as
expected.
Troubleshoot problems in SQL Server by capturing events on a production
system and replaying them on a test system. This is useful for testing or
debugging purposes and allows users to continue using the production system
without interference.
Audit and review activity that occurred on an instance of SQL Server. This allows a
security administrator to review any of the auditing events, including the success and
failure of a login attempt and the success and failure of permissions in accessing
statements and objects.
Permissions
79. A user is a member of Public role and Sales role. Public role has the
permission to select on all the table, and Sales role, which doesn’t have a
select permission on some of the tables. Will that user be able to select
from all tables?
**
80. If a user does not have permission on a table, but he has permission to a
view created on it, will he be able to view the data in table?
Yes.
81. Describe Application Role and explain a scenario when you will use it?
**
82. What is the difference between the REPEATABLE READ and SERIALIZE
isolation levels?
The level at which a transaction is prepared to accept inconsistent data is termed
the isolation level. The isolation level is the degree to which one transaction must
be isolated from other transactions. A lower isolation level increases concurrency,
but at the expense of data correctness. Conversely, a higher isolation level
ensures that data is correct, but can affect concurrency negatively. The isolation
level required by an application determines the locking behavior SQL Server
uses.
SQL-92 defines the following isolation levels, all of which are supported by SQL
Server:
Read uncommitted (the lowest level where transactions are isolated only enough
to ensure that physically corrupt data is not read).
Read committed (SQL Server default level).
Repeatable read.
Serializable (the highest level, where transactions are completely isolated from
one another).
Isolation level Dirty read Nonrepeatable read Phantom
Read uncommitted Yes Yes Yes
Read committed No Yes Yes
Repeatable read No No Yes
Serializable No No No
83. Uncommitted Dependency (Dirty Read) - Uncommitted dependency occurs when
a second transaction selects a row that is being updated by another transaction.
The second transaction is reading data that has not been committed yet and may
be changed by the transaction updating the row. For example, an editor is
making changes to an electronic document. During the changes, a second editor
takes a copy of the document that includes all the changes made so far, and
distributes the document to the intended audience.
Inconsistent Analysis (Nonrepeatable Read) Inconsistent analysis occurs when a
second transaction accesses the same row several times and reads different
data each time. Inconsistent analysis is similar to uncommitted dependency in
that another transaction is changing the data that a second transaction is
reading. However, in inconsistent analysis, the data read by the second
transaction was committed by the transaction that made the change. Also,
inconsistent analysis involves multiple reads (two or more) of the same row and
each time the information is changed by another transaction; thus, the term
nonrepeatable read. For example, an editor reads the same document twice, but
between each reading, the writer rewrites the document. When the editor reads
the document for the second time, it has changed.
Phantom Reads Phantom reads occur when an insert or delete action is
performed against a row that belongs to a range of rows being read by a
transaction. The transaction's first read of the range of rows shows a row that no
longer exists in the second or succeeding read, as a result of a deletion by a
different transaction. Similarly, as the result of an insert by a different transaction,
the transaction's second or succeeding read shows a row that did not exist in the
original read. For example, an editor makes changes to a document submitted by
a writer, but when the changes are incorporated into the master copy of the
document by the production department, they find that new unedited material has
been added to the document by the author. This problem could be avoided if no
one could add new material to the document until the editor and production
department finish working with the original document.
84. After removing a table from database, what other related objects have to be
dropped explicitly?
(view, SP)
85. You have a SP names YourSP and have the a Select Stmt inside the SP. You
also have a user named YourUser. What permissions you will give him for
accessing the SP.
**
86. Different Authentication modes in Sql server? If a user is logged under
windows authentication mode, how to find his userid?
There are Three Different authentication modes in sqlserver.
Administration
4. Explain the architecture of SQL Server?
**
5. Different types of Backups?
45. What are ‘jobs’ in SQL Server? How do we create one? What is tasks?
Using SQL Server Agent jobs, you can automate administrative tasks and run
them on a recurring basis.
**
46. What is database replication? What are the different types of replication
you can set up in SQL Server? How are they used?
Replication is the process of copying/moving data between databases on the
same or different servers. SQL Server supports the following types of replication
scenarios:
Snapshot replication
Transactional replication (with immediate updating subscribers, with queued
updating subscribers)
Merge replication
47. What are the different types of replications available in sqlserver and brief
about each?
**
48. What is snapshot replication how is it different from Transactional
replication?
Snapshot replication distributes data exactly as it appears at a specific moment
in time and does not monitor for updates to the data. Snapshot replication is best
used as a method for replicating data that changes infrequently or where the
most up-to-date values (low latency) are not a requirement. When
synchronization occurs, the entire snapshot is generated and sent to
Subscribers.
Snapshot replication would be preferable over transactional replication when
data changes are substantial but infrequent. For example, if a sales organization
maintains a product price list and the prices are all updated at the same time
once or twice each year, replicating the entire snapshot of data after it has
changed is recommended. Creating new snapshots nightly is also an option if
you are publishing relatively small tables that are updated only at the Publisher.
Snapshot replication is often used when needing to browse data such as price
lists, online catalogs, or data for decision support, where the most current data is
not essential and the data is used as read-only. These Subscribers can be
disconnected if they are not updating the data.
Snapshot replication is helpful when:
Data is mostly static and does not change often. When it does change, it makes
more sense to publish an entirely new copy to Subscribers.
It is acceptable to have copies of data that are out of date for a period of time.
Replicating small volumes of data in which an entire refresh of the data is
reasonable.
Snapshot replication is mostly appropriate when you need to distribute a read-only copy
of data, but it also provides the option to update data at the Subscriber. When
Subscribers only read data, transactional consistency is maintained between the
Publisher and Subscribers. When Subscribers to a snapshot publication must update
data, transactional consistency can be maintained between the Publisher and Subscriber
because the data is propagated using two-phase commit protocol (2PC),a feature of the
immediate updating option. Snapshot replication requires less constant processor
overhead than transactional replication because it does not require continuous monitoring
of data changes on source servers. If the data set being replicated is very large, it can
require substantial network resources to transmit. In deciding if snapshot replication is
appropriate, you must consider the size of the entire data set and the frequency of
changes to the data.
2. How can u look at what are the process running on SQL server? How can
you kill a process in SQL server?
Expand a server group, and then expand a server.
Expand Management, and then expand Current Activity.
Click Process Info. The current server activity is displayed in the details pane.
In the details pane, right-click a Process ID, and then click Kill Process.
Sort Order
Binary is the fastest sorting order, and is case-sensitive. If Binary is selected, the Case-
sensitive, Accent-sensitive, Kana-sensitive, and Width-sensitive options are not
available.
Use Latin1_General for the U.S. English character set (code page 1252).
Use Modern_Spanish for all variations of Spanish, which also use the same
character set as U.S. English (code page 1252).
Use Arabic for all variations of Arabic, which use the Arabic character set (code
page 1256).
Use Japanese_Unicode for the Unicode version of Japanese (code page 932),
which has a different sort order from Japanese, but the same code page (932).
7. What is the STUFF Function and how does it differ from the REPLACE
function?
8. What does it mean to have quoted_identifier on? What are the implications
of having it off?
XML
7. How can I convert data in a Microsoft Access table into XML format?
The following applications can help you convert Access data into XML format:
Access 2002, ADO 2.5, and SQLXML. Access 2002 (part of Microsoft Office XP)
enables you to query or save a table in XML format. You might be able to
automate this process. ADO 2.5 and later enables you to open the data into a
recordset, then persist the recordset in XML format, as the following code shows:
rs.Save "c:\rs.xml", adPersistXML
You can use linked servers to add the Access database to your SQL Server 2000
database so you can run queries from within SQL Server to retrieve data. Then,
through HTTP, you can use the SQLXML technology to extract the Access data in
the XML format you want.
8. What are the differences between RAW, AUTO and Explicit modes in
retrieving data from SQL Server in XML format?
NEW
9. @@IDENTITY ?
Ans: Returns the last-inserted identity value.
10. If a job is fail in sql server, how do find what went wrong?