Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

What is normalization? Well a relational database is basically composed of tables that contain related data.

So the Process of organizing this data into tables is actually referred to as normalization 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. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. What's the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where as unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. What are 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. What is bit datatype and what's the information that can be stored inside a bit column? Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL. Define candidate key, alternate key, 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. 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. See CREATE DEFUALT in books online. 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, Durability. These are the properties of a transaction. 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 (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. READ COMMITTED Specifies that shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default. READ UNCOMMITTED Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels. REPEATABLE READ Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom rows can be inserted into the data set by another user and are included in later reads in the current transaction. Because concurrency is lower than the default isolation level, use this option only when necessary. SERIALIZABLE Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. This is the most restrictive of the four isolation levels. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction. Remarks Only one of the options can be set at a time, and it remains set for that connection until it is explicitly changed. This becomes the default behavior unless an optimization option is specified at the table level in the FROM clause of the statement. The setting of SET TRANSACTION ISOLATION LEVEL is set at execute or run time and not at parse time. Define Dirty Reads Reads that contain uncommitted data. Example Trn1 changes a row, trn2 reads the changed row before trn1 commits the change. If trn1 rolls back the change trn2 has read a row that never logically exist. Define Phantoms By one tas, the insertion of a new row or the deletion of an existing row in a range of rows previously read by another task that has not yet committed its transaction. The task with the uncommitted transaction cannot repeat its original read because of the change to the number of rows in the range. If a connection sets its transaction isolation level to serializable, sql server uses key-range locking to prevent phantoms. CREATE INDEX myIndex ON myTable(myColumn)

SQL FAQs 1 of 28

What type of Index will get created after executing the above statement? Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise. Explain Active/Active and Active/Passive cluster configurations Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site. Explain the architecture of SQL Server http://msdn.microsoft.com/library/default.asp?url=/library/en-us/architec/8_ar_ad_71wl.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/architec/ar_ovrvw_0mnk.asp What is lock escalation? Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server. 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 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 Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach? Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker. Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table. 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 t ime, 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. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors? Cursors allow row-by-row prcessing of the resultsets. Types of cursors: 1. Static, 2. Dynamic, 3. Forward-only, 4. 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 rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 -- 5000 hike Salary between 40000 and 55000 -- 7000 hike Salary between 55000 and 65000 -- 9000 hike In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below: UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE. Write down the general syntax for a SELECT statements covering all the options. Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax). SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY order_expression [ASC | DESC] ]

SQL FAQs 2 of 28

What is a join and explain different types of joins. Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: 1. INNER JOINs, 2. OUTER JOINs (LEFT, RIGHT, FULL) 3. CROSS JOINs. Can you have a nested transaction? Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT What is an extended stored procedure? Can you instantiate a COM object by using T-SQL? An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server. Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site. What is the system function to get the current user's user id? USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME(). What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand? Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post trig gers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers. Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED() There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better? Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful. 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 INSERT INSERT INSERT INSERT emp emp emp emp emp SELECT SELECT SELECT SELECT SELECT 1,2,'Vyas' 2,3,'Mohan' 3,NULL,'Shobha' 4,2,'Shridhar' 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 (super bosses) SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager] FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid What is database replicaion? What are the different types of replication you can set up in SQL Server? Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following

SQL FAQs 3 of 28

types of replication scenarios: 1. Snapshot replication 2. Transactional replication (with immediate updating subscribers, with queued updating subscribers) 3. Merge replication See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc. Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan? Types of backups you can create in SQL Sever 7.0+ are 1. Full database backup, 2. Differential database backup, 3. Transaction log backup, 4. Filegroup backup. 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: 1. BACKUP/RESTORE, 2. Dettaching and Attaching databases, 3. Replication, 4. DTS, 5. BCP, 6. Logshipping, 7. INSERT...SELECT, SELECT...INTO, 8. Creating INSERT scripts to generate data. 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. What is a Stored Procedure? Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. What is a trigger? Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. What is a view? If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time. What is an Index? - When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index. What are the types of indexes available with SQL Server? - There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered. What is the basic difference between clustered and a non-clustered index? - The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db. What are cursors? - Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values. When do we use the UPDATE_STATISTICS command? This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. Which TCP/IP port does SQL Server run on? SQL Server runs on port 1433 but we can also change it for better security. From where can you change the default port? From the Network Utility TCP/IP properties > Port number.both on client and the server. Can you tell me the difference between DELETE & TRUNCATE commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. Can we use Truncate command on a table which is referenced by FOREIGN KEY? No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

SQL FAQs 4 of 28

What is the use of DBCC commands? - DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. Can you give me some DBCC command options?(Database consistency check) - DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage. What command do we use to rename a db? - sp_renamedb oldname , newname Well sometimes sp_renamedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? - In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. What do you mean by COLLATION? - Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary. When do you use SQL Profiler? SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc.. What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group. Which stored procedure will you be running to add a linked server? - sp_addlinkedserver, sp_addlinkedsrvlogin What are the OS services that the SQL Server installation adds? - MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator) Can you explain the role of each service? SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers How do you troubleshoot SQL Server if its running very slow? First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes What are the authentication modes in SQL Server? Windows mode and mixed mode (SQL & Windows). Where do you think the users names and passwords will be stored in sql server? They get stored in master db in the sysxlogins table. What is log shipping? Can we do logshipping with SQL Server 7.0 Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER m which will basically bring it into the maintenance mode after which we can restore the master db. What is BCP? When do we use it? - BulkCopy is a tool used to copy huge amount of data from tables and views. But it wont copy the structures of the same. What should we do to copy the tables, schema and views from one SQL Server to another? We have to write some DTS packages for it. How many clustered indexes can be created in table? Only One What are the System Databases in SQL Server 2000? There are 4 System Databases in SQL Server 200 1. Master

SQL FAQs 5 of 28

2. 3. 4.

TempDB Model MSDB

MASTER The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. master is the database that records the existence of all other databases, including the location of the database files. master records the initialization information for SQL Server; always have a recent backup of master available. TEMPDB tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. tempdb is a global resource; the temporary tables and stored procedures for all users connected to the system are stored there. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database. Because temporary tables and stored procedures are dropped automatically on disconnect, and no connections are active when the system is shut down, there is never anything in tempdb to be saved from one session of SQL Server to another. By default, tempdb autogrows as needed while SQL Server is running. Unlike other databases, however, it is reset to its initial size each time the database engine is started. If the size defined for tempdb is small, part of your system processing load may be taken up with autogrowing tempdb to the size needed to support your workload each time to restart SQL Server. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb. MODEL The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of the new database is filled with empty pages. Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system. MSDB The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators. In SQL Server 2000 and SQL Server version 7.0, every database, including the system databases, has its own set of files and does not share those files with other databases DBCC (Database Console Commands) The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for Microsoft SQL Server 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 Maintenance statements Miscellaneous statements Perform Maintenance tasks on a database, index, or filegroup. Miscellaneous tasks such as enabling row-level locking or removing a dynamic-link library (DLL) from memory. Status checks. Validation operations on a database, table, index, catalog, filegroup, system tables, or allocation of database pages.

Status statements Validation statements

The DBCC statements of SQL Server 2000 take input parameters and return values. All DBCC statement parameters can accept both Unicode and DBCS literals. Overview of Indexes You can use an index to gain fast access to specific information in a database table. An index is a structure that orders the values of one or more columns in a database table, for example the last name (lname) column of the employee table. If you were looking for a specific employee by his or her last name, the index would help you get that information faster than if you had to search all the rows in the table. The index provides pointers to the data values stored in specified columns of the table, and then orders those pointers according to the sort order you specify. The database uses the index much as you use an index in a book: it searches the index to find a particular value and then follows the pointer to the row containing that value. In database diagrams, you can create, edit, or delete each type of index in the Indexes/Keys Property Page for a selected table. An index is saved in the database when you save the table that it is attached to, or when you save the diagram in which that table appears. For details, see creating an Index. As a general rule, you should create an index on a table only if the data in the indexed columns will be queried frequently. Indexes take up disk space and slow the adding, deleting, and updating of rows. In most situations, the speed advantages of indexes for data retrieval greatly outweigh these disadvantages. However, if your application updates data very frequently or if you have disk space constraints, you might want to limit the number of indexes. Before creating an index, you must determine what columns to use and what type of index to create. For more information, see: 1. Index Columns 2. Types of Index Index Columns You can create indexes based on a single column or on multiple columns in a database table. Multiple-column indexes enable you to distinguish between rows in which one column may have the same value. Indexes are also helpful if you often search or sort by two or more columns at a time. For example, if you often set criteria for last name and first name columns in the same query, it makes sense to create a multiple-column index on those two columns. To determine the usefulness of an index:

SQL FAQs 6 of 28

Examine the WHERE and JOIN clauses of your queries. Each column included in either clause is a possible candidate for an index. Experiment with the new index to examine its effect on the performance of running queries. Consider the number of indexes already created on your table. It is best to avoid a large number of indexes on a single table. Examine the definitions of the indexes already created on your table. It is best to avoid overlapping indexes that contain shared columns.

Examine the number of unique data values in a column and compare that number with the number of rows in the table. The result is the selectivity of that column, which can help you decide if a column is a candidate for an index and, if so, what type of index. Types of Index Depending on the functionality of your database, you can create three types of indexes - unique, primary key, and clustered - in Database Designer. Unique Index A unique index is one in which no two rows are permitted to have the same index value. Most databases prevent you from saving a table with a newly created unique index when there are duplicate key values in the existing data. Your database may also prevent the addition of new data that would create duplicate key values in the table. For example, if you create a unique index on the employee's last name (lname) in the employee table, then no two employees can share the same last name. Primary Key Index A database table often has a column or combination of columns whose value uniquely identifies each row in the table. This column is called the primary key of the table. Defining a primary key for a table in a database diagram automatically creates a primary key index that is a specific type of unique index. This index requires each value in the primary key to be unique. It also permits fast access to data when you use the primary key index in queries. For more information about primary keys, see Defining a Primary Key. Clustered Index In a clustered index, the physical order of the rows in the table is the same as the logical (indexed) order of the key values. A table can contain only one clustered index. If an index is not clustered, the physical order of the rows in the table does not match the logical order of the key values. A clustered index usually provides faster access to data than does a nonclustered index. Using the inserted and deleted Tables Two special tables are used in trigger statements: the deleted table and the inserted table. Microsoft SQL Server 2000 automatically creates and manages these tables. You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for trigger actions; however, you cannot alter the data in the tables directly. The inserted and deleted tables are used primarily in triggers to:

Extend referential integrity between tables. Insert or update data in base tables underlying a view. Check for errors and take action based on the error.

Find the difference between the state of a table before and after a data modification and take action(s) based on that difference. The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common. The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added simultaneously to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table. An update transaction is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table. When you set trigger conditions, use the inserted and deleted tables appropriately for the action that fired the trigger. Although referencing the deleted table while testing an INSERT, or the inserted table while testing a DELETE does not cause any errors, these trigger test tables do not contain any rows in these cases. Note If trigger actions depend on the number of rows a data modification effects, use tests (such as an examination of @@ROWCOUNT) for multirow data modifications (an INSERT, DELETE, or UPDATE based on a SELECT statement), and take appropriate actions. SQL Server 2000 does not allow text, ntext, or image column references in the inserted and deleted tables for AFTER triggers; however, these column references are allowed for INSTEAD OF triggers. Using the inserted and deleted Tables in INSTEAD OF Triggers The inserted and deleted tables passed to INSTEAD OF triggers defined on tables follow the same rules as the inserted and deleted tables passed to AFTER triggers. The format of the inserted and deleted tables is the same as the format of the table on which the INSTEAD OF trigger is defined. Each column in the inserted and deleted tables maps directly to a column in the base table. The rules regarding when an INSERT or UPDATE statement referencing a table with an INSTEAD OF trigger must supply values for columns are the same as if the table did not have an INSTEAD OF trigger: Values cannot be specified for computed columns or columns with a timestamp data type.

Values cannot be specified for columns with an IDENTITY property, unless IDENTITY_INSERT is ON for that column. When IDENTITY_INSERT is ON, INSERT statements must supply a value.

INSERT statements must supply values for all NOT NULL columns that do not have DEFAULT constraints. For any columns except computed, identity, or timestamp columns, values are optional for any column that allows nulls, or any NOT NULL column that has a DEFAULT definition. When an INSERT, UPDATE, or DELETE statement references a view that has an INSTEAD OF trigger, the database engine calls the trigger instead of taking any direct action against any table. The trigger must use the information presented in the inserted and deleted tables to build any statements needed to implement the requested action in the base tables even when the format of the information in the inserted and deleted tables built for the view is different than the format of the data in the base tables. The format of the inserted and deleted tables passed to an INSTEAD OF trigger defined on a view matches the select list of the SELECT statement defined for the view. For example: CREATE VIEW EmployeeNames (EmployeeID, LName, FName) AS SELECT EmployeeID, LastName, FirstName FROM Northwind.dbo.Employees The result set for this view has three columns: an int column and two nvarchar columns. The inserted and deleted tables passed to an INSTEAD OF trigger defined on the view also have an int column named EmployeeID, an nvarchar column named LName, and an nvarchar column named FName.

SQL FAQs 7 of 28

The select list of a view can also contain expressions that do not map directly to a single base table column. Some view expressions, such as a constant or function invocation, may not reference any columns and can be ignored. Complex expressions can reference multiple columns, yet the inserted and deleted tables have only one value for each inserted row. The same issues apply to simple expressions in a v iew if they reference a computed column that has a complex expression. An INSTEAD OF trigger on the view must handle these types of expressions. Recompiling a Stored Procedure As a database is changed by such actions as adding indexes or changing data in indexed columns, the original query plans used to access its tables should be optimized again by recompiling them. This optimization happens automatically the first time a stored procedure is run after Microsoft SQL Server 2000 is restarted. It also occurs if an underlying table used by the stored procedure changes. But if a new index is added from which the stored procedure might benefit, optimization does not automatically happen (until the next time the stored procedure is run after SQL Server is restarted). SQL Server provides three ways to recompile a stored procedure:

The sp_recompile system stored procedure forces a recompile of a stored procedure the next time it is run. 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. Use the WITH RECOMPILE option 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. 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. You can force the stored procedure to be recompiled by specifying the WITH RECOMPILE option when you execute the stored procedure. Use this option only if the parameter you are supplying is atypical or if the data has significantly changed since the stored procedure was created.

Note If an object referenced by a stored procedure is deleted or renamed, an error is returned when the stored procedure is executed. If, however, an object referenced in a stored procedure is replaced with an object of the same name, the stored procedure execute s without having to be recompiled. SQL SERVER This one always gets asked. For a while the database interview questions were limited to Oracle and generic database design questions. This is a set of more than a hundred Microsoft SQL Server interview questions. Some questions are open-ended, and some do not have answers. 4. 5. 6. 7. 8. 9. 10. 11. What is normalization? - Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization. What is a Stored Procedure? - Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. Can you give an example of Stored Procedure? - sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way. What is a trigger? - Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. What is a view? - If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time. What is an Index? - When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index. What are the types of indexes available with SQL Server? - There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered. What is the basic difference between clustered and a non-clustered index? - The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db. What are cursors? - Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values. When do we use the UPDATE_STATISTICS command? - This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. Which TCP/IP port does SQL Server run on? - SQL Server runs on port 1433 but we can also change it for better security. From where can you change the default port? - From the Network Utility TCP/IP properties > Port number.both on client and the server. Can you tell me the difference between DELETE & TRUNCATE commands? - Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. Can we use Truncate command on a table which is referenced by FOREIGN KEY? - No. We cannot use Truncate command on a table with Foreign Key because of referential integrity. What is the use of DBCC commands? - DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. Can you give me some DBCC command options? (Database consistency check) - DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage. What command do we use to rename a db? - sp_renamedb oldname , newname Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? - In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. What do you mean by COLLATION? - Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary. What is a Join in SQL Server? - Join actually puts data from two or more tables into a single result set. Can you explain the types of Joins that we can have with Sql Server? - There are three types of joins: Inner Join, Outer Join, Cross Join When do you use SQL Profiler? - SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..

12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26.

SQL FAQs 8 of 28

27. What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. 28. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLEDB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group. 29. Which stored procedure will you be running to add a linked server? - sp_addlinkedserver, sp_addlinkedsrvlogin 30. What are the OS services that the SQL Server installation adds? - MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator) 31. Can you explain the role of each service? - SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers 32. How do you troubleshoot SQL Server if its running very slow? - First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes 33. Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot? - First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly conf igured at client end for connection Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues. 34. What are the authentication modes in SQL Server? - Windows mode and mixed mode (SQL & Windows). 35. Where do you think the users names and passwords will be stored in sql server? - They get stored in master db in the sysxlogins table. 36. What is log shipping? Can we do logshipping with SQL Server 7.0 - Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan. 37. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? - For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER m which will basically bring it into the maintenance mode after which we can restore the master db. 38. Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take? - (I am not sure- but I think we have a command to do it). 39. What is BCP? When do we use it? - BulkCopy is a tool used to copy huge amount of data from tables and views. But it wont copy the structures of the same. 40. What should we do to copy the tables, schema and views from one SQL Server to another? - We have to write some DTS packages for it. 41. What is Index? Its purpose? Indexes in databases are similar to indexes in books. In a database, an index allows the database program to find data in a table without scanning the entire table. An index in a database is a list of values in a table with the storage locations of rows in the table that contain each value. Indexes can be created on either a single column or a combination of columns in a table and are implemented in the form of Btrees. An index contains an entry with one or more columns (the search key) from each row in a table. A B-tree is sorted on the search key, and can be searched efficiently on any leading subset of the search key. For example, an index on columns A, B, C can be searched efficiently on A, on A, B, and A, B, C. 42. Explain about Clustered and non clustered index? How to choose between a Clustered Index and a Non-Clustered Index? There are clustered and nonclustered indexes. A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored or der of the rows on disk. The leaf nodes of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Consider using a clustered index for: 1. Columns that contain a large number of distinct values. 2. Queries that return a range of values using operators such as BETWEEN, >, >=, <, and <=. 3. Columns that are accessed sequentially. 4. Queries that return large result sets. Non-clustered indexes have the same B-tree structure as clustered indexes, with two significant differences: 5. The data rows are not sorted and stored in order based on their non-clustered keys. 6. The leaf layer of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Each index row contains the non-clustered key value and one or more row locators that point to the data row (or rows if the index is not unique) having the key value. 7. Per table only 249 non clustered indexes. 43. Disadvantage of index? Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. 44. Given a scenario that I have a 10 Clustered Index in a Table to all their 10 Columns. What are the advantages and disadvantages? A: Only 1 clustered index is possible. 45. How can I enforce to use particular index? You can use index hint (index=<index_name>) after the table name. SELECT au_lname FROM authors (index=aunmind) 46. What is Index Tuning? One of the hardest tasks facing database administrators is the selection of appropriate columns for non-clustered indexes. You should consider creating non-clustered indexes on any columns that are frequently referenced in the WHERE clauses of SQL statements. Other good candidates are columns referenced by JOIN and GROUP BY operations. You may wish to also consider creating non-clustered indexes that cover all of the columns used by certain frequently issued queries. These queries are referred to as covered queries and experience excellent performance gains. Index Tuning is the process of finding appropriate column for non-clustered indexes. SQL Server provides a wonderful facility known as the Index Tuning Wizard which greatly enhances the index selection process. 47. Difference between Index defrag and Index rebuild? When you create an index in the database, the index information used by queries is stored in index pages. The sequential index pages are chained together by pointers from one page to the next. When changes are made to the data that affect the index, the information in the index can become scattered in the database. Rebuilding an index reorganizes the storage of the index data (and table data in the case of a clustered index) to remove fragmentation. This can improve disk performance by reducing the number of page reads required to obtain the requested data DBCC INDEXDEFRAG Defragments clustered and secondary indexes of the specified table or view. ** 48. What is sorting and what is the difference between sorting & clustered indexes? The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table.

SQL FAQs 9 of 28

1. 2. 3.

JOINS What are Sometimes we have to select data from two or more tables to make our result complete. We have to perform a join. How many types of Joins can be categorized as:

joins? Joins?

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 Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: join.

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.

4. 5. 6.

7. 8.

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.) What is self join? A table can be joined to itself in a self-join. What are the differences between UNION and JOINS? A join selects columns from 2 or more tables. A union selects rows. 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. STORED PROCEDURE 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.

9.

They can be used as a security mechanism. What are the different types of Storage Procedure? . Temporary Stored Procedures - SQL Server supports two types of temporary procedures: local and global. A local temporary procedure is visible only to the connection that created it. A global temporary procedure is available to all connections. Local temporary procedures are automatically dropped at the end of the current session. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends. Temporary procedures named with # and ## can be created by any user. a. System stored procedures are created and stored in the master database and have the sp_ prefix.(or xp_) System stored procedures can be executed from any database without having to qualify the stored procedure name fully using the database name master. (If any user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.) b. Automatically Executing Stored Procedures - One or more stored procedures can execute automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process. The procedure(s) cannot have any input parameters. c. User stored procedure

They allow modular programming. They allow faster execution. They can reduce network traffic.

49. How do I mark the stored procedure to automatic execution? You can use the sp_procoption system stored procedure to mark the stored procedure to automatic execution when the SQL Server will start. Only objects in the master database owned by dbo can have the startup setting changed and this option is restricted to objects that have no parameters. USE master EXEC sp_procoption 'indRebuild', 'startup', 'true')3 10. What are the difference between a function and a stored procedure? 0. Functions can be used in a select statement where as procedures cannot

SQL FAQs 10 of 28

1. 2. 3.

11. How

Procedure takes both input and output parameters but Functions takes only input parameters Functions cannot return values of type text, ntext, image & timestamps where as procedures can 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 gets executed and the return Type is returned as the result set. to debug a stored procedure?

TRIGGER 12. What is Trigger? What is its use? What are the types of Triggers? What are the new kinds of triggers in sql 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 (default) - 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. 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. 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. 13. Difference between trigger and stored procedure? Trigger will get execute automatically when an UPDATE, INSERT, or DELETE statement is issued against a table or view. We have to call stored procedure manually, or it can execute automatic when the SQL Server starts (You can use the sp_procoption system stored procedure to mark the stored procedure to automatic execution when the SQL Server will start. 14. Drawback of trigger? Its alternative solution? Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integr ity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. LOCK 15. 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. 16. What are the different types of locks? SQL Server uses these resource lock modes. Lock mode Shared (S) Description Used for operations that do not change or update data (read-only operations), such as a SELECT statement. Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are Update (U) reading, locking, and potentially updating resources later. Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be Exclusive (X) 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 exclusive (IX), and shared Intent with intent exclusive (SIX). Used when an operation dependent on the schema of a table is executing. The types of schema locks are: schema 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) 17. 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.) 18. What is isolation level? An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. 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

SQL FAQs 11 of 28

determines the locking behavior SQL SQL-92 defines the following isolation levels, all of which are supported by SQL Server:

Server

uses.

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). Dirty read Yes No No No Nonrepeatable read Yes Yes No No Phantom Yes Yes Yes No

Isolation level Read uncommitted Read committed Repeatable read Serializable

19. TRANSACTION 20. 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 doublylinked 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. What is DDL? Data definition language (DDL) statements are SQL statements that support the definition or declaration of database objects (for example, CREATE TABLE, DROP TABLE, and ALTER TABLE). You can use the ADO Command object to issue DDL statements. To differentiate DDL statements from a table or stored procedure name, set the CommandType property of the Command object to adCmdText. Because executing DDL queries with this method does not generate any recordsets, there is no need for a Recordset object. What is DML? Data Manipulation Language (DML), which is used to select, insert, update, and delete data in the objects defined using DDL What are keys in RDBMS? What is a primary key/ foreign key? There are two kinds of keys. A primary key is a set of columns from a table that are guaranteed to have unique values for each row of that table. Foreign keys are attributes of one table that have matching values in a primary key in another table, allowing for relationships between tables. What is the difference between Primary Key and Unique Key? Both primary key and unique key enforce 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 NULLs, but unique key allows one NULL only. Define candidate key, alternate key, 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. What is the Referential Integrity? Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value. 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. What is normalization? Explain different levels of normalization? Explain Third normalization form with an example? The process of refining tables, keys, columns, and relationships to create an efficient database is called normalization. This should eliminates unnecessary duplication and provides a rapid search path to all necessary information. Some of the benefits of normalization are: Data integrity (because there is no redundant, neglected data) Optimized queries (because normalized tables produce rapid, efficient joins) Faster index creation and sorting (because the tables have fewer columns) Faster UPDATE performance (because there are fewer indexes per table) Improved concurrency resolution (because table locks will affect less data) Eliminate redundancy There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third norma l form." Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications.

21.

22. 23.

24.

25.

26. 27. 28.

6.

First Normal Form (1NF)

SQL FAQs 12 of 28

Eliminate repeating groups in individual tables Create a separate table for each set of related data. Identify each set of related data with a primary key. use multiple fields in a single table to store similar data.

Do not Example

Bob Mary Jim

Subordinate1 Jim Mike Alan

Subordinate2 Mary Jason

Subordinate3 Beth Carol

Subordinate4 Mark

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? Subordinates Jim, Mary, Beth Mike, Jason, Carol, Mark Alan

Bob Mary Jim

This solution is closer, but it also falls short of the mark. The subordinates column is still duplicative and non-atomic. What happens when we need to add or remove a subordinate? We need to read and write the entire contents of the table. Thats not a big deal in this situation, but what if one manager had one hundred employees? Also, it complicates the process of selecting data from the database in future queries. Solution: Subordinate Jim Mary Beth Mike Jason Carol Mark Alan

Bob Bob Bob Mary Mary Mary Mary Jim 7.

Second Normal Form (2NF)

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. 8. Third Normal Form (3NF)

Eliminate fields that do not depend on the key.

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 : MemberId 1 2 Name John Smith Dave Jones Company ABC MCI CompanyLoc Alabama Florida

The Member table satisfies first normal form - it contains no repeating groups. It satisfies second normal form - since it doesn't have a multivalued key. But the key is MemberID, and the company name and location describe only a company, not a member. To achieve third normal form, they must be moved into a separate table. Since they describe a company, CompanyCode becomes the key of the new "Company" table. The motivation for this is the same for second normal form: we want to avoid update and delete anomalies. For example, suppose no members from the IBM were currently stored in the database. With the previous design, there would be no record of its existence, even though 20 past members were from IBM! Member Table

SQL FAQs 13 of 28

MemberId 1 2

Name John Smith Dave Jones

CID 1 2

Company Table CId 1 2 9. Name ABC MCI Location Alabama Florida

Boyce-Codd Normal Form (BCNF) A relation is in Boyce/Codd normal form if and only if the only determinants are candidate key. Its a different version of 3NF, indeed, was meant to replace it. [A determinant is any attribute on which some other attribute is (fully) functionally dependent.] 10. 4th Normal Form (4NF) A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies. This applies primarily to key-only associative tables, and appears as a ternary relationship, but has incorrectly merged 2 distinct, independent relationships. Eg: This could be any 2 M:M relationships from a single entity. For instance, a member could know many software tools, and a software tool may be used by many members. Also, a member could have recommended many books, and a book could be recommended by many members.

Software

member

Book

11. The correct solution, to cause the model to be in 4th normal form, is to ensure that all M:M relationships are resolved independently if they are indeed independent.

Software

membersoftware

member

memberBook

book

12. 5th Normal Form (5NF)(PJNF) A table is in 5NF, also called "Projection-Join Normal Form", if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table. 13. 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. 1) Name of the task that is used to execute batch file in SSIS package? Execute Process Task is used to execute batch files. 2) Which Task in SSIS is used to perform operation on a file or directory? File System task is used to perform operation like move, delete, and create file or directories. 3) Can we use Configuration file in SSIS Packages? Yes, we can use configuration file in SSIS package with extension dtsConfig (XML 4) Can we have option to use configuration file in dts package? No, we don't have any option of configuration file in dts package. 5) How we can deploy SSIS? Steps to deploy SSIS are: (1) Right click on the name of the project in the solution explorer. (2) Open Properties --> Select Deployment Utility (3) Set CreateDeploymentUtility to True (4) Build Project (5) Check the Deployment folder in bin (6) Double click on <Project Name>.SSISDeploymentManifest file. 6) Which Editor we can use to create the SSIS Packages? BIDS (Business Intelligence e Development Studio) 7) Name of the containers in SSIS? (1) Task Host Containers (2) Sequence Containers (3) For Each Loop Containers (4) For Loop Containers 8) Can we write Scripting Language like VB Script and JavaScript in SSIS Package? Yes, we can Write VB Script and JavaScript in SSIS Packages using ActiveX Task Control. 9) What is SSIS SSIS is known as SQL Server Integration service. SSIS Package are replacement of DTS Package in SQL Server 2005 or higher version. File).

SQL FAQs 14 of 28

10) Can we use Oracle Database as source or destination Database in SSIS? Yes, we can Use Oracle Database and can create OLE-DB Connection to connect. 11) Can we create DTS Package in DTS package in SQL Server 2005 or higher version? 12) What is the difference between .rdl and .rdlc report. .rdl report is created using SQL Server Reporting service, But the .rdlc report is created with the help visual studio's inbuilt reporting services. in rdlc 'c' stands for client side. 13) In Analysis service what is the technology used define the expressions? Multidimensional Expressions also abbreviated as MDX 14) What is the full form of KPI? Key Performance Indicators 15) What is a cube? A cube is a collection of measures and dimensions for analyzing the data in detail. Here measure is the fact and it has the aggregate data and dimension is a group of attributes. 16) How do you map a column in SqlBulkCopy? By the object of SqlBulkCopyColumnMapping class. Following is a sample SqlBulkCopyColumnMapping mapColumn1 = new SqlBulkCopyColumnMapping("EmpID", "ID"); 17) What is a fixed-length & variable-length character? Tell me their differences?? In Sql Server there are two types of character data types. They are 1.fixed-length (i.e. char) 2.variable-length (i.e. varchar) the main differences are maximum length and in whether trailing spaces are retained 18) What is the default language of SSIS Script Task? VB.NET 19) Which one is faster? BCP or DTS? BCP is faster than DTS. 20) What is DTS? Data Transformation Services (DTS) in SQL Server 2000 provides a set of graphical tools and programmable objects to export and import data. 21) What is BCP? The Bulk Copy Program (BCP) is a command-line utility that ships with SQL Server. It is used to transform data from one database to another. 22) Use of Bulk Copying? Bulk copying is used to transfer large amount of data. 23) What is ETL? Extraction, Transformation, and Loading. The complex process of copying and cleaning data from heterogeneous sources. Important part of development projects for data warehousing and business intelligence (BI) 24) What Is DTS? DTS is a set of tools you can use to import, export, and transform heterogeneous data between one or more data sources, such as Microsoft SQL Server, Microsoft Excel, or Microsoft Access. Connectivity is provided through OLE DB, an open-standard for data access. ODBC (Open Database Connectivity) data sources are supported through the OLE DB Provider for ODBC Difference between delete,drop and truncate Delete Delete remove the Data only, the Table structure remains intact. This is a DML Statement Rollback possible No Commit is performed neither before nor after. (Because it is a DML Statement). They take locks on rows, They generate redo (lots of it) They require segments in the UNDO tablespace. A delete does not relinquish segment space thus a table in which all records have been deleted retains all of its original blocks. A truncate does not move the High Water Mark of the table back to zero, it retains it's original position. Delete deletes the specific rows filtered by where statement. and log is maintained for it. It can activate the triggers. Truncate Truncate remove the Data only, the Table structure remains intact. This is a DDL Statement Rollback not possible (Except in SQL 2005) It issues a COMMIT before it acts and another COMMIT afterward so no rollback of the transaction is possible. (Because it is a DDL Statement) No row-level locks are taken. No redo or rollback is generated. They do not require segments in the UNDO tablespace. All extents bar the initial are de-allocated from the table A truncate moves the High Water Mark of the table back to zero Truncate deletes the page associated with the table so all indexes are reset It does not activate the triggers. Drop

SQL FAQs 15 of 28

Drop permanently removes both the Data as well as the Table Structure. This is a DDL Statement Rollback not possible It issues a COMMIT before it acts and another COMMIT afterward so no rollback of the transaction is possible. (Because it is a DDL Statement) No row-level locks are taken. No redo or rollback is generated. They do not require segments in the UNDO tablespace. All extents bar the initial are de-allocated from the table A truncate moves the High Water Mark of the table back to zero Truncate deletes the page associated with the table so all indexes are reset It does not activate the triggers. FurtherMore.... The Main Difference Between DELETE & TRUNCATE Are :[1] DELETE - is a DML Command & TRUNCATE - is a DDL Command [2] After DELETE - can rollback the Records & After TRUNATE - cannot rollback the records [3] In DELETE Command you can give the conditions in WHERE Clause & In TRUNCATE you cannot give conditions [4] After using DELETE Command The memory will be occupied till the user does not give ROLLBACK or COMMIT & After using TRUNCATE Command The memory realeased immediately when ever u r using delete statement the trigger is fired.in truncated trigger is not fired. we can mention where clause in delete.in truncate we can't mention. From only4gurus.org ******************************************************************* Difference between Table and View Table : Relational Database is composed of tables that contain related data. View : 1. Views are created from one or more than one table by joins, with selected columns. 2. Views acts as a layer between user and table. 3. Views are created to hide some columns from the user for security reasons, and to hide information exist in the column. 4. Views reduces the effort for writing queries to access specific columns every time. 5. Reports can be created on views. 6. View doesn't contain any data. ****************************************************************** Primary Key and Foreign key A primary key is an attribute (or combination of attributes) that uniquely identifies each row in a relation. A primary key is designated by underlining the attribute name. The primary key of an entity set allows us to distinguish among the various entities of the set. A foreign key is an attribute in a relation of database that serves as the primary key of another relation in the same database. ******************************************************************* Can we update the View ?.. There are two types of views namely Simple and complex views. U can perform DML operation on simple views which is based on single table and that view doesn't contain any single row function and any group by clause and it has to satiesfy integrity constraint also. U can't perform DML operation on complex views becuase they are based on multiple table. U can achive this task by using Triggers(Instade of...). ------------------------------------------Eg: suppose you can create the view create view v1 as select ename,sal from emp suppose you want to update the view according to salary update v1 set ename='shailendra' where sal=800; ************************************************************** Livelock and Deadock 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. 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. 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 others 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 users process. A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely. Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.

***************************************************************** SQL 2005 Paging Method USE AdventureWorks GO DECLARE @StartRow INT DECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140 SELECT FROM ( SELECT FirstName, LastName, EmailAddress PC.FirstName, PC.LastName, PC.EmailAddress,

SQL FAQs 16 of 28

ROW_NUMBER() OVER(Order BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumber FROM Person.Contact PC) PersonContact WHERE RowNumber > @StartRow AND RowNumber < @EndRow ORDER BY FirstName, LastName, EmailAddress GO SQL 2000 Paging Method USE AdventureWorks GO DECLARE @StartRow INT DECLARE @EndRow INT SET @StartRow = 120 SET @EndRow = 140 CREATE TABLE #tables (RowNumber INT IDENTITY(1,1), FirstName VARCHAR(100), LastName VARCHAR(100), EmailAddress VARCHAR(100)) INSERT INTO #tables (FirstName, LastName, EmailAddress) SELECT PC.FirstName, PC.LastName, PC.EmailAddress FROM Person.Contact PC ORDER BY FirstName, LastName, EmailAddress SELECT FirstName, LastName, EmailAddress FROM #tables WHERE RowNumber > @StartRow AND RowNumber < @EndRow DROP TABLE #tables GO ********************************************************************************** Top 10 new features in SQL Server 2005 (http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1137301,00.html) In the business world, everything is about being "better, faster and cheaper" than the competition -- and SQL Server 2005 offers many new features to save energy, time and money. From programming to administrative capabilities, this version of SQL Server tops all others and it enhances many existing SQL Server 2000 features. Here I'll outline the 10 most significant new features in order of importance: 1. T-SQL (Transaction SQL) enhancements T-SQL is the native set-based RDBMS programming language offering high-performance data access. It now incorporates many new features including error handling via the TRY and CATCH paradigm, Common Table Expressions (CTEs), which return a record set in a statement, and the ability to shift columns to rows and vice versa with the PIVOT and UNPIVOT commands. 2. CLR (Common Language Runtime) The next major enhancement in SQL Server 2005 is the integration of a .NET compliant language such as C#, ASP.NET or VB.NET to build objects (stored procedures, triggers, functions, etc.). This enables you to execute .NET code in the DBMS to take advantage of the .NET functionality. It is expected to replace extended stored procedures in the SQL Server 2000 environment as well as expand the traditional relational engine capabilities. 3. Service Broker The Service Broker handles messaging between a sender and receiver in a loosely coupled manner. A message is sent, processed and responded to, completing the transaction. This greatly expands the capabilities of data-driven applications to meet workflow or custom business needs. 4. Data encryption SQL Server 2000 had no documented or publicly supported functions to encrypt data in a table natively. Organizations had to rely on thirdparty products to address this need. SQL Server 2005 has native capabilities to support encryption of data stored in user-defined databases. 5. SMTP mail Sending mail directly from SQL Server 2000 is possible, but challenging. With SQL Server 2005, Microsoft incorporates SMTP mail to improve the native mail capabilities. Say "see-ya" to Outlook on SQL Server! 6. HTTP endpoints You can easily create HTTP endpoints via a simple T-SQL statement exposing an object that can be accessed over the Internet. This allows a simple object to be called across the Internet for the needed data. 7. Multiple Active Result Sets (MARS) MARS allow a persistent database connection from a single client to have more than one active request per connection. This should be a major performance improvement, allowing developers to give users new capabilities when working with SQL Server. For example, it allows multiple searches, or a search and data entry. The bottom line is that one client connection can have multiple active processes simultaneously. 8. Dedicated administrator connection If all else fails, stop the SQL Server service or push the power button. That mentality is finished with the dedicated administrator connection. This functionality will allow a DBA to make a single diagnostic connection to SQL Server even if the server is having an issue. 9. SQL Server Integration Services (SSIS) SSIS has replaced DTS (Data Transformation Services) as the primary ETL (Extraction, Transformation and Loading) tool and ships with SQL

SQL FAQs 17 of 28

Server free of charge. This tool, completely rewritten since SQL Server 2000, now has a great deal of flexibility to address complex data movement. 10. Database mirroring It's not expected to be released with SQL Server 2005 at the RTM in November, but I think this feature has great potential. Database mirroring is an extension of the native high-availability capabilities. So, stay tuned for more details. For now, here's ************************************************************ Union Vs Union All Union command does 2 things 1) It works like distinct clause ie it removes duplicate rows also it shows the rows which are unique in a particular table. eg if Table A has rows with values 1,2,3 and Table B has rows with values 4,2,3 the Union table A and table B would give result 1,2,3,4 ********************************************************** Which is more faster - IN or EXISTS? Ans. EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value. ****** One legitimate reason you might want to consider using a temp table is to avoid having to use a cursor. SQL Server cursors have huge overhead and slow SQL Server's performance. One alternative of using a cursor is to use a temp table instead. In almost all cases, using a temp table over a cursor will produce less overhead and better performance. Of course, if you do not have to use a temp table, and find another way to get away from using a cursor, so much the better. ****** **************************************************************

Delete Duplicate Records Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateValueColumn1, DuplicateValueColumn2 and DuplicateValueColumn3. DELETE FROM MyTable WHERE ID NOT IN (SELECT MAX(ID) FROM MyTable GROUP BY DuplicatevalueColumn1, DuplicateValueColumn2, DuplicateValueColumn2 ************************************************************* Transaction Isolation Level (http://www.mssqlcity.com/Articles/General/TIL.htm) read uncommitted When it's used, SQL Server not issue shared locks while reading data. So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. It ensures only that a physically corrupt data will not be read. read committed This is the default isolation level in SQL Server. When it's used, SQL Server will use shared locks while reading data. It ensures that a physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it does not ensure that the data will not be changed before the end of the transaction. repeatable read When it's used, the dirty reads and nonrepeatable reads cannot occur. It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data. This is the definition of nonrepeatable read from SQL Server Books Online: nonrepeatable read When a transaction reads the same row more than one time, and between the two (or more) reads, a separate transaction modifies that row. Because the row was modified between reads within the same transaction, each read produces different values, which introduces inconsistency. serializable Most restrictive isolation level. When it's used, then phantom values cannot occur. It prevents other users from updating or inserting rows into the data set until the transaction is complete. This is the definition of phantom from SQL Server Books Online: phantom Phantom behavior occurs when a transaction attempts to select a row that does not exist and a second transaction inserts the row before the first transaction finishes. If the row is inserted, the row appears as a phantom to the first transaction, inconsistently appearing and disappearing. You can set the appropriate isolation level for an entire SQL Server session by using the SET TRANSACTION ISOLATION LEVEL statement. This is the syntax from SQL Server Books Online: SET TRANSACTION ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED

SQL FAQs 18 of 28

| REPEATABLE READ | SERIALIZABLE } You can use DBCC USEROPTIONS command to determine the Transaction Isolation Level currently set. This command returns the set options that are active for the current connection. This is the example: SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED GO DBCC USEROPTIONS GO This is the result: Set Option Value ------------------------------ -----------------------------------textsize 64512 language us_english dateformat mdy datefirst 7 isolation level read uncommitted ********************************************* What is normalization? (http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1120129,00.html#) Normalization is the process of designing a data model to efficiently store data in a database. The end result is that redundant data is eliminated, and only data related to the attribute is stored within the table. For example, let's say we store City, State and ZipCode data for Customers in the same table as Other Customer data. With this approach, we keep repeating the City, State and ZipCode data for all Customers in the same area. Instead of storing the same data again and again, we could normalize the data and create a related table called City. The "City" table could then store City, State and ZipCode along with IDs that relate back to the Customer table, and we can eliminate those three columns from the Customer table and add the new ID column. Normalization rules have been broken down into several forms. People often refer to the third normal form (3NF) when talking about database design. This is what most database designers try to achieve: In the conceptual stages, data is segmented and normalized as much as possible, but for practical purposes those segments are changed during the evolution of the data model. Various normal forms may be introduced for different parts of the data model to handle the unique situations you may face. Whether you have heard about normalization or not, your database most likely follows some of the rules, unless all of your data is stored in one giant table. We will take a look at the first three normal forms and the rules for determining the different forms here. Rules for First Normal Form (1NF) Eliminate repeating groups. This table contains repeating groups of data in the Software column. Computer Software 1 2 3 Word Access, Word, Excel Word, Excel

To follow the First Normal Form, we store one type of software for each record. Computer Software 1 2 2 3 3 3 Word Access Word Excel Word Excel

Rules for second Normal Form (2NF) Eliminate redundant data plus 1NF. This table contains the name of the software which is redundant data. Computer Software 1 2 2 3 3 3 Word Access Word Excel Word Excel

To eliminate the redundant storage of data, we create two tables. The first table stores a reference SoftwareID to our new table that has a unique list of software titles. Computer SoftwareID 1 2 2 3 3 3 1 2 1 3 1 3

SoftwareID Software

SQL FAQs 19 of 28

1 2 3

Word Access Excel

Rules for Third Normal Form (3NF) Eliminate columns not dependent on key plus 1NF and 2NF. In this table, we have data that contains both data about the computer and the user. Computer User Name User Hire Date Purchased 1 2 Joe Mike 4/1/2000 9/5/2003 5/1/2003 6/15/2004

To eliminate columns not dependent on the key, we would create the following tables. Now the data stored in the computer table is only related to the computer, and the data stored in the user table is only related to the user. Computer Purchased 1 2 5/1/2003 6/15/2004

User User Name User Hire Date 1 2 Joe Mike 5/1/2003 6/15/2004

Computer User 1 2 1 1

What does normalization have to do with SQL Server? To be honest, the answer here is nothing. SQL Server, like any other RDBMS, couldn't care less whether your data model follows any of the normal forms. You could create one table and store all of your data in one table or you can create a lot of little, unrelated tables to store your data. SQL Server will support whatever you decide to do. The only limiting factor you might face is the maximum number of columns SQL Server supports for a table. SQL Server does not force or enforce any rules that require you to create a database in any of the normal forms. You are able to mix and match any of the rules you need, but it is a good idea to try to normalize your database as much as possible when you are designing it. People tend to spend a lot of time up front creating a normalized data model, but as soon as new columns or tables need to be added, they forget about the initial effort that was devoted to creating a nice clean model. To assist in the design of your data model, you can use the DaVinci tools that are part of SQL Server Enterprise Manager. Advantages of normalization 1. Smaller database: By eliminating duplicate data, you will be able to reduce the overall size of the database. 2. Better performance: a. Narrow tables: Having more fine-tuned tables allows your tables to have less columns and allows you to fit more records per data page. b. Fewer indexes per table mean faster maintenance tasks such as index rebuilds. c. Only join tables that you need. Disadvantages of normalization 1. More tables to join: By spreading out your data into more tables, you increase the need to join tables. 2. Tables contain codes instead of real data: Repeated data is stored as codes rather than meaningful data. Therefore, there is always a need to go to the lookup table for the value. 3. Data model is difficult to query against: The data model is optimized for applications, not for ad hoc querying. 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 doublylinked 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. **************************************************************** CURSOR SET NOCOUNT ON DECLARE @vendor_id int, @vendor_name nvarchar(50), @message varchar(80), @product nvarchar(50) PRINT '-------- Vendor Products Report --------' DECLARE vendor_cursor CURSOR FOR SELECT VendorID, Name FROM Purchasing.Vendor WHERE PreferredVendorStatus = 1 ORDER BY VendorID OPEN vendor_cursor FETCH NEXT FROM vendor_cursor

SQL FAQs 20 of 28

INTO @vendor_id, @vendor_name WHILE @@FETCH_STATUS = 0 BEGIN PRINT ' ' SELECT @message = '----- Products From Vendor: ' + @vendor_name PRINT @message -- Declare an inner cursor based -- on vendor_id from the outer cursor. DECLARE product_cursor CURSOR FOR SELECT v.Name FROM Purchasing.ProductVendor pv, Production.Product v WHERE pv.ProductID = v.ProductID AND pv.VendorID = @vendor_id -- Variable value from the outer cursor OPEN product_cursor FETCH NEXT FROM product_cursor INTO @product IF @@FETCH_STATUS <> 0 PRINT ' BEGIN SELECT @message = ' PRINT @message FETCH NEXT FROM product_cursor INTO @product END CLOSE product_cursor DEALLOCATE product_cursor -- Get the next vendor. FETCH NEXT FROM vendor_cursor INTO @vendor_id, @vendor_name END CLOSE vendor_cursor DEALLOCATE vendor_cursor ******************************************************** 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 SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee ORDER BY salary DESC) a ORDER BY salary Employee empid empname salary mgrid Phone Empid phnumber ' + @product <<None>>' WHILE @@FETCH_STATUS = 0

SELECT empname FROM employee WHERE (empid IN (SELECT empid FROM phone GROUP BY empid HAVING COUNT(empid) > 1)) ********************* select Player,Captain from tblDuplicate SELECT t.Player AS EmployeeNumber, tCount AS NumberOfDuplicates FROM (SELECT Player, COUNT(*) AS tCount FROM tblDuplicate WHERE Player IS NOT NULL GROUP BY Player) t WHERE tCount > 1 ORDER BY t.Player 1) Why OLAP? OLAP is useful because it provides fast and interactive access to aggregated data and the ability to drill down to detail.

SQL FAQs 21 of 28

2) Where .NET CLR and SQL SERVER run? All .net relates application and Sql Server runs in same process or we can say that on same address because there is no issue of speed because if these two process are run in different process then there may be a speed issue created one process goes fast and other slow may create the problem. 3) What is the control flow? In SSIS a workflow is called a control-flow. A control-flow links together our modular data- flows as a series of operations in order to achieve a desired result. A control flow consists of one or more tasks and containers that execute when the package runs. To control order or define the conditions for running the next task or container in the package control flow, you use precedence constraints to connect the tasks and containers in a package. A subset of tasks and containers can also be grouped and run repeatedly as a unit within the package control flow. SQL Server 2005 Integration Services (SSIS) provides three different types of control flow elements: Containers that provide structures in packages, Tasks that provide functionality, Precedence constraints that connect the executables, containers, and tasks into an ordered control flow. 4) What is a data flow? A data flow consists of the sources and destinations that extract and load data, the transformations that modify and extend data, and the paths that link sources, transformations, and destinations. Before you can add a data flow to a package, the package control flow must include a Data Flow task. The Data Flow task is the executable within the SSIS package that creates, orders, and runs the data flow. A separate instance of the data flow engine is opened for each Data Flow task in a package. SQL Server 2005 Integration Services (SSIS) provides three different types of data flow components: Sources, extract data from data stores such as tables and views in relational databases, files, and Analysis Services databases. Transformations, Sources Transformations modify, summarize, and clean data. Destinations, load data into data stores or create in-memory datasets. 5) How do you do error handling in SSIS? When a data flow component applies a transformation to column data, extracts data from sources, or loads data into destinations, errors can occur. Errors frequently occur because of unexpected data values. For example: a data conversion fails because a column contains a string instead of a number, an insertion into a database column fails because the data is a date and the column has a numeric data type, or an expression fails to evaluate because a column value is zero, resulting in a mathematical operation that is not valid. Errors typically fall into one the following categories: -Data conversion errors, which occur if a conversion results in loss of significant digits, the loss of insignificant digits, and the truncation of strings. Data conversion errors also occur if the requested conversion is not supported. -Expression evaluation errors, which occur if expressions that are evaluated at run time perform invalid operations or become syntactically incorrect because of missing or incorrect data values. -Lookup errors, which occur if a lookup operation fails to locate a match in the lookup table. Many data flow components support error outputs, which let you control how the component handles row-level errors in both incoming and outgoing data. You specify how the component behaves when truncation or an error occurs by setting options on individual columns in the input or output. For example, you can specify that the component should fail if customer name data is truncated, but ignore errors on another column that contains less important data. 6) How do you do logging in SSIS? a) b) c) d) e) f) g) SSIS includes logging features that write log entries when run-time events occur and can also write custom messages. Integration Services supports a diverse set of log providers, and gives you the ability to create custom log providers. The Integration Services log providers can write log entries to text files, SQL Server Profiler, SQL Server, Windows Event Log, or XML files. Logs are associated with packages and are configured at the package level. Each task or container in a package can log information to any package log. The tasks and containers in a package can be enabled for logging even if the package itself is not. To customize the logging of an event or custom message, Integration Services provides a schema of commonly logged information to include in log entries. The Integration Services log schema defines the information that you can log. You can select elements from the log schema for each log entry. that contains the package you want.

To enable logging in a package 1. In Business Intelligence Development Studio, open the Integration Services project 2. On the SSIS menu, click Logging. 3. Select a log provider in the Provider type list, and then click Add. 7) What are variables and what is variable scope? Variables: a) b) c)

Variables store values that a SSIS package and its containers, tasks, and event handlers can use at run time. The scripts in the Script task and the Script component can also use variables. The precedence constraints that sequence tasks and containers into a workflow can use variables when their constraint definitions include expressions.

SQL FAQs 22 of 28

Integration Services supports two types of variables 1. 2. User-defined variables System variables.

User-defined variables are defined by package developers, and system variables are defined by Integration Services. You can create as many user-defined variables as a package requires, but you cannot create additional system variables. Scope: A variable is created within the scope of a package or within the scope of a container, task, or event handler in the package. Because the package container is at the top of the container hierarchy, variables with package scope function like global variables and can be used by all containers in the package. Similarly, variables defined within the scope of a container such as a For Loop container can be used by all tasks or containers within the For Loop container. 8) Using a checkpoint file in SSIS is just like issuing the CHECKPOINT command against the relational engine. It commits all of the data to the database. False. SSIS provides a Checkpoint capability which allows a package to restart at the point of failure. 9) SSIS has a default means to log all records updated, deleted or inserted on a per table basis. False, but a custom solution can be built to meet these needs.

10) What is a breakpoint in SSIS? How is it setup? How do you disable it? A breakpoint is a stopping point in the code. The breakpoint can give the Developer\DBA an opportunity to review the status of the data, variables and the overall status of the SSIS package. 10 unique conditions exist for each breakpoint. Breakpoints are setup in BIDS. In BIDS, navigate to the control flow interface. Right click on the object where you want to set the breakpoint and select the 'Edit Breakpoints...' option. 11) How do you eliminate quotes from being uploaded from a flat file to SQL Server? In the SSIS package on the Flat File Connection Manager Editor, enter quotes into the Text qualifier field then preview the data to ensure the quotes are not included. Additional information: How to strip out double quotes from an import file in SQL Server Integration Services 12) Can you explain how to setup a checkpoint file in SSIS? The following items need to be configured on the properties tab for SSIS package: Checkpoint Filename - Specify the full path to the Checkpoint file that the package uses to save the value of package variables and log completed tasks. Rather than using a hard-coded path as shown above, it's a good idea to use an expression that concatenates a path defined in a package variable and the package name. Checkpoint Usage - Determines if/how checkpoints are used. Choose from these options: Never (default), If Exists, or Always. Never indicates that you are not using Checkpoints. If Exists is the typical setting and implements the restart at the point of failure behavior. If a Checkpoint file is found it is used to restore package variable values and restart at the point of failure. If a Checkpoint file is not found the package starts execution with the first task. The Always choice raises an error if the Checkpoint file does not exist. Save Checkpoints - Choose from these options: True or False (default). You must select True to implement the Checkpoint behavior. 13) How do you upgrade an SSIS Package? Depending on the complexity of the package, one or two techniques are typically used: 1) 2) Recode the package based on the functionality in SQL Server DTS Use the Migrate DTS 2000 Package wizard in BIDS then recodes any portion of the package that is not accurate.

14) Explain the architecture of SQL Reporting service? a) b) c) d) e) Reporting Services runs as a middle-tier server, as part of your existing server architecture. SQL Server 2000 should be installed for the database server, and Internet Information Services 6.0 as a Web server. The report server engine takes in report definitions, locates the corresponding data, and produces the reports. Interaction with the engine can be done through the Web-based Report Manager, which also lets you manage refresh schedules and notifications. End users view the report in a Web browser, and can export it to PDF, XML, or Excel

15) What is Reporting Services? SQL Servers Reporting services offer a variety of interactive and printed reports managed by a web interface. Reporting services is a server based environment. 16) How does the report manager work in SSRS? a) b) c) d) Report manager is a web application. In SSRS it is accessed by a URL. The interface of this Report manager depends on the permissions of the user. This means to access any functionality or perform any task, the user must be assigned a role.

SQL FAQs 23 of 28

e) f)

A user with a role of full permissions can entire all the features and menus of the report. To configure the report manager, a URL needs to be defined.

17) What are the Reporting Services components? Reporting services components assist in development. These processing components include some tools that are used to create, manage and view reports. A report designer is used to create the reports. A report sever is used to execute and distribute reports. A report manager is used to manage the report server. 18) SQL Server Reporting Services vs. Crystal Reports? a) b) c) d) e) Crystal reports are processed by IIS while SSSR have a report server. Caching in Crystal reports is available through cache server. On the other hand, caching in SSSR is available for Report history snapshots. Crystal reports have standards and user defined field labels. SSSR allows only user defined field labels.

19) What can SQL Server Reporting Services do? With Reporting Services, a) b) c) d) e) You You You You You can can can can can create interactive, tabular, graphical, or free-form reports from relational, multidimensional, or XML-based data sources. publish reports, schedule report processing, or access reports on-demand. create ad hoc reports based on predefined models and interactively explore data within the model. select from a variety of viewing formats, export reports to other applications, and subscribe to published reports. view the reports created over a Web-based connection or as part of Windows application.

20) Describe SQL Server Reporting Services lifecycle. The phases of the Reporting Life Cycle involve: 1) 2) 3) 4) 5) Report authoring Report management Report delivery Report security Report authoring This stage involves creation of reports that are published using the Report Definition language. RDL is an XML based industry standard for defining reports. Report management This involves managing the published reports as a part of the web service. The reports are cached for consistency and performance. They can be executed whenever demanded or can be scheduled and executed. In short Report Management includes: - Organizing reports and data sources, - Scheduling report execution and delivery, and - Tracking reporting history. Report delivery Reports can be delivered to the consumers either on their demand or based on an event. Then they can view them is a webbased format. Report security It is important to protect reports as well as the report resources. Therefore, Reporting Services implement a flexible, role-based security model . 21) What are the ways to tune Reporting Services? Following are a few ways you can tune up Reporting Services: a) b) c) You can expand your current Server or avail the reporting service database on another server. Depending on report characteristics and application logic, it is sometimes better to have a copy of data separate to improve the performance. You can also use continuous replication for reporting. With this there wouldnt be any interference with the OLTP environment. The locking problems can be solved by using no lock and the query performance can be improved using dirty read when a copy of the data is not available. This can be accomplished only if the database design and application logic permit dirty reads.

SQL FAQs 24 of 28

22) How to schedule SSAS Database backup? SSAS database backups can be taken using SQL Server Management Studio (SSMS). In order to create a backup using the SSAS backup option, a SQL Server Agent Job needs to be created and scheduled. This can be achieved by following the steps below: SQL Agent nodes job folder should be right clicked to select new job option. This job can be given a name and go to steps page. In the steps page, a new step should be created SQL Server Analysis Services Command should be selected as the job type. The server name can be entered. The SSAS database name and the backup name should be changed. From the schedule page the schedule can be created. <Backup xmlns="http://schemas.microsoft.com/analysisservices/2003/engine"> <Object> <DatabaseID>DatabaseName</DatabaseID> </Object> <File> DatabaseName.abf</File> <AllowOverwrite>true</AllowOverwrite> <Password>password</Password> </Backup> 23) How to Generate an Auto Incremental Number in a SSIS Package? Steps to generate an Auto Incremental Number in SSIS package: a) b) c) Drag the Script component to the Data flow and select Script component type as Transformation. Double click the script component. In the input columns tab choose the column you need to pass through script component. In Inputs and Outputs tab, add a column with an integer data type. d) Go to Script tab and click Design script and type the following in it:imports System Imports System. Data Imports System. Math Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper Imports Microsoft.SqlServer.Dts.Runtime.Wrapper Public Class Script Main Inherits User Component Dim Counter As Integer = 0 'Set initial value here Public Overrides Sub Input0_ProcessInputRow (By Val Row As Input0Buffer) Row. Column = Counter Counter = Counter + 1 ' Set the incremental value here End Sub End Class - In a T-SQL, this can be done by the ROW_NUMBER () function. - In SQL Server Reporting Services Row Number (Nothing) can be used. 24) How to send a SSRS report from SSIS? SSIS has the ability to send SSRS report in different formats like Excel, PDF etc. This is achieved by creating a report subscription using the Report manager. In the report subscription, the format of the SSRS report can be mentioned along with the email address of the recipient. Sp_start_job is used to execute the report subscription. The steps one needs to follow to do this are: a) b) c) d) Creation of an SSRS report subscription from Report Manager. Entering the report format and the email address of the recipient in the subscription. Creation of a schedule for the SSRS report so that the SQL Server Agent Job gets created. Execution of SSRS report subscription from the SSIS by using sp_start_job and providing a relevant job name.

25) Lookups are a key component in SQL Server Integration Services (SSIS). Explain its purpose? I. a. b. c. d. e. f. SSIS 2008 has the ability of cache lookup data in to a local file. Lookup data thus needs to be retrieved once, and then cached and reused. Lookups are a way to provide a range of values for a particular columns value. It is very useful while transforming data and cleaning it as well. Lookup enables transforming of data from one table to another and merging tables as well through a range of values. This can clear and clean a lot of misspelled data.

Example: A table might have flrida stored as city instead of florida. If the transformation is made through a lookup consisting of Florida, then flrida will be converted to Florida, providing a clean transformation. II Lookup transformation combines data from two sources. The fields of these sources are matched. The lookups performed by the transformation are case sensitive. The lookups are used to access additional information in a related table that is based on values in common columns. III Lookups are used for the following purposes: 1. Lookup transformation

SQL FAQs 25 of 28

2. 3. 4. 5. 6. 7. 8.

Looking up data in data warehouse Looking for the key thats different in the DW Inferred members Inferred members in the error output in the lookup Slowly changing dimensions Type two slowly changing dimension Optimizations - Cache mode: full cache, partial cache, no cache

26) How to unzip a File in SSIS? Use the Execute Process Task in the Control Flow task. In BIDS, drag and drop an Execute Process task to the control flow and configure. In Execute process, provide the path of the executable (Executable), provide arguments to extract the zip files (Arguments), and provide working directory for processing (Working Directory) configurations. In the Execute Process, you need to perform three configurations: 1. Executable: This is the path of the application you are going to use. 2. Arguments: Arguments to extract the zipped files. 1. e: stands for Extract files to current directory. 2. Then the full path name of the zipped file. 3. o+: overwrite existing files. 3. Working Directory: Current directory for the process.

27) What are the advantages of using Stored Procedures? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) Stored procedures provide performance benefits through local storage, precompiling the code, and caching. Stored procedures offer security features that include encryption and privilege limits that restrict users from modifying structure of stored procedure. Stored procedures manage, control and validate data. Large queries can be avoided. Reduces network traffic since they need not be recompiled. Even though the stored procedure itself may be a complex piece of code, we need not write it over and over again. Hence stored procedures increases reusability of code Permissions can be granted for stored procedures. Hence, increases security.

They are easier to maintain and troubleshoot as they are modular. Stored procedures enable better tuning for performance. Using stored procedures is much easier from a GUI end than building/using complex queries. They can be part of a separate layer which allows separating the concerns. Hence Database layer can be handled by separate developers proficient in database queries. 12) Help in reducing network usage. 13) Provides more scalability to an application. 14) Reusable and hence reduce code. SQL Server Integration Services (SSIS) Interview questions 1. What is for-loop container? Give an example of where it can be used. 2. What is foreach-loop container? Give an example of where it can be used. 3. What is sequence container? Give an example of where it can be used. 4. What is the difference between Analysis Services processing task & Analysis services execute DDL task? 5. What is the difference between for-loop container & foreach-loop container? 6. What are the different parameters or configurations that send mail task requires? 7. Mention few mapping operations that the Character Map transformation supports. 8. Explain the functionality of: Import Column Transformation and Export Column Transformation 9. Explain the functionality of: Percentage Sampling transformation 10. Explain the functionality of: SCD transformation 11. Explain the functionality of: Union All transformation 12. What does Lookup transformation used for? 13. What are checkpoints? For which objects we define checkpoint? How to configure checkpoint for a package? 14. What is the use of package configurations available in SSIS? 15. What are the different ways in which configuration details can be stored? 16. How to deploy a package from development server to production server? 17. How to create Integration Services Package Deployment Utility? 18. How to deploy packages to file system? 19. How to deploy packages to SQL server? Where in database packages will be stored? 20. How to set security for a package? Explain the same as per different deployment options. 21. Explain the architecture of SSIS 22. Explain the how SSIS engine workflow DWBI: 1. 2. 3. 4. 5.

Differentiate Data warehouse with BI. Difference between OLTP and OLAP What is Data Mart? What is Fact? What is a dimension?

SQL FAQs 26 of 28

6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.

Explain about lifecycle of DWH. What is Surrogate Key? Why we need that we have Primary Key? Difference between Star Schema and Snowflake schema? What is integrated schema? What is Data Cleansing? What if fact less fact table? Can we call that as a dimension table? What is drill down and drill up? Which schema you have used in your projects? What is Junk dimension? What is confirmed dimension? What is Degenerated dimension? What is Role Playing dimension? Types of Facts? DWH database is normalized or denormalized? Ans: Denormalized. Explain ETL processing? What is the advantage if we use snow flake schema? What is the size of fact table in your previous project? Difference between DWH and Database? Explain about different types of fact tables. Explain about MOLAP, ROLAP and HOLAP.

T-SQL: 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52.

Explain about SQL Query Performance tuning. Difference between stored procedure and function. What is Cursor? Difference between query and Stored Procedure? What is a view? Explain about triggers? How to find out second highest salary using T-SQL? Explain about Joins. Difference between Left and Outer Join? What is Common Table Expression(CTE)? What is indexed view? What is covering index? What are SQL Hints? What is linked server? How you can pull the data using this? Difference between Primary Key and Non Primary Key? What are indexes? How that can be used to improve performance? How many clustered and Non Clustered indexes you can create? Difference between DELETE and TRUNCATE? What is Cross Join? What is Composite Key? What is the MAX size of a row? What are Correlated queries? How will you delete duplicate records using T-SQL? What is stored procedure? Diff betn Stored procedure and function? Types of Stored procedures? Top 2nd(specified) Salary with a sql query? Hint: Rank function or rownumber function

SSIS: 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71.

What is a package? How to remove duplicates using SSIS and T-SQL? What are the transformations you have worked? Explain about SCD, give some examples. Difference between Merge and Merge Join? Difference between Union and Union All in T-SQL? Explain about Lookup. Difference between For and For Each loop, give examples? Explain about Execute Package Task and Execute SQL task. Have you used Bulk Insert task? What are Checkpoints? How a package can be restarted? What is the Size of lookup that you have used in your projects? What is the exception handling mechanism you have used in your projects? Do you know about Web Service task? Explain about error handling mechanism in SSIS. Have you used Script Component or script task in SSIS? What are the major challenges you have faced in SSIS or ETL? If a package gets fail at the middle of the data transformation, what will you do? How will you deploy the SSIS package?

SQL FAQs 27 of 28

72. 73. 74. 75.

Have you used DTExec Utility? How will you tune package performance? What is Fuzzy Lookup? While using Conditional Split transformation, if you specify following three conditions 1. >100, 2. >100 and <200 and 3. <200 and <500. Suppose if any record have the value of 50 in which scenario the record will go 76. What is package configuration? What type of configuration you have used in your project? 77. In an excel file you have the following three columns 1. Name, 2. City, 3. Age All Cities name should go into City dimension table. How do you accomplish this using SSIS? 78. Explain about Logging and different types of logging mechanisms 79. Through SSIS, to how many sources you can connect? 80. Difference between Control flow and Data Flow? 81. Explain about Variables and Expressions in SSIS. 82. How can you schedule SSIS package? 83. How will you retrieve the data that exists on other server? 84. On what databases you have worked? 85. How will you load the data into the cube? 86. Have you used script task? If so for what scenario you have used? 87. In what format SSIS package will store the metadata? 88. Explain about the architecture of SSIS. 89. How can you perform Incremental load operation using SSIS? 90. What are your responsibilities in the project? 91. How indexes improve the Package performance? 92. What is Surrogate Key? How will you create that using SSIS? 93. What is Ignore failure, Redirect row option does in SSIS? 94. What are containers? How many types of containers are there? 95. Delay validation 96. Optimized mode (64 & 32 bit) 97. Transaction 98. Synchronization tasks 99. Web Services task 100. Prerequisites for pivot task 101. Counters in ssis 102. Log file to save in a sql server whether package got error. 103. How many tasks can execute parallel in either control flow or data flow 104. Check point settings and usage 105. Diff betn oledb and sql server destination 106. Diff betn files system task and ftp task. 107. How to retrieve the all files or files in a folder from another server. 108. Performance tuning of a package 109. Error handling in a package 110.

SSRS: 111. Explain the flow from a report request to report delivery. 112. Where does connection string of a report exists? Can we read it? 113. What is a Sub Report? 114. Navigating from one report to another report with parameter values? 115. Can we pass the parameter value to sub report? NO 116. Difference between Matrix and Table Control? 117. Creating a drilldown report Explain the Steps. 118. How to change the format of Currency field. 119. How to enable sort functionality for the columns in the report? 120. What services in windows need to run for SSRS to run properly? 121. Mention some of the inbuilt security roles in SSRS 122. Why do we use Reporting services configuration manager tool? What are the tasks we achieve in this? 123. How can you pass the parameters to Dataset? 124. Can we use stored procedure in Dataset instead of writing query? 125. How to deploy SSRS report? 126. How to integrate SSRS report in dot net? 127. How will you pull the data from Cubes? 128. What is query parameter and report parameter? 129. What are reporting service components in SSRS? 130. What is RDL in SSRS? 131. Passing the parameter value to another parameter 132. can grow shrink 133. can we use the in operator in a filter

SQL FAQs 28 of 28

You might also like