SQL Server can be used to view table structures, lists of columns and tables. It is based on the relational model and supports null values. Triggers allow procedures to fire on data modifications and can contain nested triggers. Views allow accessing data without a physical schema. Stored procedures optimize performance through filters, selective column selection, and efficient joins. Error handling uses TRY/CATCH blocks to return error details.
SQL Server can be used to view table structures, lists of columns and tables. It is based on the relational model and supports null values. Triggers allow procedures to fire on data modifications and can contain nested triggers. Views allow accessing data without a physical schema. Stored procedures optimize performance through filters, selective column selection, and efficient joins. Error handling uses TRY/CATCH blocks to return error details.
• DESCRIBE is used to see table structure. In SQL server 2005 we can use sp_columns, sp_tables or sp_help. • sp_columns will show list of columns and its details in table. • sp_tables will show list of tables in the database. • Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. • RDMS is based upon relational modal of E.F.Codd Can UNIQUE KEY in SQL Server 2005 have two or more NULL? SQL server 2005 can not have more then one NULL, because in SQL server 2005 every null is having same value. Trigger and Nested Triggers • In any database including SQL Server 2005 a trigger is procedure that initiates on INSERT, DELETE or UPDATE actions. • the DBMS automatically fires the trigger when data modification events (INSERT, DELETE or UPDATE) happened in the associated table. • Triggers are same as stored procedures in term of procedural logic that is stored at the database level. • Stored procedures are executed explicitly and triggers are event-drive. • Triggers can also execute stored procedures. • Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. VIEW • a view can be thought of stored SQL query which result can be accessible as a table. • It can be used for retrieving data, as well as updating or deleting rows. • But database view does not have physical schema. How do you optimize stored procedures in SQL Server 2005? • 1. Use as much as possible WHERE clause filters. Where Clause is the most important part for optimization • 2. Select only those fields which really require. • 3. Joins are expensive in terms of time. Make sure that use all the keys that relate the two tables together and don't join to unused tables, always try to join on indexed fields. The join type is important as well (INNER,OUTER). How is the error handling in stored procedures of SQL Server 2005? • In previous versions of SQL Server you would handle exceptions by checking the @@error global variable immediately after an INSERT, UPDATE or DELETE, and then perform some corrective action if @@error did not equal zero. • SQL Server 2005 provides structured exception handing through TRY CATCH block as other programming language like JAVA, C# etc. • BEGIN TRY RAISERROR ('Yaa, I ma the problem', 16,1) END TRY • BEGIN CATCH SELECT ERROR_NUMBER() as ERROR_NUMBER, ERROR_SEVERITY() as ERROR_SEVERITY, ERROR_STATE() as ERROR_STATE, ERROR_MESSAGE() as ERROR_MESSAGE END CATCH • ERROR_NUMBER() returns the number of the error. • ERROR_SEVERITY() returns the severity. ERROR_STATE() returns the error state number. • ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred. • ERROR_LINE() returns the line number inside the routine that caused the error. • ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names or times. Describe the purposes and advantages 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. Distributed Queries & linked server.
• Distributed queries can access data from different data sources.
• These sources can reside on the same server or a different server. • They can query multiple databases. • linked server • allows remote access. Using this, we can issue distributed queries, update, commands, and transactions across different data sources. • A linked server has an OLE DB provider and data source. Pivot and UnPivot SQL service broker • PIVOT feature is for analytical view that presents the row data to column. It summarizes data in cross tab format. • Unpivot feature is used to unpivot the pivoted data. • SQL service broker provides asynchronous queuing functionality to SQL server. Once message is sent to the SQL server, the client can continue with some other task instead of waiting for any notification from the server. Explain the use of keyword WITH ENCRYPTION. Create a Store Procedure with Encryption. • WITH ENCRYPTION Indicates that SQL Server will convert the original text of the CREATE PROCEDURE statement to an encrypted format. Users that have no access to system tables or database files cannot retrieve the encrypted text. However, the text will be available to privileged users. • Example • CREATE PROCEDURE salary_sum • WITH ENCRYTION • AS • SELECT sum(salary) • FROM employee • WHERE emp_dept LIKE Develop Primary Key-user defined datatypes-bit datatype? • Primary Key = Unique + Not Null • User defined datatypes is created by using base SQL Server data type by providing a descriptive name. They are created when there a column which appears in many tables. In this we can create a user defined data types and uses it across all the tables. • Bit data type is used to store Boolean information like 1 or 0 (true or false). Lock Escalation RAID • It is the process of converting a lot of low level locks into higher level locks. • RAID, Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. We have 0 through 5 RAID levels that offers different levels of performance and fault tolerance. Truncate Vs Delete • Truncate • Truncate command is used to remove all rows of the column. • The removed records are not recorded in the transaction log. • It is the fast way to remove all the records from the table. • The records once removed can’t be rolled back. • It can’t activate trigger. • It resets the identity of the column • Delete • Delete command removes records one at a time and logs into the transaction log. • It can be used with or without where clause. • The records can be rolled back. • It activates trigger. • It doesn’t reset the identity of the column. Query Optimization • Restrict Query Result for performance optimization • Restrict columns in the SQL query • Use stored procedure instead of heavy duty queries • Avoid SQL cursor for optimal performance • Use constraints instead of trigger • Use table variable instead of temporary tables. • Avoid using Having clause • Include SET NOCOUNT ON in the stored procedure. Database Optimization question that can be asked during interview • • 1. What is nested join, hash join and merge join in SQL Query plan? • 2. What is an Execution plan? • 3. What are indexes? What are types of indexes? • 4. Define B-Trees. • 5. How do you see the SQL plan in textual format? • 6. Is it a good database design to create indexes on the table in which lot of inserts occurs? • 7. What are “Table Scan’s” and “Index Scan’s”? • 8. What is “FillFactor” concept in indexes? What is the best value for “FillFactor”? • 9. Define “Index statistics”. • 10. How can we see statistics of an index? • 11. Define Fragmentation. How can we measure Fragmentation? • 12. What are the criteria to be considered while selecting an index? • 13. Define “Index Tuning Wizard”. Optimizer Hint • In most cases, the SQL Server Query Optimizer will correctly evaluate a query and run it as optimally as possible. • But on occasion the Query Optimizer will fail, producing a less than optimal execution plan, and query performance will suffer because of it. • When you identify such a query, you can override the Query Optimizer using what is called an Optimizer Hint. Optimizer hints can be divided into five different categories: • Table Hints: Used to force index selection. • Join Hints: Used to specify the type of JOIN strategy used. • Query Hints: Hints used to affect GROUP BY and UNION functionality. • Lock Hints : Used to help avoid undesirable locking. • View Hints: Used to specify indexes in indexed views. • Other Hints: Misc. hints. What is normalization? & Stored Procedure? • - 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. • 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. • 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. Trigger VIEW • Triggers are basically used to implement business rules. • Triggers are 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. • 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 sometimes allowing specific 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. Index Clustered Non Clustered • 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 Cursors • cursors help us to do an operation on a set of data that we retrieve 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 retrieval one by one and remove rows which have duplicate values. UPDATE_STATISTICS command? TCP/IP port • 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. 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. DBCC • 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. Rename DB HAVING WHERE COLLATION • 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. JOINS PROFILER • 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. Linked Server • 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 OS services • 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 Trouble Shoot and Connection • 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 • 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 configured 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. Auth Mode-Log Shipping Storing Uname& PW • 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. • 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. Misc • 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. • 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). • 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 won’t 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. • What are the different types of joins and what dies each do? • What are the four main query statements? • What is a sub-query? When would you use one? • What is a NOLOCK? • What are three SQL keywords used to change or set someone’s permissions? • What is the difference between HAVING clause and the WHERE clause? • What is referential integrity? What are the advantages of it? • What is database normalization? • Which command using Query Analyzer will give you the version of SQL server and operating system? • Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table? • What is the purpose of using COLLATE in a query? • What is a trigger? • What is one of the first things you would do to increase performance of a query? For example, a boss tells you that “a query that ran yesterday took 30 seconds, but today it takes 6 minutes” • What is an execution plan? When would you use it? How would you view the execution plan? • . What is the STUFF function and how does it differ from the REPLACE function? • What does it mean to have quoted_identifier on? What are the implications of having it off? • What are the different types of replication? How are they used? • What is the difference between a local and a global variable? • What is the difference between a Local temporary table and a Global temporary table? How is each one used? • What are cursors? Name four types of cursors and when each one would be applied? • What is the purpose of UPDATE STATISTICS? • How do you use DBCC statements to monitor various aspects of a SQL server installation? • How do you load large data to the SQL server database? • How do you check the performance of a query and how do you optimize it? • How do SQL server 2000 and XML linked? Can XML be used to access data? • What is SQL server agent? • What is referential integrity and how is it achieved? • What is indexing? • What is normalization and what are the different forms of normalizations? • Difference between server.transfer and server.execute method? • What id de-normalization and when do you do it? • What is better - 2nd Normal form or 3rd normal form? Why? • Can we rewrite subqueries into simple select statements or with joins?Example? • What is a function? Give some example? • What is a stored procedure? • Difference between Function and Procedure-in general? • Difference between Function and Stored Procedure? • Can a stored procedure call another stored procedure. If yes what level and can it be controlled? • Can a stored procedure call itself(recursive). If yes what level and can it be controlled.? • How do you find the number of rows in a table? • Difference between Cluster and Non-cluster index? • What is a table called, if it does not have neither Cluster nor Non-cluster Index? • Explain DBMS, RDBMS? • Explain basic SQL queries with SELECT from where Order By, Group By-Having? • Explain the basic concepts of SQL server architecture? • Explain couple pf features of SQL server • Scalability, Availability, Integration with internet, etc.)? • Explain fundamentals of Data ware housing & OLAP? • Explain the new features of SQL server 2000? • How do we upgrade from SQL Server 6.5 to 7.0 and 7.0 to 2000? • What is data integrity? Explain constraints? • Explain some DBCC commands? • Explain sp_configure commands, set co • Explain what are db_options used for? • What is the basic functions for master, msdb, tempdb databases? • What is a job? • What are tasks? • What are primary keys and foreign keys? • How would you Update the rows which are divisible by 10, given a set of numbers in column? • If a stored procedure is taking a table data type, how it looks? • How m-m relationships are implemented? • How do you know which index a table is using? • How will you test the stored procedure taking two parameters namely first name and last name returning full name? • How do you find the error, how can you know the number of rows effected by last SQL statement? • How can you get @@error and @@rowcount at the same time? • What are sub-queries? Give example? In which case sub-queries are not feasible? • What are the type of joins? When do we use Outer and Self joins? • Which virtual table does a trigger use? • How do you measure the performance of a stored procedure? • Questions regarding Raiseerror? • Questions on identity? • If there is failure during updation of certain rows, what will be the state? • Although no two phone interviews are the same, below outlines some potential questions to keep in mind as you prepare for a SQL Server DBA phone interview: • Can you explain your skill set? • Employers look for the following: • DBA (Maintenance, Security, Upgrades, Performance Tuning, etc.) • Database developer (T-SQL, DTS, SSIS, Analysis Services, Reporting Services, Crystal Reports, etc.) • Communication skills (oral and written) • o DBA's • This is your 30 second elevator pitch outlining your technical expertise and how you can benefit the organization • Can you explain the environments you have worked in related to the following • items: • SQL Server versions • SQL Server technologies • Relational engine, Reporting Services, Analysis Services, Integration Services • Number of SQL Servers • Number of instances • Number of databases • Range of size of databases • Number of DBAs • Number of Developers • Hardware specs (CPU’s, memory, 64 bit, SANs) IQ’s • What are the tasks that you perform on a daily basis and how have you automated them? • For example, daily checks could include: ▪ Check for failed processes ▪ Research errors ▪ Validate disk space is not low ▪ Validate none of the databases are offline or corrupt ▪ Perform database maintenance as available to do so • o For example, automation could include: ▪ Setup custom scripts to query for particular issues and email the team ▪ Write error messages centrally in the application and review that data ▪ Setup Operators and Alerts on SQL Server Agent Jobs for automated job notification Rearchitect Process-1 • How do you re-architect a process? • o Review the current process to understand what is occurring • o Backup the current code for rollback purposes o Determine what the business and technical problems are with the process • o Document the requirements for the new process • o Research options to address the overall business and technology needs • ▪ For example, these could include: • ▪ Views • ▪ Synonyms • ▪ Service Broker Rearchitect Process-2 • ▪ SSIS • Migrate to a new platform • Upgrade in place • Design and develop a new solution • Conduct testing (functional, load, regression, unit, etc.) • Run the systems in parallel • Sunset the existing system • Promote the new system • Additional information - Checklist to Re-Architect a SQL Server Database 3 rd party Applications • What is your experience with third party applications and why would you use them? • Experience • Backup tools • Performance tools • Code or data synchronization • Disaster recovery\high availability • Why • Need to improve upon the functionality that SQL Server offers natively • Save time, save money, better information or notification Performance Issue
• How do you identify and correct a SQL Server performance issue?
• o Identification - Use native tools like Profiler, Perfmon, system stored procedures, dynamic management views, custom stored procedures or third party tools • Analysis - Analyze the data to determine the core problems • Testing - Test the various options to ensure they perform better and do not cause worse performance in other portions of the application • Knowledge sharing - Share your experience with the team to ensure they understand the problem and solution, so the issue does not occur again • Additional information - MSSQLTips.com Category: Performance Tuning and Query Optimization New Commands • What are some of the new T-SQL commands with SQL Server 2005 that you have used and what value do they offer? • ROW_NUMBER - Means to page through a result set and only return the needed portion of the result set • Additional Information: Paging through SQL Server result sets with the ROW_NUMBER() Function • EXCEPT - The final result set where data exists in the first dataset and not in the second dataset ▪ Additional Information: Comparing Multiple SQL Server Datasets with the INTERSECT and EXCEPT operators • INTERSECT - The final result set where values in both of the tables match New Commands • Additional Information: Comparing Multiple SQL Server Datasets with the INTERSECT and EXCEPT operators • o PIVOT\UNPIVOT - Expression to flip rows to columns or vice versa • Additional Information: Crosstab queries using PIVOT in SQL Server 2005 • Synonyms - Alias to an object (table, stored procedure, function, view) to maintain the original object and refer to the new object as well • Additional Information: How and why should I use SQL Server 2005 synonyms? • NOTE - Many more commands do exist, this is an abbreviated list. DMV’s • What are the dynamic management views and what value do they offer? • The DMV's are a set of system views new to SQL Server 2005 to gain insights into particular portions of the engine • Here are some of the DMV's and the associated value: • sys.dm_exec_query_stats and sys.dm_exec_sql_text - Buffered code in SQL Server • Additional Information: Identifying the input buffer in SQL Server 2000 vs SQL Server 2005 • sys.dm_os_buffer_descriptors • Additional Information: Buffer Pool Space in SQL Server 2005 DMV’s • sys.dm_tran_locks - Locking and blocking • Additional Information: Locking and Blocking Scripts in SQL Server 2000 vs SQL Server 2005 • sys.dm_os_wait_stats - Wait stats • Additional Information: Waitstats performance metrics in SQL Server 2000 vs SQL Server 2005 • sys.dm_exec_requests and sys.dm_exec_sessions - Percentage complete for a process • Additional Information: Finding a SQL Server process percentage complete with dynamic management views DTS to SSIS Packages • What is the process to upgrade from DTS to SSIS packages? • You can follow the steps of the migration wizard but you may need to manually upgrade portions of the package that were not upgraded by the wizard • Additional Information: Upgrade SQL Server DTS Packages to Integration Services Packages • For script related tasks, these should be upgraded to new native components or VB.NET code SQL 2008 Packages • What are some of the features of SQL Server 2008 that you are looking into and why are they of interest? • Change Tracking • Plan Guides • SQL Data Collector • Data Auditing • Data compression • NOTE - Many more new features do exist, this is an abbreviated list. • Additional Information: MSSQLTips.com Category: SQL Server 2008