Sql-Server Database Training Documentation Version No.1.0 15 Feb 2010
Sql-Server Database Training Documentation Version No.1.0 15 Feb 2010
Version No.1.0
15th Feb 2010
Last Edited:
1.0 Introduction........................................................................................................................................................................6
2.0 SQL.....................................................................................................................................................................................6
2.1 Different roles of SQL.................................................................................................................................. 6
3.0 Features..............................................................................................................................................................................7
3.1 Enterprise Data Management...................................................................................................................... 7
3.2 Developer Productivity................................................................................................................................. 8
3.3 Business Intelligence................................................................................................................................... 8
4.0 Data types...........................................................................................................................................................................9
5.0 Database............................................................................................................................................................................11
5.1 SQL Server System Databases................................................................................................................. 11
6.0 Tables................................................................................................................................................................................13
6.1 Keys and Constraints................................................................................................................................. 13
6.2 Relationship between the tables................................................................................................................ 14
6.2.1 Types of Relationships..........................................................................................................14
6.3 Table Creation........................................................................................................................................... 16
7.0 Clauses..............................................................................................................................................................................18
7.1 Select......................................................................................................................................................... 18
7.2 Distinct....................................................................................................................................................... 18
7.3 Into............................................................................................................................................................. 18
7.4 Where........................................................................................................................................................ 18
7.5 Group By.................................................................................................................................................... 18
7.6 Having........................................................................................................................................................ 19
7.7 Order By.................................................................................................................................................... 19
8.0 Joins..................................................................................................................................................................................20
8.1 Types of joins............................................................................................................................................. 20
9.0 Views.................................................................................................................................................................................24
10.0 Triggers...........................................................................................................................................................................26
Last Edited:
Last Edited:
It is prepared on the basis of conceptual knowledge rather than theoretical knowledge. It will provide a
clear view of handling, creating and maintaining databases in the applications.
Microsoft SQL Server is a full-featured relational database management system (RDBMS) that offers a
variety of administrative tools to ease the burdens of database development, maintenance and
administration. In this article, some of the important topics have been covered about SQL Server like
features and Execution Plan.
And it provides plenty of tables and diagrams for visual interpretation and example coding have been
zipped and attached for reference at the end of this document.
2.0 SQL
Structured Query Language (SQL) is a standard language for accessing and manipulating databases.
The SQL language is sub-divided into several language elements, including
Clauses which are in some cases optional, constituent components of statements and queries.
Expressions which can produce either scalar values or tables consisting of columns
and rows of data.
Predicates which specify conditions that can be evaluated to SQL three-valued logic (3VL)
Boolean truth values and which are used to limit the effects of statements and queries, or to
change program flow.
Queries which retrieve data based on specific criteria.
Statements which may have a persistent effect on schemas and data, or which may control
transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not required on
every platform, it is defined as a standard part of the SQL grammar.
SQL is an interactive query language. Users type SQL commands into an interactive SQL
program to retrieve data and display it on the screen, providing a convenient, easy-to-use tool
for ad hoc database queries.
SQL is a database programming language. Programmers embed SQL commands into their
application programs to access the data in a database. Both user written programs and
Last Edited:
3.0 Features
Various features of SQL Server 2005 are enterprise data management, developer productivity and
business intelligence which are discussed as follows.
High Availability
Failover clustering and database mirroring technology in SQL Server 2005 enables enterprises
to deliver highly reliable, available applications to employees, customers, and partners.
Management Tools
SQL Server 2005 introduces an integrated suite of management tools and management
application programming interfaces (APIs) to provide ease of use, manageability, and support
for operating large-scale SQL Server deployments.
Security Enhancements
SQL Server 2005 has been designed to help provide the highest level of security for enterprise
data through features such as database encryption, more secure default settings, password
policy enforcement, granular permissions control, and an enhanced security model.
Scalability
Scalability advancements in SQL Server 2005 include table partitioning, replication
enhancements, and 64-bit support.
Last Edited:
Analysis Services
Analysis Services provides a unified and integrated view of all your business data as the
foundation for all of your traditional reporting, OLAP analysis, Key Performance Indicator (KPI)
scorecards and data mining.
Integration Services
SQL Server Integration Services (SSIS) is a next generation data integration platform that can
integrate data from any source. SSIS provides a scalable and extensible platform that
empowers development teams to build, manage, and deploy integration solutions to meet
unique integration needs.
Reporting Services
SQL Server Reporting Services is a comprehensive, server-based reporting solution designed
to help you author, manage, and deliver both paper-based and interactive Web-based reports.
Data Mining
SQL Server 2005 Analysis Services (SSAS) provides tools for data mining with which you can
identify rules and patterns in your data, so that you can determine why things happen and
predict what will happen in the future giving you powerful insight that will help your company
make better business decisions.
Last Edited:
We also learnt the importance of choosing correct data type for storing a particular type of data.
The following are various data types available in the SQL server 2005.
NUMBER OF
DATA TYPE COMMENTS
BYTES
tinyint 1
smallint 2
Integer
int 4
bigint 8
decimal[p[,s]] 5-17
Exact numeric
numeric[p[,s]] 5-17
Appropriate float[(n)[ 8
numeric real 4
smallmoney 4
Monetary
money 8
smalldatetime 4
Date and time
datetime 8
Last Edited:
binary[(n)] 0-8000
varbinary[(n)] 0-8000
Binary
16 bytes pointer or in row, ,preferred over
varbinary(max) 0-2 GB
image data type
cursor 0-8
table -
sql_variant 0-8016
Last Edited:
Master Core system database to manage The first database in the SQL
the SQL Server instance. In SQL Server Server startup process
2005, the Master database is the logical In SQL Server 2005, needs to
repository for the system objects residing reside in the same directory as the
in the sys schema. In SQL Server 2000 Resource database
and previous editions of SQL Server, the
Master database physically stored all of
the system objects.
Resource The Resource database is Introduced in SQL Server 2005
responsible for physically storing all of to help manage the upgrade and
the SQL Server 2005 system objects. rollback of system objects.
This database has been created to
improve the upgrade and rollback of SQL Prior to SQL Server 2005 the
Server system objects with the ability to system related data was stored in
overwrite only this database. the master database.
Model Template database for all user User defined tables, stored
defined databases procedures, user defined data
types, etc can be created in the
Model database and will exist in all
future user defined databases.
Last Edited:
A key is a way of identifying a record in a database table. We can use keys to build
relationships between tables because a key refers to a whole record.
A key can be defined on a single column if that’s enough to identify the record, or it can be
defined on more than one column if not. The sections that follow introduce the three kinds of keys you
can use in a database.
Last Edited:
A relationship in a SQL Server database is a logical link between two tables. It is impossible to
have a physical link. When defining a logical relationship, we’re informing SQL Server that we’ll be
linking a primary key from the master table to a foreign key in another table. So already there is a need
for two keys: one on each table.
One-To-One Relationships
A one-to-one relationship is created if both of the related columns are primary keys or have
unique constraints.
Example:
To illustrate the one-to-one relationship, imagine that in our example bank database there is a
table that holds PIN numbers for ATM cards, keeping them completely separate from the
remainder of the customer records (see Figure 3-1). In most cases, there would be one PIN
number record for each customer record, but there may be exceptions—for instance, a high
interest deposit account may not have a card, and therefore there would be no associated PIN
number record.
Last Edited:
One-To-Many Relationships
A one-to-many relationship is the most common type of relationship. In this type of relationship,
a row in table A can have many matching rows in table B, but a row in table B can have only one
matching row in table A.
Example:
Using our banking example, say we have a customer master record along with any number of
associated transaction records. The number of these transaction records could range from
none, which corresponds to when a customer is new to the bank and hasn’t made a deposit or
performed a transaction, to one or more, which corresponds to when there has been an initial
deposit in an account, and then further deposits or withdrawal transactions after that.
The following example shows the table creation and the relationship diagram for student mark
list.
Queries:
create table CourseDetail ( CourseID INTEGER PRIMARY KEY NOT NULL,
CourseName VARCHAR(20))
7.0 Clauses
7.1 Select
The SELECT statement is used to select data from a database. The result is stored in a result
table, called the result-set.
Syntax:
SELECT column_name(s)
FROM table_name
Last Edited:
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can
be used to return only distinct (different) values.
Syntax:
SELECT DISTINCT column_name(s)
FROM table_name
7.3 Into
The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.
Syntax:
SELECT * INTO new_table_name [IN externaldatabase]
FROM old_tablename
7.4 Where
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
7.5 Group By
SQL- Group By clause, deals with aggregate functions on the column names of a table. It
consolidates and calculates column values into a single record value. GROUP BY requires a list of table
columns on which to run the calculations. We can also use the GROUP BY statement on more than one
column. It will return unique values. Hence it inherits the behavior of “SELECT DISTINCT “command.
Syntax:
SELECT
column_name, aggregate_function (column_name)
FROM table_name
WHERE condition
GROUP BY column_name
Last Edited:
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Syntax:
SELECT
column_name,
Aggregate function (column_name)
FROM
table_name
WHERE
column_name operator value
GROUP BY
column_name
HAVING
aggregate_function (column_name) operator value
7.7 Order By
The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY
keyword sorts the records in ascending order by default. If you want to sort the records in a descending
order, you can use the DESC keyword.
Syntax:
SELECT
column_name(s)
FROM
table_name
ORDER BY
column_name(s) ASC|DESC
8.0 Joins
SQL joins are used to retrieve data from two or more tables, based on a relationship between certain
columns in the tables.
A. INNER JOIN
B. LEFT OUTER JOIN
C. RIGHT OUTER JOIN
Last Edited:
A. INNER JOIN: Return rows when there is at least one match in both tables
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
JOIN CourseDetail c
ON
S.CourseID = C.CourseID
Last Edited:
B. LEFT OUTER JOIN: Return all rows from the left table, even if there are no matches in the right table
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
left JOIN
CourseDetail c
ON
S.CourseID = C.CourseID
Output table:
Last Edited:
Output table:
D. FULL JOIN: Return rows when there is a match in one of the tables
Last Edited:
Output table:
E. CROSS JOIN: Return the Cartesian product of the rows of two tables
Example:
SELECT
S.StudentName,
C.CourseName
FROM
StudentDetail S
Cross Join
CourseDetail c
Last Edited:
9.0 Views
SQL VIEWS are data objects, and like SQL Tables, they can be queried, updated, and
dropped.
Views are virtual tables containing columns and rows but the data is generated dynamically
from SQL tables and hence physically it doesn’t exist inside the view itself.
It always gives updated data.
A view serves as a security mechanism. This ensures that users are able to retrieve and modify
only the data seen by them. Users cannot see or access the remaining data in the underlying
tables.
Complex queries can be stored in the form as a view, and data from the view can be extracted
using simple queries.
Database contains only the definition of the view table, without its definition.
Database creates ABSTRACTION using views.
Nested views reduce the complexity of normalization.
Views are dynamic SQL query .Changes in the base table will be reflected in the subsequent
invocation of views.
Views can also be removed by using the DROP VIEW command.
Syntax:
(Or)
Sample code:
Views ensure the security of data by restricting access to the following data:
Specific rows of the tables.
Specific columns of the tables.
Specific rows and columns of the tables.
Rows fetched by using joins.
Statistical summary of data in a given tables.
Subsets of another view or a subset of views and tables.
Types of views:
Read-only
We cannot update the read-only views.
Updatable-view
We can make changes in the views like update , delete, insert etc;
10.0 Triggers
A trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database
There are typically three triggering events that cause data triggers to 'fire':
a) INSERT event (as a new record is being inserted into the database).
b) UPDATE event (as a record is being changed).
Last Edited:
Trigger Syntax
CREATE TRIGGER
trigger_name
ON
{table | view }
{{
{ FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ] [ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
}]
sql_statement [ ...n ]
}}
11.0 Cursors
Cursors are simply defined as “It’s an iterator over the collection of rows in the recordset”.
Using cursors, the client can get, put, and delete database records. Database programmers
use cursors for processing individual rows returned by the database system for a query.
Syntax:
DECLARE cursor_name CURSOR FOR SELECT ... FROM...
It declares a cursor with a name for the table to be accessed.
OPEN cursor_name
Open statement places the cursor before first row in the resultset.
CLOSE cursor_name
Last Edited:
Scrollable
Syntax:
DECLARE
cursor_name sensitivity SCROLL CURSOR
FOR
SELECT...
FROM
FETCH [NEXT | PRIOR | FIRST | LAST] FROM cursor_name|
FETCH ABSOLUTE n FROM cursor_name|
FETCH RELATIVE n FROM cursor_name
Non-Scrollable (forward-only)
Here, we can FETCH each row at most once and the cursor automatically moves
to the immediately following row.
With-Hold cursors
Cursors will be closed automatically once the transaction is over i.e. when a
commit or rollback occurs. This property of a cursor can be changed by declared
it using the WITH HOLD clause.
Holdable cursor is open for commit and closed for rollback
Last Edited:
It provides the ability to manipulate the presentation of the data without actually updating or
changing the base table.
It masks the actual values present in a table to end users without altering the data in base
table. And provides the necessary information needed by the particular end users.
Syntax:
Select
column_name, ‘new_column_name’=CASE
WHEN (Condition)
THEN
“msg to display / any computation”
ELSE
Some other output
END
Sample code:
Select
Product, ‘Status’=CASE
WHEN
Quantity>0
THEN
“In-stock”
ELSE
“Out-of-stock”
END
From
dbo.inventory
Explanation:
Last Edited:
Temporary tables are used to store and process intermediate results by using the same
selection, update, and join capabilities of SQL Server tables. However, using temporary
tables can adversely affect system performance
There are two types of temporary tables: global and local.
Temp tables can be created locally (#TableName) or globally (##TableName)
SQL server appends a unique number at the end ‘temporary table’ object to identify it ,
in order to avoid confusion when two users create the same temporary table name.
It works pretty quickly. It is cached in memory.
We should drop the temporary table explicitly.
We should recompile the stored procedures again and again, if we use temporary
tables inside it. It avoids recompilations, always we need to create temporary table and
create indexed for that.
Temp tables allow for multiple indexes to be created
Temp tables can be used throughout multiple batches.
Temp tables can be used to hold the output of a stored procedure
Syntax:
CREATE TABLE
#table_name [column_name [n] datatype...]
INSERT INTO
#tablevariable_name
SELECT * FROM table_name [where (condition)]
(SQL query statements: update or delete, drop)
Sample Code:
CREATE TABLE
#Yaks
(
YakID int,
YakName char (30)
)
INSERT INTO
#TibetanYaks (YakID, YakName)
SELECT
Last Edited:
Syntax:
Sample code:
DECLARE @TibetanYaks TABLE
(YakID int,
YakName char (30)
)
INSERT INTO
@TibetanYaks (YakID, YakName)
SELECT
YakID, YakName
FROM
dbo.Yaks
WHERE
YakType = 'Tibetan'
Last Edited:
Temporary tables are stored in tempdb Table variables are stored in memory with a
database. table like outlook.
Access time is lesser when compared to Since it is partially stored in memory, the access
table variable. time for a table variable can be faster than the
time it takes to access a temporary table.
For stored procedures, temp table is the
best choice. For small resultsets, table variable is the best
choice.
It’s good to drop explicitly.
No need to drop explicitly.
Since it cannot be passed as parameter from one stored procedure to another, there
temporary tables are used.
We cannot create non- clustered index.
SQL Server does not maintain statistics on table variable.
Table variable cannot be altered.
It won’t participate in transaction rollbacks.
It can’t use dynamic SQL, unless it is declared dynamically.
While table sharing, nested stored procedures table variables cannot be used.
It cannot be used for large resultsets, while needs indexes for query optimization.
Last Edited:
Syntax:
Sample Code:
SELECT
Product, Quantity
FROM
Inventory
WHERE
Warehouse = 'FL'
Where the query has to be compiled and executed every time and the warehouse
manager should have knowledge about the sql queries and appropriate permissions to
access the table information.
Where as in SP, the procedure is precompiled. Hence it can be executed easily by only
specifying the location name.
Precompiled execution.
Reduced client/server traffic.
Efficient reuse of code and programming abstraction.
Enhanced security controls.
16.0 Functions
A function is mainly used in the case where it must return a value. A function can be created
and called in SQL Queries. There are some pre-defined functions available in MS SQL server,
they are
We can create our own functions using CREATE FUNCTION statements. The syntax
for creating a function is
Syntax
CREATE FUNCTION
Last Edited:
Split function is a user defined function it accept a string containing a stream of words
separated by “,” and display it as individual rows in a table.
Code
CREATE FUNCTION splitFunction
(@List nvarchar(2000))
RETURNS
@RtnValue table ( Value nvarchar(100))
AS
BEGIN
While (Charindex(',',@List)>0)
Begin
Insert Into @RtnValue (value)
Select
Value = ltrim(rtrim(Substring(@List,1,Charindex(',',@List)-1)))
Set
@List = Substring(@List,Charindex(',',@List)+len(','),len(@List))
End
Insert Into @RtnValue (Value)
Select Value = ltrim(rtrim(@List))
Return
END
Last Edited:
Read Lock - The locked data is reserved for read by the current session. Other
sessions can read the locked data. But they can not write (update) the locked data. A
read lock is also called a shared lock.
Write Lock - The locked data is reserved for write by the current session. Other
sessions can not read and write the locked data. A write lock is also called an exclusive
lock.
Table Lock - The lock is set at the table level. All rows in the locked table are locked.
Row Lock - The lock is set at the row level. Some rows of a table are locked. But other
rows are not locked.
Column Lock - The lock is set at the column level. Some columns of a row are locked.
But other columns are not locked.
18.0 Index
Index is mainly used for speed up the storage or retrieval time for a data from or to a particular row of a
table in a database.
18.1 Types
Bitmap index
A bitmap index is a special kind of index that stores the bulk of its data as bit arrays (bitmaps)
and answers most queries by performing bitwise logical operations on these bitmaps. The most
commonly used index, such as B+trees, are most efficient if the values it indexes do not repeat or
repeat a smaller number of times. In contrast, the bitmap index is designed for cases where the values
Last Edited:
Dense index
A dense index in databases is a file with pairs of keys and pointers for every record in the data
file. Every key in this file is associated with a particular pointer to a record in the sorted data file. In
clustered indexes with duplicate keys, the dense index points to the first record with that key.
Sparse index
A sparse index in databases is a file with pairs of keys and pointers for every block in the data
file. Every key in this file is associated with a particular pointer to the block in the sorted data file. In
clustered indexes with duplicate keys, the sparse index points to the lowest search key in each block.
Reverse index
A reverse key index reverses the key value before entering it in the index. E.g., the value 24538
becomes 83542 in the index. Reversing the key value is particularly useful for indexing data such as
sequence numbers, where new key values monotonically increase.
A. Clustered index
Clustered indexes sort and store the data rows in the table or view based on their key values.
There can be only one clustered index per table because the rows themselves can be sorted in only
one order.
Advantages
It increases the speed while we are trying to retrieve the data.
Limitations
Insertion and deletion will become a slow process as it uses physical index.
B. Non clustered index
It provides the logical index contains the non clustered index key values and each key value entry has a
pointer to the data row that contains the key value.
We can have more than one non clustered index for a single table.
C. Unique Indexes
A unique index ensures that the indexed column contains no duplicate values. In the case of
multicolumn unique indexes, the index ensures that each combination of values in the indexed column
Last Edited:
Both clustered and nonclustered indexes can be unique. Therefore, provided that the data in the
column is unique, you can create both a unique clustered index and multiple-unique nonclustered
indexes on the same table.
Indexes can be implemented using a variety of data structures. Popular indexes include
balanced trees, B+ trees and hashes.
In Microsoft SQL Server, the leaf node of the clustered index corresponds to the actual data,
not simply a pointer to data that resides elsewhere, as is the case with a non-clustered index. Each
relation can have a single clustered index and many unclustered indexes.
Consider creating index on column(s) frequently used in the WHERE, ORDER BY, and
GROUP BY clauses.
Keep your indexes as narrow as possible.
Drop indexes that are not used.
Try to create indexes on columns that have integer values rather than
character values.
Limit the number of indexes, if your application updates data very
frequently.
Check that index you tried to create does not already exist.
Create clustered index instead of nonclustered to increase performance of
the queries that return a range of values and for the queries that contain
the GROUP BY or ORDER BY clauses and return the sort results.
Create nonclustered indexes to increase performance of the queries that
return few rows and where the index has good selectivity.
Create clustered index on column(s) that is not updated very frequently.
Create clustered index based on a single column that is as narrow as
possibly.
Avoid creating a clustered index based on an incrementing key.
Create a clustered index for each table.
Don't create index on column(s) which values has low selectivity.
If you create a composite (multi-column) index, try to order the columns in
the key as to enhance selectivity, with the most selective columns to the
leftmost of the key.
Last Edited:
Distinct aggregation (e.g. select count(distinct key) …) is a SQL language feature that
results in some very slow queries.
Try to restrict the queries result set by using the WHERE clause. This can reduce
network traffic and boost the overall performance of the query.
Try to restrict the queries result set by returning only the particular columns from the
table, not all table's columns.
Use views and stored procedures instead of heavy-duty queries. This can be used to
facilitate permission management also, because you can restrict user access to
table columns they should not see.
Try to avoid using SQL Server cursors, whenever possible. It can result in performance
degradation when compared to select statement.
If you need to return the total table's row count, you can use alternative way instead of
SELECT COUNT (*) statement.
You can use sysindexes system table, in this case. There is ROWS column in the
sysindexes table. This column contains the total row count for each table in your
database. So, you can use the following select statement
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid
< 2 So, you can improve the speed of such queries in several times.
Last Edited:
An execution plan is the result of the query optimizer's attempt to calculate the most
efficient way to implement the request represented by the T-SQL query you submitted.
When a query is submitted, number of processes on the server goes to work on that
query. The purpose of the processes is to manage the system to store and retrieve
data in a timely manner and maintaining the integrity of data.
The processes around T-SQL are broken down into two stages.
In the relational engine the query is parsed and then processed by the Query
Optimizer, which generates an execution plan.
The plan is sent (in a binary format) to the storage engine, which it then uses to
retrieve or update the underlying data. The storage engine is where processes such
as locking, index maintenance and transactions occur
SQL Server Query Optimizer uses the cost to make the decision on selecting the most
efficient execution plan. When any query is executed, the SQL Server Query Optimizer
prepares several alternative execution plans to execute the query and selects the
lowest cost plan.
Two kinds of plan will be available: Trivial Plan and Non-trivial plan
Graphical Plan
Textual Plan
Last Edited:
Execution plans are there to assist in writing efficient T-SQL code, troubleshooting existing T-
SQL behavior or monitoring and reporting on your systems.
When you query a table that doesn't have indexes, or if the optimizer decides not to
use an existing index or indexes, the system performs a table scan.
Table Scan is a logical and physical operator.
The Table Scan operator retrieves all rows from the table specified in the
Argument column of the query execution plan. If a WHERE :() predicates
appears in the Argument column, only those rows that satisfy the predicate are
returned.
When SQL Server does a scan it loads the object which it wants to read from disk into memory,
then reads through that object from top to bottom looking for the records that it needs.
The SQL Server optimizer's uses indexes to improve query execution time. Index access is an
access method in which SQL Server uses an existing index to read and write data pages. Because
index access significantly reduces the number of I/O read operations, it often outperforms a table scan.
A clustered index physically sorts the table's contents in the order of the specified index
columns.
There can be only one clustered index for a table.
SQL Server navigates from the b-tree root node to the leaf nodes to retrieve data.
A clustered index property has leaf nodes that contain data pages.
The Clustered Index Scan logical and physical operator scans the clustered index
specified in the Argument column. When an optional WHERE :() predicates is present,
only those rows that satisfy the predicate are returned.
If the Argument column contains the ORDERED clause, the query processor has
requested that the rows' output be returned in the order in which the clustered index
has sorted them. If the ORDERED clause is not present, the storage engine will scan
the index in the optimal way (not guaranteeing the output to be sorted).
Last Edited:
A nonclustered index has the same index structure as a clustered index, but with two
important differences. Nonclustered indexes don't change the row's physical order in
the table, and the nonclustered index's leaf level consists of an index key plus a
bookmark.
A bookmark shows where to find the row that corresponds to the nonclustered index
key.
We can create 249 non-clustered indexes on a table.
When SQL Server does a seek it knows where in the index that the data is going to be,
so it loads up the index from disk, goes directly to the part of the index that it needs and reads
to where the data that it needs ends. This is obviously a must more efficient operation than a
scan, as SQL already knows where the data is that it is looking for.
The Clustered Index Seek logical and physical operator uses the seeking ability of
indexes to retrieve rows from a clustered index.
The Argument column contains the name of the clustered index being used and the
SEEK :() predicate. The storage engine uses the index to process only those rows that
satisfy this SEEK :() predicates. It optionally can include a WHERE :() predicate, which
the storage engine evaluates against all rows satisfying the SEEK :() predicate (it does
not use indexes to do this).
If the Argument column contains the ORDERED clause, the query processor has
determined that the rows must be returned in the order in which the clustered index has
sorted them. If the ORDERED clause is not present, the storage engine searches the
index in the optimal way (not guaranteeing the output to be sorted). Allowing the output
to retain its ordering can be less efficient than producing nonsorted output.
Read a graphical execution plan from right to left and top to bottom.
This arrow represents the data being passed between the operators.
The thickness of the arrow reflects the amount of data being passed.
The percentage below each icon represents the cost to the operator. That cost returned
from the optimizer, is the estimated execution time for that operation.
Last Edited:
Estimated Subtree Cost – tells us the accumulated optimizer cost assigned to this
step and all previous steps, but remember to read from right to left. This number is
meaningless in the real world, but is a mathematical evaluation used by the query
optimizer to determine the cost of the operator in question; it represents the amount of
time that the optimizer thinks this operator will take.
The I/O Cost and CPU cost are not actual operators, but rather the cost numbers
assigned by the Query Optimizer during its calculations. These numbers are useful
when determining whether most of the cost is I/O-based or if we're putting a load on the
CPU.
To be able to access data from a database, a user must pass through two stages of
authentication, one at the SQL Server level and the other at the database level. These two stages are
implemented using Logins names and User accounts respectively. A valid login is required to connect
to SQL Server and a valid user account is required to access a database.
During a new connection request, SQL Server verifies the login name supplied, to make sure,
that login is authorized to access SQL Server. This verification is called Authentication. SQL Server
supports two authentication modes:
Mixed mode: Mixed mode allows users to connect using Windows authentication or
SQL Server authentication. Your DBA must first create valid SQL Server login accounts
Last Edited:
A valid login name is required to connect to an SQL Server instance. A login could be:
A Windows NT/2000 login that has been granted access to SQL Server
Syntax
Sources:
WINDOWS [WITH windows_options [...]]
CERTIFICATE certname
ASYMMETRIC KEY asym_key
option_list:
SID = sid
DEFAULT_DATABASE = database
DEFAULT_LANGUAGE = language
CHECK_EXPIRATION = {ON | OFF}
CHECK_POLICY = {ON | OFF}
CREDENTIAL = credential
windows_options:
DEFAULT_DATABASE = database
DEFAULT_LANGUAGE = language
Key:
Login
Login SQL Server / certificate-mapped / asymmetric key-mapped / [Windows].
WINDOWS
Map to a Windows login.
Certname
Last Edited:
Examples
A valid user account within a database is required to access that database. User
accounts are specific to a database. All permissions and ownership of objects in the database
are controlled by the user account. SQL Server logins are associated with these user accounts.
A login can have associated users in different databases, but only one user per database.
Syntax:
Last Edited:
Options:
Examples
Create a user with full rights to create objects and save data:
You have to create a user first before you can GRANT permissions, roles or assign a default
ROLE.
21.3 Roles
Last Edited:
These are server-wide roles. Logins can be added to these roles to gain the associated
administrative permissions of the role. Fixed server roles cannot be altered and new
server roles cannot be created.
Each database has a set of fixed database roles, to which database users can be
added. These fixed database roles are unique within the database. While the
permissions of fixed database roles cannot be altered, new database roles can be
created.
Application roles
After creating and assigning the required permissions to an application role, the client
application needs to activate this role at run-time to get the permissions associated with
that application role. Application roles simplify the job of DBAs, as they don't have to
worry about managing permissions at individual user level. All they need to do is to
create an application role and assign permissions to it.
Data Definition Language (DDL) statements are used to define the database structure or schema.
Statement Syntax Purpose
CREATE CREATE [TEMPORARY] To create table in the
TABLE [table name] ( [column definitions] ) [table database
parameters].
ALTER ALTER TABLE [table name] ADD [column Alters the structure of the
definitions] database
INSERT INSERT INTO [table name] ([column names]) Insert data into a table
VALUES([column values]);
UPDATE UPDATE [table name] Updates existing data
SET ([column values]) within a table.
WHERE [conditions] It is mainly used for
incrementing or
decrementing the column
values.
DELETE DELETE from [table name] Deletes all records from a
WHERE [conditions] table, the space for the
records remain
Data Control Language (DCL) statements deal with the user privileges.
Statement Syntax Purpose
GRANT GRANT SELECT, UPDATE Gives user's access
ON [table name] privileges to database
TO [user names]
REVOKE REVOKE SELECT, UPDATE Withdraw access privileges
Last Edited:
The above figure represents how the change occurred in a transaction is committed or discarded from
the target table.
Last Edited:
23.0 Conclusion
Thus the document provides detailed view about SQL Server 2005 and it will be useful for the
future trainees of Photon Infotech. And the sample coding are zipped and attached here. And reference
links are specified.
23.1 Attachments
http://www.tizag.com/sqlTutorial/sqlsyntax.php
http://social.msdn.microsoft.com/Search/en-IN?query=sql&ac=8
http://weblogs.sqlteam.com/mladenp/articles/9502.aspx
Last Edited:
http://vyaskn.tripod.com/sql_server_security_best_practices.htm
http://www.mssqlcity.com/Tips/tipTSQL.htm
http://www.codeproject.com/KB/database/sqldodont.aspx
http://www.erpgenie.com/sap-technical/abap/sql-performance-qdos-and-dontsq
Last Edited: