sqlserver material 5
Is there any Performance Difference between IF EXISTS (Select null from table) and IF EXISTS (Select 1 from table)?
There is no performance difference between IF EXISTS (Select null from table) and IF EXISTS (Select 1 from table). (Read more here)What is Difference in Performance between INSERT TOP (N) INTO Table and Using Top with INSERT?
INSERT TOP (N) INTO Table is faster than Using Top with INSERT but when we use INSERT TOP (N) INTO Table, the ORDER BY clause is totally ignored. (Read more here)Does the Order of Columns in UPDATE statements Matter?
No, the order of columns in UPDATE statement does not matter for results updated.Both the below options produce the same results.
Option 1:
UPDATE
TableName
SET
Col1
=
'Value'
,
Col2
=
'Value2'
Option 2:
UPDATE
TableName
SET
Col2
=
'Value2'
,
Col1
=
'Value'
3) Questions on SQL SERVER 2008
What are the basic functions for master, msdb, model, tempdb and resource databases?
The master database holds information for all the databases located on the SQL Server instance, and it is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.
The resource Database is a read-only database that contains all the system objects that are included in the SQL Server. SQL Server system objects such as sys.objects are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.
What is the Maximum Number of Index per Table?
For SQL Server 2005:1 Clustered Index + 249 Nonclustered Index = 250 Index.
For SQL Server 2008:
1 Clustered Index + 999 Nonclustered Index = 1000 Index. (Read more here)
Explain Few of the New Features of SQL Server 2008 Management Studio
SQL Server 2008 Microsoft has upgraded SSMS with many new features as well as added tons of new functionalities requested by DBAs for long time.A few of the important new features are as follows:
- IntelliSense for Query Editing
- Multi Server Query
- Query Editor Regions
- Object Explorer Enhancements
- Activity Monitors
Explain IntelliSense for Query Editing:
After implementing IntelliSense, we will not have to remember all the syntax or browse online references. IntelliSense offers a few additional features besides just completing the keyword.Explain MultiServer Query:
SSMS 2008 has a feature to run a query on different servers from one query editor window. First of all, make sure that you registered all the servers under your registered server. Once they are registered, right click on server group name and click New Query.e.g. for server version information,
SELECT
SERVERPROPERTY
(
'Edition'
)
AS
Edition
,
SERVERPROPERTY
(
'ProductLevel'
)
AS
ProductLevel
,
SERVERPROPERTY
(
'ProductVersion'
)
AS
ProductVersion
Explain Query Editor Regions:
When the T-SQL code is more than hundreds of lines, after a while, it becomes more and more confusing.The regions are defined by the following hierarchy:
From first GO command to the next GO command.
Statements between BEGIN – END, BEGIN TRY – END TRY, BEGIN CATCH – END CATCH
Explain Object Explorer Enhancements:
In Object Explorer Detail, the new feature is Object Search. Enter any object name in the object search box and the searched result will be displayed in the same window as Object Explorer Detail.Additionally, there are new wizards which help you perform several tasks, from policy management to disk monitoring. One cool thing is that everything displayed in the object explorer details screen can be right away copied and pasted to Excel without any formatting issue.
Explain Activity Monitors:
There are four graphs- percent; Processor Time,
- Waiting Tasks,
- Database I/O,
- Batch Requests/Sec
What is Service Broker?
Service Broker is a message-queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is a feature which provides facility to SQL Server to send an asynchronous, transactional message. It allows a database to send a message to another database without waiting for the response; so the application will continue to function if the remote database is temporarily unavailable. (Read more here)
Where are SQL server Usernames and Passwords Stored in the SQL server?
They get stored in System Catalog Views, sys.server_principals and sys.sql_logins. However, you will not find password stored in plain text.
What is Policy Management?
Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes. (Read More Here)
What is Database Mirroring?
Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients, which is known as the principal database. Updates made by the clients to the principal database are applied to the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database.
What are Sparse Columns?
A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve non-null values. (Read more here)
What does TOP Operator Do?
The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETE statements.
What is CTE?
CTE is the abbreviation for Common Table Expression. A CTE is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. (Read more here)
What is MERGE Statement?
MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement, we can include the logic of such data modifications in one statement that even checks when the data is matched, then just update it, and when unmatched, insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once. (Read more here)
What is Filtered Index?
Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performance, reduces index maintenance costs, and reduces index storage costs when compared with full-table indexes. When we see an Index created with a WHERE clause, then that is actually a FILTERED INDEX.
Which are the New Data Types Introduced in SQL SERVER 2008?
The GEOMETRY Type: The GEOMETRY datatype is a system .NET common language runtime (CLR) datatype in SQL Server. This type represents data in a two-dimensional Euclidean coordinate system.
The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.
New Date and Time Data types: SQL Server 2008 introduces four new data types related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.
- DATE: The new DATE data type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.
- TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME(n) defines this level of fractional second precision from 0 to 7 digits of precision.
- The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time-zone-aware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + time + time-zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.
- The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the lower boundary of 1753 of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides.
What are the Advantages of Using CTE?
- Using CTE improves the readability and enables easy maintenance of complex queries.
- The query can be divided into separate, simple, and logical building blocks, which can be then used to build more complex CTEs until the final result set is generated.
- CTE can be defined in functions, stored procedures, triggers or even views.
- After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data.
How can we Rewrite Sub-Queries into Simple Select Statements or with Joins?
Yes. We can rewrite sub-queries using the Common Table Expression (CTE). A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
e.g.
USE AdventureWorks
GO
WITH EmployeeDepartment_CTE AS (
SELECT EmployeeID,DepartmentID,ShiftID
FROM HumanResources.EmployeeDepartmentHistory
)
SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID
FROM HumanResources.Department ed
INNER JOIN EmployeeDepartment_CTE ecte ON ecte.DepartmentID = ed.DepartmentID
GO
USE AdventureWorks
GO
WITH EmployeeDepartment_CTE AS (
SELECT EmployeeID,DepartmentID,ShiftID
FROM HumanResources.EmployeeDepartmentHistory
)
SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID
FROM HumanResources.Department ed
INNER JOIN EmployeeDepartment_CTE ecte ON ecte.DepartmentID = ed.DepartmentID
GO
What is CLR?
In SQL Server 2008, SQL Server objects such as user-defined functions can be created using such CLR languages. This CLR language support extends not only to user-defined functions, but also to stored procedures and triggers. You can develop such CLR add-ons to SQL Server using Visual Studio 2008. (Read more here)
What are Synonyms?
Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object. (Read more here)
What is LINQ?
Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:
- Tools to create classes (usually called entities) mapped to database tables
- Compatibility with LINQ’s standard query operations
- The DataContext class with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more
What are Isolation Levels?
Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side-effects, such as dirty reads or phantom reads, are allowed.
Transaction isolation levels control the following:
- Whether locks are taken when data is read, and what type of locks are requested.
- How long the read locks are held.
- Whether a read operation referencing rows modified by another transaction
- blocks until the exclusive lock on the row is freed,
- retrieves the committed version of the row that existed at the time the statement or transaction started, and
- reads the uncommitted data modification.(Read more here)
What is Use of EXCEPT Clause?
EXCEPT clause is similar to MINUS operation in Oracle. The EXCEPT query and MINUS query return all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fields in the result sets with similar data types. (Read more here)
What is XPath?
XPath uses a set of expressions to select nodes to be processed. The most common expression that you’ll use is the location path expression, which returns back a set of nodes called a node set. XPath can use both an unabbreviated and abbreviated syntax. The following is the unabbreviated syntax for a location path:
/axisName::nodeTest[predicate]/axisName::nodeTest[predicate]
What is NOLOCK?
Using the NOLOCK query optimizer hint is generally considered a good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken on data when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay (blocking). (Read more here)
What is the Difference between Update Lock and Exclusive Lock?
When Exclusive Lock is on any process, no other lock can be placed on that row or table. Every other process have to wait till Exclusive Lock completes its tasks.
Update Lock is a type of Exclusive Lock, except that it can be placed on the row which already has Shared Lock on it. Update Lock reads the data of the row which has the Shared Lock as soon as the Update Lock is ready to change the data it converts itself to the Exclusive Lock.
How will you Handle Error in SQL SERVER 2008?
SQL Server now supports the use of TRY…CATCH constructs for providing rich error handling. TRY…CATCH lets us build error handling at the level we need, in the way we need to by setting a region where if any error occurs, it will break out of the region and head to an error handler. The basic structure is as follows:BEGIN TRY
<code>
END TRY
BEGIN CATCH
<code>
END CATCH
So if any error occurs in the TRY block, then execution is diverted to the CATCH block, and the error can be resolved.What is RAISEERROR?
RaiseError generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct. (Read more here)How to Rebuild the Master Database?
Master database is system database and it contains information about running server’s configuration. When SQL Server 2005 is installed, it usually creates master, model, msdb, tempdb, resourcedb and the distribution system database by default. Only the Master database is the one which is absolutely a must-have database. Without the Master database, the SQL Server cannot be started. This is the reason why it is extremely important to backup the Master database.To rebuild the Master database, run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server. (Read more here)
What is the XML Datatype?
The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that has a missing single top-level element. You can create columns and variables of the xml type and store XML instances in them. The xml data type and associated methods help integrate XML into the relational framework of SQL Server.What is Data Compression?
In SQL SERVE 2008, Data Compression comes in two flavors:- Row Compression
- Page Compression
Row Compression
Row compression changes the format of physical storage of data. It minimize the metadata (column information, length, offsets etc) associated with each record. Numeric data types and fixed-length strings are stored in variable-length storage format, just like Varchar. (Read more here)Page Compression
Page compression allows common data to be shared between rows for a given page. It uses the following techniques to compress data:- Row compression.
- Prefix Compression. For every column in a page, duplicate prefixes are identified. These prefixes are saved in compression information headers which resides after the page header. A reference number is assigned to these prefixes and that reference number is replaced where ever those prefixes are being used.
Dictionary Compression
Dictionary compression searches for duplicate values throughout the page and stores them in CI. The main difference between prefix and dictionary compression is that the former is only restricted to one column while the latter is applicable to the complete page.What is Use of DBCC Commands?
The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for SQL Server. DBCC commands are used to perform the following tasks.- Maintenance tasks on database, index, or filegroup.
- Tasks that gather and display various types of information.
- Validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.
- Miscellaneous tasks such as enabling trace flags or removing a DLL from memory. (Read more here)
How to Copy the Tables, Schema and Views from one SQL Server to Another?
There are multiple ways to do this.- “Detach Database” from one server and “Attach Database” to another server.
- Manually script all the objects using SSMS and run the script on a new server.
- Use Wizard of SSMS. (Read more here)
Comments