SQL Server Interview Questions
SQL Server Interview Questions
Answer: Commit statement helps in termination of the current transaction and does all the
changes that occur in transaction persistent and this also commits all the changes to the
database. COMMIT we can also use in store procedure.
ROLLBACK do the same thing just terminate the current transaction but one another thing is
that the changes made to database are ROLLBACK to the database.
Question: Can You explain integration between SQL Server 2005 and Visual Studio 2005?
Answer: This integration provide wider range of development with the help of CLR for database
server. Because CLR helps developers to get flexibility for developing database applications and
also provides language interoperability just like Visual C++, Visual Basic .Net and Visual C# .Net.
The CLR helps developers to get the arrays, classes and exception handling available through
programming languages such as Visual C++ or Visual C# which is use in stored procedures,
functions and triggers for creating database application dynamically and also provide more
efficient reuse of code and faster execution of complex tasks. We particularly liked the error-
checking powers of the CLR environment, which reduces run-time errors
Question: What is the difference between UNION ALL Statement and UNION?
Answer:- The main difference between UNION ALL statement and UNION is UNION All
statement is much faster than UNION, the reason behind this is that because UNION ALL
statement does not look for duplicate rows, but on the other hand UNION statement does look
for duplicate rows, whether or not they exist.
Question: SQL Server runs on which TCP/IP port and From where can you change the default
port?
Answer: SQL Server runs on port 1433 but we can also change it for better security and From
the network Utility TCP/IP properties –>Port number.both on client and the server.
Question: What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Answer: 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.
Normalizing a logical database design involves using formal methods to separate the data into
multiple, related tables. A greater number of narrow tables (with fewer columns) is
characteristic of a normalized database. A few wide tables (with more columns) is characteristic
of an non-normalized database. Reasonable normalization often improves performance. When
useful indexes are available, the Microsoft® SQL Server™ 2000 query optimizer is efficient at
selecting rapid, efficient joins between tables.
Question: If I want to see what fields a table is made of, and what the sizes of the
fields are, what option do I have to look for?
Sp_Columns ‘TableName’
Question: If you delete a table in the database, will the data in the table be deleted too?
Yes
Question: What is the Parse Query button used for? How does this help you?
Parse query button is used to check the SQL Query Syntax
Question: Tables are created in a ____________________ in SQL Server 2005.
resouce database(System Tables)
Question: Can a SELECT statement in SQL Server 2005 be used to make an assignment?
Explain with examples.
Yes. Select @MyDate = GetDate()
Question: What is the ORDER BY used for?
Order By clause is used for sorting records in Ascending or Descending order
Question: Does ORDER BY actually change the order of the data in the tables or does it just
change the output?
Order By clause change only the output of the data
Question: What are four major operators that can be used to combine conditions on a
WHERE clause?
OR, AND, IN and BETWEEN
Question: In a WHERE clause, do you need to enclose a text column in quotes? Do you need
to enclose a numeric column in quotes?
Enclose Text in Quotes (Yes)
Enclose Number in Quotes (NO)
Question: Is a null value equal to anything? Can a space in a column be considered a null
value? Why or why not?
No NULL value means nothing. We can’t consider space as NULL value.
Question: Will COUNT(column) include columns with null values in its count?
Yes, it will include the null column in count
Question: What are column aliases? Why would you want to use column aliases? How can
you embed blanks in column aliases?
You can create aliases for column names to make it easier to work with column names,
calculations, and summary values. For example, you can create a column alias to:
* Create a column name, such as “Total Amount,” for an expression such as (quantity *
unit_price) or for an aggregate function.
* Create a shortened form of a column name, such as “d_id” for “discounts.stor_id.”
After you have defined a column alias, you can use the alias in a Select query to specify query
output
Question: What are table qualifiers? When should table qualifiers be used?
[@table_qualifier =] qualifier
Is the name of the table or view qualifier. qualifier is sysname, with a default of NULL. Various
DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this
column represents the database name. In some products, it represents the server name of the
table’s database environment.
Question: Are semicolons required at the end of SQL statements in SQL Server 2005?
No it is not required
Question: When would you use the ROWCOUNT function versus using the WHERE clause?
Returns the number of rows affected by the last statement. If the number of rows is more than
2 billion, use ROWCOUNT_BIG.
Transact-SQL statements can set the value in @@ROWCOUNT in the following ways:
* Set @@ROWCOUNT to the number of rows affected or read. Rows may or may not be sent to
the client.
* Preserve @@ROWCOUNT from the previous statement execution.
* Reset @@ROWCOUNT to 0 but do not return the value to the client.
Statements that make a simple assignment always set the @@ROWCOUNT value to 1.
Question: Can a synonym name of a table be used instead of a table name in a SELECT
statement?
Yes
Question: Can a synonym of a table be used when you are trying to alter the definition of a
table?
Not Sure will try
Question: Can you type more than one query in the query editor screen at the same time?
Yes we can.
Question: While you are inserting values into a table with the INSERT INTO .. VALUES option,
does the order of the columns in the INSERT statement have to be the same as the order of
the columns in the table?
Not Necessary
Question: While you are inserting values into a table with the INSERT INTO .. SELECT option,
does the order of the columns in the INSERT statement have to be the same as the order of
the columns in the table?
Yes if you are not specifying the column names in the insert clause, you need to maintain the
column order in SELECT statement
Question: When would you use an INSERT INTO .. SELECT option versus an INSERT INTO ..
VALUES option? Give an example of each.
INSERT INTO .. SELECT is used insert data in to table from diffrent tables or condition based
insert. INSERT INTO .. VALUES you have to specify the insert values
Question: Can you change the data type of a column in a table after the table has been
created? If so,which command would you use?
Yes we can. Alter Table Modify Column
Question: Will SQL Server 2005 allow you to reduce the size of a column?
Yes it allows
Question: What integer data types are available in SQL Server 2005?
Exact-number data types that use integer data.
Data type Range Storage
bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte
Question: What is the default value of an integer data type in SQL Server 2005?
NULL
Question: If you are going to have too many nulls in a column, what would be the best data
type to use?
Variable length columns only use a very small amount of space to store a NULL so VARCHAR
datatype is the good option for null values
Question: When columns are added to existing tables, what do they initially contain?
The column initially contains the NULL values
Question: What command would you use to add a column to a table in SQL Server?
ALTER TABLE tablename ADD column_name DATATYPE
Question: How many indexes does SQL Server 2005 allow you to have on a table?
250 indices per table
Question: What is the default ordering that will be created by an index (ascending or
descending)?
Clustered indexes can be created in SQL Server databases. In such cases the logical order of the
index key values will be the same as the physical order of rows in the table.
By default it is ascending order, we can also specify the index order while index creation.
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
Question: What command must you use to include the NOT NULL constraint after a table has
already been created?
DEFAULT, WITH CHECK or WITH NOCHECK
Question: When a PRIMARY KEY constraint is included in a table, what other constraints does
this imply?
Unique + NOT NULL
Question: How are the UNIQUE and PRIMARY KEY constraints different?
A UNIQUE constraint is similar to PRIMARY key, but you can have more than one UNIQUE
constraint per table.
When you declare a UNIQUE constraint, SQL Server creates a UNIQUE index to speed up the
process of searching for duplicates. In this case the index defaults to NONCLUSTERED index,
because you can have only one CLUSTERED index per table.
* The number of UNIQUE constraints per table is limited by the number of indexes on the table
i.e 249 NONCLUSTERED index and one possible CLUSTERED index.
Contrary to PRIMARY key UNIQUE constraints can accept NULL but just once. If the constraint is
defined in a combination of fields, then every field can accept NULL and can have some values
on them, as long as the combination values is unique.
Question: What is a referential integrity constraint? What two keys does the referential
integrity constraint usually include?
Referential integrity in a relational database is consistency between coupled tables. Referential
integrity is usually enforced by the combination of a primary key or candidate key (alternate
key) and a foreign key. For referential integrity to hold, any field in a table that is declared a
foreign key can contain only values from a parent table’s primary key or a candidate key. For
instance, deleting a record that contains a value referred to by a foreign key in another table
would break referential integrity. The relational database management system (RDBMS)
enforces referential integrity, normally either by deleting the foreign key rows as well to
maintain integrity, or by returning an error and not performing the delete. Which method is
used would be determined by the referential integrity constraint, as defined in the data
dictionary.
Question: Can you use the ON DELETE and ON UPDATE in the same constraint?
Yes we can.
CREATE TABLE part_sample
(part_nmbr int PRIMARY KEY,
part_name char(30),
part_weight decimal(6,2),
part_color char(15) )
CREATE TABLE order_part
(order_nmbr int,
part_nmbr int
FOREIGN KEY REFERENCES part_sample(part_nmbr)
ON DELETE NO ACTION ON UPDATE NO ACTION,
qty_ordered int)
GO
Question: What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to
database servers. There are six RAID levels 0 through 5 offering different levels of performance,
fault tolerance.
Question: 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.
Question: How to restart SQL Server in single user mode? How to start SQL Server in minimal
configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL
Server in single user mode and -f is used to start the SQL Server in minimal confuguration
mode.
Question: As a part of your job, what are the DBCC commands that you commonly use for
database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs.
Question: What is the difference between them (Ethernet networks and token ring
networks)?
With Ethernet, any devices on the network can send data in a packet to any location on the
network at any time. With Token Ring, data is transmitted in ‘tokens’ from computer to
computer in a ring or star configuration. Token ring speed is 4/16 Mbit/sec , Ethernet – 10/100
Mbit/sec.
Question: 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 triggers. But in SQL Server 2000 you could create pre triggers also.
Question: 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().
Execution context is represented by a pair of security tokens: a login token and a user token.
The tokens identify the primary and secondary principals against which permissions are
checked and the source used to authenticate the token. A login connecting to an instance of
SQL Server has one login token and one or more user tokens, depending on the number of
databases to which the account has access.
Database User
Database Role
Application Role
Question: What is the use of the Public database role in SQL Server?
Every database user belongs to the public database role. When a user has not been granted or
denied specific permissions on a securable, the user inherits the permissions granted to public
on that securable.
##MS_SQLResourceSigningCertificate##
##MS_SQLReplicationSigningCertificate##
##MS_SQLAuthenticatorCertificate##
##MS_AgentSigningCertificate##
##MS_PolicyEventProcessingLogin##
##MS_PolicySigningCertificate##
##MS_PolicyTsqlExecutionLogin##
Question: What will you do if you lost rights of your SQL Server instance?
We can use the below options
1. Dedicated Administrator Connection
2. BUILIN\Administrator Group (Incase its rights are not revoked)
3. Final Option is to change the registry value
4. You can change authentication mode via registry
Question: What is the Guest user account in SQL Server? What login is it mapped to it?
The Guest user account is created by default in all databases and is used when explicit
permissions are not granted to access an object. It is not mapped directly to any login, but can
be used by any login. Depending on your security needs, it may make sense to drop the Guest
user account, in all databases except Master and TempDB
Question: What are steps to load a .NET code in SQL SERVER 2005?
Write the managed code and compile it to a DLL/Assembly.
After the DLL is compiled using the “CREATE ASSEMBLY” command you can load the assemby
into SQL SERVER. Below is the create command which is loading “mycode.dll” into SQL SERVER
using the “CREATE ASSEMBLY” command
Syntax
CREATE ASSEMBLY AssemblyName FROM ‘C:/MyAssmbly.dll’
Question: If I want to see which files are linked with which assemblies?
Use sys.Assemblies_files system tables have the track about which files are associated with
what assemblies.
SELECT * FROM sys.assemblies_files
Question: Does .NET CLR and SQL SERVER run in different process?
.NET CLR engine (hence all the .NET applications) and SQL SERVER run in the same process or
address space. This “Same address space architecture” is implemeted so that there no speed
issues. If the architecture was implemented the other way (i.e. SQL SERVER and .NET CLR
engine running in different memory process area) there would have been reasonable speed
issue.
SQL SERVER can control .NET framework by “Host Control” mechanism provided by .NET
Framework 2.0. Using the “Host Control” framework external application’s can control the way
memory management is done, thread allocation’s are done and lot more. SQL SERVER uses
“host Control” mechanism exposed by .NET 2.0 and controls the framework.
NOTE: Loading .NET programming consumes some memory resources around 20 to 30 MB(it
may vary depending on lot of situations). So if you really need .NET Integration then only go for
this option.
* Exceptional conditions
* Code loading
* Class loading
* Security particulars
* Resource allocation
SQL Server uses the “ICLRRuntimeHOST” to control .NET run time as the flexibility provided by
the interface is far beyond what is given by the previous .NET version, and that ‘s what exactly
SQL Server needs, a full control of the .NET run time.
Now for SQL SERVER it’s .NET the external third party which is running and SQL SERVER has to
be sure that .NET runtime crashes does not affect his working. So in order that SQL Server runs
properly there are three sandboxes that user code can run:
Safe Access sandbox: This will be the favorite setting of DBA’s if they are compelled to run CLR-
Safe access Safe means you have only access to in-proc data access functionalities. So you can
create stored procedures, triggers, functions, data types, triggers etc. But you can not access
memory, disk, create files etc. In short you ca not hang the SQL Server.
External access sandbox: In External access you can use some real cool features of .NET like
accessing file systems outside box, you can leverage your classes etc. But here you are not
allowed to play around with threading, memory allocation etc.
Unsafe access sandbox:In Unsafe access you have access to memory management,
threading,etc. So here developers can write unreliable and unsafe code which destabilizes SQL
Server. In the first two access levels of sand box its difficult to write unreliable and unsafe code.
Bulk Log Backup: —Bulk Log backups contain both transactional data and any physical extents
modified by bulk operations while the database was in Bulk Logged recovery.
Tail Log Backup: —Tail Log backups are completed when the database is in Full or Bulk Logged
recovery prior to a database restoration to capture all transaction log records that have not yet
been backed up. It is possible in some instances to execute a Tail Log backup even if the
database is damaged.
The default instance of SQL Server is assigned the TCP Port 1433 by default to support client
incoming requests. However, because more than one application/SQL Server Instances cannot
share a port assignment, any named instances are given a random port number when the
service is started. This random port assignment makes it difficult for clients to connect to it,
because the client applications don’t know what port the server is listening on. To meet this
need, the SQLBrowser Service was created.
On start‐up, the SQLBrowser Service queries the registry to discover all the names and port
numbers of installed servers and reserves UDP Port 1434. It then listens on UDP Port 1434 for
SQL Server Resolution Protocol (SSRP) requests and responds to the requests with the list of
instances and their respective port assignments so that clients can connect without knowing
the port number assignment.
It is very important that no unauthenticated traffic on UDP Port 1434 be allowed on the
network, because the service will respond to any request on that port.
If the SQLBrowser Service is disabled, it will be necessary to specify a static port number for all
named instances of the SQL Server Service and to configure all client applications that connect
to those instances with the appropriate connection information.
There will be only one SQL Browser Service for all the instances on same machine.
Question: What are the steps SQL Server performs internally at the time of FULL backup?
SQL Server follow the below steps once you execute the BACKUP command
1.Backup Process will lock the database and block all the transaction
2.Place a mark in the transaction log
3.Release the database lock
4.Extract all the pages in the data files and write them to the backup device
5.Lock the database and block all the transactions
6.Place a mark in the transaction log
7.Release the database lock
8.Extract the portion of the log between the marks and append it to backup
VIA
The Virtual Interface Adapter (VIA) can be used only by VIA hardware.
Shared Memory
Shared Memory can only be used on the local computer and cannot be used as a network
protocol.
Question: What is the difference between database mirroring and log shipping?
Question: How to troubleshoot suspect database problem? How to bring it back online? What
are the do you need to perform once the database is online?
Solution
Step 1: Bring the database online using below script
USE Master
GO
What is Schema in SQL Server 2005? Explain its properties with example?
A schema is nothing more than a named, logical container in which you can create database
objects. A new schema is created using the CREATE SCHEMA DDL statement.
Properties
Ownership of schemas and schema-scoped securables is transferable.
Objects can be moved between schemas
A single schema can contain objects owned by multiple database users.
Multiple database users can share a single default schema.
Permissions on schemas and schema-contained securables can be managed with greater
precision than in earlier releases.
A schema can be owned by any database principal. This includes roles and application
roles.
A database user can be dropped without dropping objects in a corresponding schema.
– data insertion –
– Data Selection –
Select * From Employee.Empinfo
1. Service Packs
2. Hot fixes
Question: What is the difference between a Service Pack and a Hotfix?
Service Packs normally have three properties:
Provide security fixes
Correct software errors
Enhance performance
Service Packs don’t add new functionality or change the interface dramatically. Service Packs
are bundled into a programmed delivery method, and are cumulative. That means that you can
install Service Pack three without applying Service Pack two, or even one. They are for general
use — pretty much everyone should install the Service Pack
A Hotfix is usually a specific security or software flaw that is addressed in code. There may or
may not be a packaged delivery method — some Hotfixes just come with instructions of how
and where to copy the patch. Hotfixes are normally not for everyone — Microsoft states that
you should only apply the patch if you’re having the specific problem it addresses. Even then,
some Hotfixes are only available from a Microsoft support representative.
Question: What does integration of .NET Framework mean for SQL Server 2005?
This feature enables us to execute C# or VB.NET code in the DBMS to take advantage of the
.NET functionality. This feature gives more flexibility in writing complex stored procedures,
functions, and triggers that can be written in .net compatible language.
Question: What is new with the Reporting services in SQL server 2005?
SQL Server 2005 Reporting Services is a key component of SQL Server 2005 that provides
customers with an enterprise-capable reporting platform. This comprehensive environment is
used for authoring, managing, and delivering reports to the entire organization. SQL Server
2005 reporting services have some major changes when compared with the previous version.
-> Changes to the core functionality of the Reporting services in the design of the report,
processing, and interactivity
-> Better Integration with other components – Enhanced integration with other components
within SQL Server 2005 like SSIS, SSAS and SQL Server Management studio
-> Report Builder – A new reporting tool that enables business users to create their own reports
Question: What is new with the Analysis Services (SSAS) in SQL Server 2005?
SQL Server 2005 Analysis Services (SSAS) delivers online analytical processing (OLAP) and data
mining functionality through a combination of server and client technologies, further reinforced
through the use of a specialized development and management environment coupled with a
well-defined object model for designing, creating, deploying, and maintaining business
intelligence applications. The server component of Analysis Services is implemented as a
Microsoft Windows service. Clients communicate with Analysis Services using the public
standard XML for Analysis (XMLA), a SOAP-based protocol. Let us see the enhancements of
made to SSAS.
· Supports up to 16 instances of Analysis Services Service.
· As discussed above, the Analysis Services service fully implements the XML for Analysis
(XMLA) 1.1 specification. All communication with an instance of Analysis Services is handled
through XMLA commands in SOAP messages.
· Uses the Proactive caching.
Question: What is Full Text Search? How does it get implemented in SQL server 2005?
Full-text search allows fast and flexible indexing for keyword-based query of text data stored in
a Microsoft SQL Server database. In contrast to the LIKE predicate which only works on
character patterns, full-text queries perform linguistic searches against this data, by operating
on words and phrases based on rules of a particular language.
Question: What is Replication? What is the need to have the replication? What are the
enhancements made to SQL Server 2005 related to the replication?
“Replication is a set of technologies for copying and distributing data and database objects from
one database to another and then synchronizing between databases to maintain consistency.”
In short, replication is all about having multiple copies of the same database. We need
replication when we need to distribute data to and from different locations. Generally we have
a master copy of data. There will be multiple slaves (Clients) located at various locations which
need to be replicated. We use replication for a variety of reasons. Load balancing is sharing the
data among a number of servers and distributing the query load. Offline processing is one of
the main reasons. In this scenario we need to modify the data on the database that is not
connected to the network. The last reason may be to have a back-up to the database in case of
failure to the existing database. Let us see the enhancements of SQL server 2005 database
related to replication.
· Database Mirroring – Database Mirroring is moving the transactions of database from one
SQL Server database to another SQL server database on a different SQL Server.
· Replication Management topology (RMO) – RMO is a new construct in SQL Server 2005. It is a
.NET Framework library that provides a set of common language runtime classes for
configuring, managing, and scripting replication, and for synchronizing Subscribers.
Question: What are Various Service packs available for SQL Server 2005?
As of now there are two service packs available for the SQL Server 2005.
· Service Pack 1 – Has major changes or enhancements to SQL Server 2005 in Analysis Services,
Data Programmability, SSIS, and reporting services.
· Service Pack 2 – Unlike Service Pack 2, this service pack enables SQL Server 2005 customers to
take advantage of the enhancements within Windows Vista and the 2007 Office system.
Question: What are the New Data types introduced in SQL Server 2005?
SQL Server 2005 has added some new data types to its existing data types.
. XML Data type
· VARCHAR (MAX)
· NVARCHAR (MAX)
· VARBINARY (MAX)
As we can see, the new term MAX has been introduced in SQL Server 2005. This new specifier
expands the storage capabilities of the varchar, nvarchar, and varbinary data types.
Varchar(max), nvarchar(max), and varbinary(max) are collectively called large-value data types.
Syntax
CREATE DATABASE AdventureWorks_SS ON
(
NAME = AdventureWorks_Data,
FILENAME = ‘D:\Program Files\Microsoft SQL
Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.ss’
)
AS SNAPSHOT OF AdventureWorks
The WITH Statement define the CTE and later using the CTE name I have display the CTE data.
Question: Why would you use CTE rather than simple View?
With CTE you can use a recursive query with CTE itself. That’s not possible with view.
BEGIN TRY
DELETE table 1 WHERE id=122
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER As ErrNum,
ERROR_SEVERITY ( ) As ErrSev,
ERROR_STATE ( ) As ErrSt,
ERROR_MESSAGE ( ) As ErrMsg;
END CATCH
Select Status as OrderStatus, isnull (*2006+, 0 ) as ‘YR 2007′, isnull(*2007+, 0) as ‘Yr 2007′ from
PURCHASEORDERHEADERCTE Pivot (sum(subtotal) for Orderdate in ([2006], [2007] ) ) as
pivoted
You can see from the above SQL the top WITH statement is the CTE supplied to the PIVOT. After
that PIVOT is applied on subtotal and orderdate. You have to secify in what you want the pivot
(here it is 2006 and 2007). So below is the output of CTE table.
CTE ouput
After the PIVOT is applied you can see the rows now grouped column wise with the subtotal
assigned to each. You can summarize that PIVOT summarizies your data in cross tab format.
Select col1, col2, RANK(), over (order by col2) as ROW_NUMER from table _1
Select col1, col2, Dense_rank(), over (order by col2) as ROW_NUMER from table _1
col1 col2 RowNumber
121
232
432
432
563
563
SQL injection attacks typically are easy to avoid by ensuring that a system has strong input
validation.
As name suggest’s we inject SQL which can be relatively dangerous for the database.
Exammple:
Now some body does not put “x” as the input but put “x; DROP TABLE members;”. So the actual
SQL will execute is:
Atomicity states that database modifications must follow an “all or nothing” rule. Each
transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails.
It is critical that the database management system maintain the atomic nature of transactions
in spite of any DBMS, operating system or hardware failure.
Consistency states that only valid data will be written to the database.If, for some reason, a
transaction is executed that violates the database’s consistency rules, the entire transaction will
be rolled back and the database will be restored to a state consistent with those rules. On the
other hand, if a transaction successfully executes, it will take the database from one state that
is consistent with the rules to another state that is also consistent with the rules.
Isolation requires that multiple transactions occurring at the same time not impact each other’s
execution. For example, if Joe issues a transaction against a database at the same time that
Mary issues a different transaction, both transactions should operate on the database in an
isolated manner. The database should either perform Joe’s entire transaction before executing
Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced
as a side effect of part of Mary’s transaction that will not eventually be committed to the
database. Note that the isolation property does not ensure which transaction will execute first,
merely that they will not interfere with each other.
Durability ensures that any transaction committed to the database will not be lost. Durability is
ensured through the use of database backups and transaction logs that facilitate the
restoration of committed transactions in spite of any subsequent software or hardware failures.
Question: What is “Begin Trans”, “Commit Tran”, “Rollback Tran” and “Save Tran”?
Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group successfully complete. If any of the tasks
fails, the transaction fails. Therefore, a transaction has only two results: success or failure.
Incomplete steps result in the failure of the transaction.
Users can group two or more Transact-SQL statements into a single transaction using the
following statements:
* Begin Transaction
* Rollback Transaction
* Commit Transaction
Begin Transaction
Marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments
@@TRANCOUNT by 1.
Rollback Transaction
If anything goes wrong with any of the grouped statements, all changes need to be aborted.
The process of reversing changes is called rollback in SQL Server terminology.
A ROLLBACK, on the other hand, works regardless of the level at which it is issued, but rolls back
all transactions, regardless of the nesting level
Commit Transaction
If everything is in order with all statements within a single transaction, all changes are recorded
together in the database. In SQL Server terminology, we say that these changes are committed
to the database.
A COMMIT issued against any transaction except the outermost one doesn’t commit any
changes to disk – it merely decrements the@@TRANCOUNT automatic variable.
Save Tran
Savepoints offer a mechanism to roll back portions of transactions. A user can set a savepoint,
or marker, within a transaction. The savepoint defines a location to which a transaction can
return if part of the transaction is conditionally canceled. SQL Server allows you to use
savepoints via the SAVE TRAN statement, which doesn’t affect the @@TRANCOUNT value. A
rollback to a savepoint (not a transaction) doesn’t affect the value returned by
@@TRANCOUNT, either. However, the rollback must explicitly name the savepoint: using
ROLLBACK TRAN without a specific name will always roll back the entire transaction.
Syntax
CHECKPOINT
Concurrency control theory has two classifications for the methods of instituting concurrency
control:
Pessimistic concurrency control
A system of locks prevents users from modifying data in a way that affects other users. After a
user performs an action that causes a lock to be applied, other users cannot perform actions
that would conflict with the lock until the owner releases it. This is called pessimistic control
because it is mainly used in environments where there is high contention for data, where the
cost of protecting data with locks is less than the cost of rolling back transactions if concurrency
conflicts occur.
Optimistic concurrency control
In optimistic concurrency control, users do not lock data when they read it. When an update is
performed, the system checks to see if another user changed the data after it was read. If
another user updated the data, an error is raised. Typically, the user receiving the error rolls
back the transaction and starts over. This is called optimistic because it is mainly used in
environments where there is low contention for data, and where the cost of occasionally rolling
back a transaction outweighs the costs of locking data when read.
For example, an editor makes changes to a document submitted by a writer, but when the
changes are incorporated into the master copy of the document by the production department,
they find that new unedited material has been added to the document by the author. This
problem could be avoided if no one could add new material to the document until the editor
and production department finish working with the original document.
SQL Server can lock these resources (listed in order of increasing granularity).
RID: Row identifier. Used to lock a single row within a table.
Key: Row lock within an index. Used to protect key ranges in serializable transactions.
Page: 8 kilobyte –(KB) data page or index page.
Extent: Contiguous group of eight data pages or index pages.
Table: Entire table, including all data and indexes.
DB: Database.
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.
Question: If you are using COM+, what “Isolation” level is set by default?
SERIALIZABLE transaction isolation level is the default isolation level for the COM+ application.
Question: What are “Lock” hints?
A range of table-level locking hints can be specified using the SELECT, INSERT, UPDATE, and
DELETE statements to direct Microsoft SQL Server 2000 to the type of locks to be used. Table-
level locking hints can be used when a finer control of the types of locks acquired on an object
is required. These locking hints override the current transaction isolation level for the session.
Question: What are the steps you can take to avoid “Deadlocks”?
Here are some tips on how to avoid deadlocking on your SQL Server:
* Ensure the database design is properly normalized.
* Have the application access server objects in the same order each time.
* During transactions, don’t allow any user input. Collect it before the transaction begins.
* Avoid cursors.
* Keep transactions as short as possible. One way to help accomplish this is to reduce the
number of round trips between your application and SQL Server by using stored procedures or
keeping transactions with a single batch. Another way of reducing the time a transaction takes
to complete is to make sure you are not performing the same reads over and over again. If your
application does need to read the same data more than once, cache it by storing it in a variable
or an array, and then re-reading it from there, not from SQL Server.
* Reduce lock time. Try to develop your application so that it grabs locks at the latest possible
time, and then releases them at the very earliest time.
* If appropriate, reduce lock escalation by using the ROWLOCK or PAGLOCK.
* Consider using the NOLOCK hint to prevent locking if the data being locked is not modified
often.
* If appropriate, use as low of an isolation level as possible for the user connection running the
transaction.
* Consider using bound connections.
Question: How can I know what locks are running on which resource?
Use SP_Locks system stored procedure
RDBMS is a Relational Data Base Management System Relational DBMS. This adds the
additional condition that the system supports a tabular structure for the data, with enforced
relationships between the tables. This excludes the databases that don’t support a tabular
structure or don’t enforce relationships between tables.
Many DBA’s think that RDBMS is a Client Server Database system but thats not the case with
RDBMS.
Yes you can say DBMS does not impose any constraints or security with regard to data
manipulation it is user or the programmer responsibility to ensure the ACID PROPERTY of the
database whereas the rdbms is more with this regard bcz rdbms difine the integrity constraint
for the purpose of holding ACID PROPERTY.
When you insert rows into a table they go on a page, into ‘slots’, your row will have a row
length and you can get only so many rows on the 8Kbyte page. What happens when that row’s
length increases because you entered a bigger product name in your varchar column for
instance, well, SQL Server needs to move the other rows along in order to make room for your
modification, if the combined new length of all the rows on the page will no longer fit on that
page then SQL Server grabs a new page and moves rows to the right or left of your modification
onto it – that is called a ‘page split’.
Case sensitivity
If A and a, B and b, etc. are treated in the same way then it is case-insensitive. A computer
treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value
of A is 65, while a is 97. The ASCII value of B is 66 and b is 98.
Accent sensitivity
If a and á, o and ó are treated in the same way, then it is accent-insensitive. A computer treats a
and á differently because it uses ASCII code for differentiating the input. The ASCII value of a is
97 and áis 225. The ASCII value of o is 111 and ó is 243.
Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana
sensitive.
Width sensitivity
When a single-byte character (half-width) and the same character when represented as a
double-byte character (full-width) are treated differently then it is width sensitive.
Database, Tables and columns with different collation
SQL Server 2000 allows the users to create databases, tables and columns in different
collations.
The start of each page is a 96-byte header used to store system information, such as the type of
page, the amount of free space on the page, and the object ID of the object owning the page.
Extent is a collection of 8 pages. There are two types of extents. 1. Uniform Extents 2. Mix
Extents
There are three main normal forms, each with increasing levels of normalization:
# First Normal Form (1NF): Each field in a table contains different information. For example, in
an employee list, each table would contain only one birthdate field.
# Second Normal Form (2NF): Each field in a table that is not a determiner of the contents of
another field must itself be a function of the other fields in the table.
# Third Normal Form (3NF): No duplicate information is permitted. So, for example, if two
tables both require a birthdate field, the birthdate information would be separated into a
separate table, and the two other tables would then access the birthdate information via an
index field in the birthdate table. Any change to a birthdate would automatically be reflect in all
tables that link to the birthdate table.
There are additional normalization levels, such as Boyce Codd Normal Form (BCNF), fourth
normal form (4NF) and fifth normal form (5NF). While normalization makes databases more
efficient to maintain, they can also make them more complex because data is separated into so
many different tables.