Friday, December 14, 2007

Features in SQL Server 2000

1) User-Defined Functions.
User-Defined Functions (UDFs) - one or more Transact-SQL statements that can be used to encapsulate code for reuse. User-defined functions cannot make permanent changes to the data or modify database tables. You can’t use insert, update or select statements to modify a table. UDF can change only local objects for this UDF, such as local cursors or variables. This basically means that the function can’t perform any changes to a resource outside the function itself.

2) Distributed partitioned views.
Distributed partitioned views allow you to partition tables horizontally across multiple servers.
So, you can scale out one database server to a group of database servers that cooperate to provide the same performance levels as a cluster of database servers.

3) New data types.
There are new data types:
• bigint data type: - This type is an 8-byte integer type.
• sql_variant data type: - This type is a type that allows the storage of data values of different data types.
• table data type: - This type lets an application store temporary results as a table that you can manipulate by using a select statement or even action queries—just as you can manipulate any standard user table.

4) INSTEAD OF and AFTER Triggers.
There are INSTEAD OF and AFTER Triggers in SQL Server 2000. INSTEAD OF triggers are executed instead of the INSERT, UPDATE or DELETE triggering action. “AFTER” triggers are executed after the triggering actions.

5) Cascading Referential Integrity Constraints.
There are new ON DELETE and ON UPDATE clauses in the REFERENCES clause of the CREATE TABLE and ALTER TABLE statements.
The ON DELETE clause controls what actions are taken if you attempt to delete a row to which existing foreign keys point.
The ON UPDATE clause defines the actions that are taken if you attempt to update a candidate key value to which existing foreign keys point.

The ON DELETE and ON UPDATE clauses have two options:
• NO ACTION: - NO ACTION specifies that the deletion/updation fail with an error.
• CASCADE: - CASCADE specifies that all the rows with foreign keys pointing to the deleted/updated row are also deleted / updated.

6) XML Support.
SQL Server 2000 can use XML to insert, update, and delete values in the database, and database engine can return data as Extensible Markup Language (XML) documents.

7) Indexed Views.
Unlike standard views, in which SQL Server resolves the data-access path dynamically at execution time, the new indexed views feature lets you store views in the database just as you store tables. Indexed views, which are persistent, can significantly improve application performance by eliminating the work that the query processor must perform to resolve the views.


Rules of Normalization
Normalization is used to avoid redundancy of data and inconsistent dependencies within a table. A certain amount of Normalization will often improve performance.
First Normal Form: -
For a table to be in First Normal Form (1NF) each row must be identified, all columns in the table must contain atomic values, and each field must be unique.

Second Normal Form: -
For a table to be in Second Normal Form (2NF); it must be already in 1NF and it contains no partial key functional dependencies. In other words, a table is said to be in 2NF if it is a 1NF table where all of its columns that are not part of the key are dependent upon the whole key - not just part of it.

Third Normal Form: -
A table is considered to be in Third Normal Form (3NF) if it is already in Second Normal Form and all columns that are not part of the primary key are dependent entirely on the primary key. In other words, every column in the table must be dependent upon "the key, the whole key and nothing but the key." Eliminate columns not dependent upon the primary key of the table.

Referential Integrity: - The referential integrity of a database concerns the parent/child relationship between tables. The relationships between tables are classified as one-to-one, one-to-many, many-to-one, and many-to-many. If the child records have no parent records then they are called orphan records.

Indexing
An index is a separate table that lists in order, ascending or descending, the contents of a particular table with pointers to the records in the table. An index increases the speed at which rows are retrieved from a database. The index can consist of one column or can be a composite index composed of many columns. There are two types of indexes.
i) Clustered Indexes: - A clustered index means that the data is sorted and placed in the table in sorted order, sorted on what columns are contained in the index. Since the rows are in sorted order and an entity can exist in sorted order only once, there can be only one clustered index per table. The data rows are actually part of the index. A table should have at least one clustered index unless it is a very small table.
ii) NonClustered Indexes: - In a Nonclustered index, the data rows are not part of the index. A Nonclustered index stores pointers to the data rows in the table and is not as efficient as a clustered index but is much preferable to doing a table scan.
If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same time, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

A View is a copy of a table or tables that doesn’t exist except as a result set that is created when the view is queried.

A Trigger is a special kind of stored procedure that becomes active only when data is modified in a specified table using one or more data modification operations (Update, Insert, or Delete).

UNION combines the results of two or more queries into a single result set consisting of all the rows belonging to all queries in the union.

Joined Tables
Tables are joined for the purpose of retrieving related data from two or more tables by comparing the data in columns and forming a new table from the rows that match. The types of joins are:
i) Inner Join: An inner join is the usual join operation using a comparison operator. It displays only the rows with a match for both join tables.
ii) Outer Join: An outer join includes the left outer join, right outer join, and full outer join.
The relational operators for an outer join are:
a) Left outer join: Left join returns all the rows from the first table in the JOIN clause with NULLS for the second table’s columns if no matching row was found in the second table.
b) Right outer join: Right join returns all the rows from the second table in the JOIN clause with NULLS for the first table’s columns if no matching row was found in the first table.
c) Full outer join: When a Full Outer Join occurs and a row from either the first table or the second table does not match the selection criteria, the row is selected and the columns of the other tables are set to NULL.
iii) Cross Join: A Cross Join results in the cross product of two tables and returns the same rows as if no WHERE clause was specified in an old, non-ANSI-style.

Stored Procedure
A stored procedure is essentially a routine you create that will execute an SQL statement. There are four major reasons why using them can be beneficial.

1. They can dramatically increase security.
If you set up a series of Stored Procedures to handle all of your interaction to the data then this means that you can remove all the user rights on all of your tables and such. For example, say I create a stored procedure for inserting a new employee. I can remove everyone's rights to the actual EMPLOYEES table and require them to only do INSERTS via the stored procedure. I have effectively forced them to always insert data my way.

2. They can assist you in centralizing your code.
If I ever need to change the structure of that EMPLOYEES table I don't have to worry about any applications crashing if when they try to insert something new. Since all interaction is via that stored procedure I just have to make the updates in that one stored procedures code and nowhere else.

3. They are executed on the Server's machine.
Because they actually reside on the server's machine, they will use the process resources there as well. Generally your Database Server will be much more 'beefy' as far as processor and memory resources go than your clients machines.

4. Better than that. (They are precompiled)
The database can convert your stored procedure into binary code and execute it as one command rather than parse the SQL statement through an interpreter as if it was text. Execution speeds can be vastly improved by this alone.


Q. What are the types of User-Defined Functions available in SQL Server 2000?
There are three types of UDF in SQL Server 2000:
 Scalar functions: returns one of the scalar data types. Text, ntext, image, cursor or timestamp data types are not supported.
 Inline table-valued functions: returns a variable of data type table whose value is derived from a single SELECT statement.
 Multi-statement table-valued functions: return a table that was built with many TRANSACT-SQL statements.

Q. What is the difference between User-Defined functions and Stored Procedures?
 A stored procedure may or may not return values whereas a UDF always return values.
 The function can't perform any actions that have side effects. This basically means that the function can't perform any changes to a resource outside the function itself. You can't create a procedure that modifies data in a table, performs cursor operations on cursors that aren't local to the procedure, sends email, creates database objects, or generates a result set that is returned to the user.
 SELECT statements that return values to the user aren't allowed. The only allowable SELECT statements assign values to local variables.
 Cursor operations including DECLARE, OPEN, FETCH, CLOSE, and DEALLOCATE can all be performed in the cursor. FETCH statements in the function can't be used to return data to the user. FETCH statements in functions can be used only to assign values to local variables using the INTO keyword. This limitation is also minor because you can populate a table variable within a cursor and then return the table to the user.
 UDFs can return only one rowset to the user, whereas stored procedures can return multiple rowsets.
 UDFs cannot call stored procedures (except extended procedures), whereas stored procedures can call other procedures.
 UDFs also cannot execute dynamically constructed SQL statements.
 UDFs cannot make use of temporary tables. As an alternative, you are allowed to use table variables within a UDF. Recall however, that temporary tables are somewhat more flexible than table variables. The latter cannot have indexes (other than a primary and unique key); nor can a table variable be populated with an output of a stored procedure.
 RAISERROR statement cannot be used within a UDF. In fact, you can't even check the value of the @@ERROR global variable within a function. If you encounter an error, UDF execution simply stops, and the calling routine fails. You are allowed to write a message to the Windows error log with xp_logevent if you have permission to use this extended procedure.

Q. Difference between a "where" clause and a "having" clause
Having clause is used only with group functions whereas Where is not used with

Q. What is the basic difference between a join and a union?
A join selects columns from 2 or more tables. A union selects rows.

Q. What are foreign keys?
These are attributes of one table that have matching values in a primary key in another table, allowing for relationships between tables.

Q. What is a synonym? How is it used?
A synonym is used to reference a table or view by another name. The other name can then be written in the application code pointing to test tables in the development stage and to production entities when the code is migrated. The synonym is linked to the AUTHID that created it.

Q. What is a Cartesian product?
A Cartesian product results from a faulty query. It is a row in the results for every combination in the join tables.

Q. 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.

Q. What's the difference between a primary key and a unique key?
Both, primary and unique key enforces uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULL values, but unique key allows one NULL only.

Q. What is user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar (8). In this case you could create a user defined datatype called Flight_num_type of varchar (8) and use it across all your tables.

Q. Define candidate key, alternate key, and composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.

Q. What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.

Q. What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, and Durability.

Q. Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels:

Read Uncommitted: - A transaction can read any data, even if it is being modified by another transaction. This is the least safe isolation level but allows the highest concurrency.

Read Committed: - A transaction cannot read data that is being modified by another transaction that has not committed. This is the default isolation level in Microsoft SQL Server.

Repeatable Read: - Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. Any type of new data can be inserted during a transaction.

Serialized: - Data read by the current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction.

Q. What type of Index will get created with: CREATE INDEX myIndex ON myTable (myColumn)?
Non-clustered index; important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

Q. What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. The TRUNCATE TABLE command sets the identity value to one whereas the DELETE command retains the identity value. The TRUNCATE TABLE cannot activate a trigger.

Q. What are constraints? Explain different types of constraints.
Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

Q. What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.

Q. 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.

Q. What is database replication? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:
• Snapshot replication
• Transactional replication (with immediate updating subscribers, with queued updating subscribers)
• Merge replication

Q. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursor is a database object used to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.

Cursor Type --------- Description
ForwardOnly ---------You can only scroll forward through records. This is the default cursor type.
Static ---------A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible. The Recordset is fully navigable, forward and backward.
Dynamic ---------Additions, changes, and deletions by other users are visible, and all types of movement through the Recordset are allowed.
Keyset ---------Like the dynamic cursor type, except that you can’t see records that other users add. Deletions and other modifications made by other users are still visible.

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 resultset 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.
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.

Q. How will you copy the structure of a table without copying the data?
Create table EMPTEMP as select * from EMP where 1 = 2;

Q. 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.


Q. What is database replication? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:
 Snapshot replication
 Transactional replication (with immediate updating subscribers, with queued updating subscribers)
 Merge replication

Q. How many triggers you can have on a table? How to invoke a trigger on demand?
You can 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

Q. 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. Yes, you can instantiate a COM object from T-SQL by using sp_OACreate stored procedure.

Q. What is a self join? Explain it with an example.
Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp (empid int, mgrid int, empname char(10) )
INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2 WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid


SQL Server Limitations
Object ---------Maximum sizes/numbers
Bytes per text, ntext or image column--------- 2 GB-2
Clustered indexes per table--------- 1
Columns per index--------- 16
Columns per foreign key--------- 16
Columns per primary key--------- 16
Columns per base table--------- 1,024
Columns per SELECT statement--------- 4,096
Columns per INSERT statement--------- 1,024
Connections per client--------- Maximum value of configured connections
Database size--------- 1,048,516 TB
Databases per instance of SQL Server--------- 32,767
Files per database--------- 32,767
File size (data) --------- 32 TB
Identifier length (in characters) --------- 128
Locks per connection--------- Max. locks per server
Nested stored procedure levels--------- 32
Nested subqueries--------- 32
Nested trigger levels--------- 32
Nonclustered indexes per table--------- 249
Objects in a database--------- 2,147,483,6474
Parameters per stored procedure--------- 2,100
REFERENCES per table--------- 253
Rows per table--------- Limited by available storage
Tables per database--------- Limited by number of objects in a database
Tables per SELECT statement--------- 256
Triggers per table--------- Limited by number of objects in a database
UNIQUE indexes or constraints per table--------- 249 nonclustered and 1 clustered

No comments: