Sie sind auf Seite 1von 31

SQL SERVER 6.

5
Chapter-5/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Implementation of Indexes and views
SCOPE
Types of Indexes
Clustered
Nonclustered
Implementing Indexes
Creating and dropping Indexes
Performance analysis
Table Scan Vs Index Search
SHOWPLAN
Optimizer Hints
UPDATE STATISTICS
DBCC commands
Views
Advantages
Creating and dropping views
Modifying data through views
SQL SERVER 6.5
Chapter-5/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
TYPES OF INDEXES
Indexes
Indexes are SQL Servers internal method of organizing the data in a table in such a way,
that the data can be retrieved optimally.
An index is a collection of data values of a column in a table and their corresponding
pointers to the rows where those values are physically represented in that table..
DIAGRAM
MEM_NUM LAST_NAME FIRST_NAME AGE SEX
M003 BARR PETER 13 M
M001 ALLEN SAM 14 M
M002 M MARY 13 F
M005 ALLEN JOHN 14 M
M004 SOLLY ALLEN 14 M
. . . . .
. . . . .
. . . . .
M001
.
.
M004
M005
.
.
.
MEMBER
INDEX ON
MEM_NUM
SQL SERVER 6.5
Chapter-5/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Creation of Indexes
Indexes are another kind of objects, similar to tables, that are stored in the databases.
Indexes require pages of data to store their rows, like tables.
When an index is created, the database
(a) Scans the table.
(b) Gathers the values of the column that is being indexed.
(c) Writes a list of those values and their corresponding pointers to the rows
where those values physically exist, on to the index page.
How SQL Server uses the index
SQL Server uses an index as the index of the book is used.
It searches the index to find a particular value and then follows the pointer to locate the
row containing the value.
EXAMPLE
Note : Refer to the diagram on page 2 of the session.
SQL Server locates the record containing M004 in the MEMBER table by searching the index for the data
value M004 and following the pointer.
Types of indexes
There are two types of indexes
(a) Clustered indexes
(b) Nonclustered indexes
Clustered indexes
The file being indexed is stored in data pages with several records in each page.
SQL SERVER 6.5
Chapter-5/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


DIAGRAM




Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

14 13 12 15 18 25

11 10 17 20 23 26

16 19 22 21 27 24








After the creation of a clustered index records are in the order of the index.


DIAGRAM



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27







Index contains one entry per page, giving the topmost value of the indexed field
occurring in that page and a pointer to start of the page.






data pages
data pages
SQL SERVER 6.5
Chapter-5/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

DIAGRAM

Page 100 Page 101

Page Key Page Key

5 10 8 19

6 13 9 22

7 16 10 25



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27








The sequence of data pages is represented by the sequence of entries in the index.

If the index gets large, an index to an index is created. ( Represented by the Root
level and the non leaf level in this case)
data pages
Index pages
SQL SERVER 6.5
Chapter-5/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


DIAGRAM

Page 103

Page Key

102 10


Page 102

Page Key

100 10

101 19
Page 100 Page 101

Page Key Page Key

5 10 8 19

6 13 9 22

7 16 10 25



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27




In clustered index, the actual data pages represent the leaf level of the index i.e.
actual data pages are a part of the index.

Thus, the physical order of the rows is same as the indexed order. Data pages are
physically ordered on a hard disk using the logical order of the clustered index.

data pages
Leaf level
Root level
Non
leaf
level
SQL SERVER 6.5
Chapter-5/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Advantages of clustered index


Removes the need for sequential scanning of the indexed file.
UPDATE and DELETE operations are accelerated since these operations require
much reading.


Consider using a clustered index for


Queries that return a range of values using operators such as BETWEEN , >, <=, <,
<=.

EXAMPLE
SELECT * FROM emp

WHERE hire_date BETWEEN 5/1/95 AND 6/1/95


Queries that return large result sets.


Clustered index guidelines

There can be only one clustered index per table.
A clustered index should always be the first index to be created.
If CLUSTERED is not specified, a nonclustered index would be created, which is the
default.
Requires over twice the space to build (1.21 * table size) ; space to store the original
sequence until the index is built, and the space to create the clustered index.
Space required to create an index comes from the tables database.


SQL SERVER 6.5
Chapter-5/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Nonclustered indexes


DIAGRAM



14 13 21 19 20 12

11 10 17 22 23 26

25 27 16 24




10 14 20 24

11 16 21 25


12 17 22 26

13 19 23 27







Physical ordering of the rows is not same as their indexed order.

Nonclustered index specifies the logical ordering of the table.

Leaf level pages of a non-clustered index are index pages i.e. contains indexed
values and pointers to rows on data pages and are not the actual data pages of the
table.

These actual data pages are unordered.

Conceptually, there is a level of indirection between the index structure and the data
itself.

data pages
leaf level of index
SQL SERVER 6.5
Chapter-5/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Nonclustered Index guidelines

Number of nonclustered index permissible on one table is 249.

Clustered indexes should be created before the nonclustered indexes, because
clustered indexes change the physical order of the rows, and nonclustered indexed
would have to be rebuilt.


Consider using a nonclustered index for


Queries that return a small or single row result sets.


EXAMPLE

SELECT * FROM member

WHERE mem_num = M001



Columns that contain a large number of unique values. For example mem_num
column of member table.


Clustered indexes Vs Nonclustered indexes



Clustered Index Non clustered index

Indexed order of key values is same as the
physical order.
Indexed order of key value is not same as
physical order.
Leaf level pages of a clustered index
contain actual data pages.
Leaf level pages of a non-clustered index
are index pages.
A table can contain one clustered index. A table can have 249 nonclustered indexes.


SQL SERVER 6.5
Chapter-5/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


IMPLEMENTING INDEXES



Reasons for using Indexes


Enforces the uniqueness of rows.

Speeds the execution of SQL statements with search conditions, that refer to the
indexed column.

Reduces the number of I/Os required by the SQL Server query optimizer, to reach
any given piece of data in a table.

In certain cases, front-end application might require an index.



Indexing guidelines


When creating indexes on columns, consider the following:

Using indexes is appropriate for columns that are used frequently in search
conditions.

Indexes should be made for the tables for which queries are more frequent than
inserts and updates.

Primary keys should be indexed uniquely by creating a clustered or nonclustered
index.

Indexing on foreign keys help process joins more efficiently.

A column that is often accessed in sorted order should be given a clustered index.

Columns frequently used in joins should always be indexed.

The columns frequently used in WHERE clause and the columns which are searched
for range of value should be indexed.



SQL SERVER 6.5
Chapter-5/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Good index candidates


Candidates Notes

Foreign Keys Prime candidates for indexes. Helps the lookup times
immensely.
Large result set queries For the queries that will be returning a large dataset result,
indexing is preferred.
Order by and group support Columns that are referenced in these clauses will benefit
greatly from an index.



Optimizing indexes based on usage patterns



In a system where lots of inserts and updations are expected, the indexes on the table
must be limited, because when records are inserted or updated, the indexes must be
updated as well.


On the other hand, in a query-centric system where few inserts are happening, all the
indexes needed to improve the query performance can be implemented. Limiting factor in
this case becomes the disk space.



Reasons for not indexing every column


Building an index takes time.

Disk space is required for each index in addition to the space used by the table.

When updating, inserting, or deleting rows the index is also dynamically maintained
to reflect any changes.

SQL SERVER 6.5
Chapter-5/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


CREATING INDEXES


SQL Server automatically creates an index for the PRIMARY KEY and UNIQUE
constraints ( if defined with CREATE TABLE statement.)

The other indexes have to be created explicitly using the CREATE INDEX statement.
The statement creates an index on column(s) in a table.


Syntax:


CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name

ON [ [ database.] owner.] table_name ( column_name [, column_name ]...)

[ WITH

[FILLFACTOR = fillfactor ]

[ [,] IGNORE_DUP_KEY ]

[ [,] { SORTED_DATA | SORTED_DATA_REORG}]

[ [,] { IGNORE_DUP_ROW | ALLOW_DUP_ROW }]]



Index rules

Only the owner of the table can CREATE or DROP the index.

Indexes can be created on tables in another database by qualifying the
database.table_name.

Indexes speed data retrieval but can slow data update.

Index can not be created on a view.

Index can not be created on columns defined with bit, text and image datatypes.

The various options for CREATE INDEX are covered in the following sections.

SQL SERVER 6.5
Chapter-5/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

UNIQUE

The option specifies to create a unique index in which no two rows are permitted to
have the same index value.

The system checks for the duplicate values when the index is created ( if data already
exists) and checks each time data is added with an INSERT or UPDATE statement.

If the duplicate values are found, statement is canceled (roll backed) irrespective of
the number of rows affected and an error message is returned.

A UNIQUE index can not be created on a column where the key is NULL in more
than one rows, because these are treated as duplicate values for indexing purpose.

EXAMPLE
Assuming a table called applicant is already existing which has a field called appl_id.

CREATE UNIQUE INDEX app_ind

ON applicant ( appl_id)

OUTPUT:

Creates an index called app_ind on the appl_id column of the applicant table that enforces uniqueness.



CLUSTERED

If the option is specified, the index will be created as a clustered index.

EXAMPLE
CREATE UNIQUE CLUSTERED INDEX app_clind

ON applicant (appl_id)





OUTPUT:

Creates an index called appl_clind on the appl_id column of the applicant table that enforces
uniqueness.
The index will physically order the data on the disk because the CLUSTERED is specified.

SQL SERVER 6.5
Chapter-5/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


NONCLUSTERED

Specifies that a nonclustered index is to be created.

This is the default index type.

If no index type is specified, a nonclustered index is created.

EXAMPLE
CREATE NONCLUSTERED INDEX app_nonind

ON applicant (fname)

OUTPUT:

Creates a noclustered index called appl_nonind on the fname column of the applicant table .



FILLFACTOR

When an index page fills up, SQL Server splits the data onto separate data pages to
make room for new rows. Page splitting is costly operation in terms of I/O and should
be thus avoided.

Specifying a FILLFACTOR tells SQL Server how to pack the index data into the
index data pages .

FILLFACTOR tells SQL Server to preserve a percentage of free space on the index
data page for other similar rows which will be inserted in the future and thus avoids
page splitting.

FILLFACTOR improves the performance by minimizing the amount of page splitting
that occurs each time the index page becomes full.
SQL SERVER 6.5
Chapter-5/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Specifying a FILLFACTOR when creating an index on a table without data has no
effect because SQL Server has no way of placing the data in the index correctly.

When using the FILLFACTOR option consider the following guidelines:

(a) Primarily used as an option to fine-tune performance.

(b) A small FILLFACTOR is useful for the table when inserting a lot of data after the
index creation. (except 0)


EXAMPLE

If a table is going to have many more values, a low FILLFACTOR of about 10 can be specified.

SQL Server will preallocate space in the index pages for those values so that it wont need to page split.
Thus, the data is spread over more pages, leaving space for the rows that you plan to add.



(c) A high FILLFACTOR will enforce more frequent page splits because SQL Server
will have no room on the index page to add any additional values. This option is
good for highly concurrent, read-only tables.

(d) User specified FILLFACTOR values can be from 1 through 100.

(e) For read-only databases, a FILLFACTOR of 100 is optimal.

(f) If FILLFACTOR is not specified , SQL Server uses the default FILLFACTOR
value to determine how much to fill an index page. The default value is 0. When
FILLFACTOR is 0 only, only the leaf pages are filled. Space is left in nonleaf pages
for at least one entry.


FILLFACTOR Internal page Leaf page
0%
one free slot
*
100% full
1-99%
one free slot
*
<= FILLFACTOR % FULL
100% 100% full 100% full
*
Two free slots for nonunique clustered indexes.

The FILLFACTOR is not maintained after the index is initially built. However, if index
pages become too full and page splits become a performance problem, indexes can be
dropped and rebuilt to reestablish the desired FILLFACTOR.
SQL SERVER 6.5
Chapter-5/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

CREATE NONCLUSTERED INDEX zip_ind

ON author (zip)

WITH FILLFACTOR = 100


OUTPUT:

FILLFACTOR option is set to 100.
It fills every index page completely .

NOTE : Useful only when it is known that no index values in the table will ever change.



IGNORE_DUP_KEY


Controls what happens when an attempt to enter a duplicate key in a unique clustered
index is made.

Meaningful only when the UPDATE or INSERT statement affects multiple rows.

If the IGNORE_DUP_KEY is specified, and an UPDATE or an INSERT statement
affecting several rows creates duplicate keys, then only the rows causing the
duplicates are ignored, the other rows are added or changed as usual.

No error message is generated for the duplicate value.

A unique index can not be created on a column that already includes duplicate values,
whether or not IGNORE_DUP_KEY is set.

EXAMPLE
CREATE UNIQUE CLUSTERED INDEX item_ind

ON items (item_id)

WITH IGNORE_DUP_KEY

OUTPUT:

Creates a unique clustered index called item_ind on the items table.
If a duplicate key is entered, transaction for that particular record is ignored.



SQL SERVER 6.5
Chapter-5/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

SORTED_DATA

Speeds up the index creation for clustered indexes.

Tells SQL Server, that data to be indexed is already physically sorted in the order of
the index.

SQL Server verifies by checking that each item is greater than the previous item.

If any discrepancy is found, an error is reported and index creation is aborted.

The option reduces the time and space required to create clustered index.

Time is reduced because no time is spent in ordering the data.

Space is reduced because there is no need for the temporary workspace required for
placing the sorted values before creating the index.


SORTED_DATA_REORG


Differs from SORTED_DATA because it physically reorganizes the data.

SORTED_DATA is faster than the SORTED_DATA_REORG because the data is
not copied and nonclustered indexes will not be rebuilt.

Using SORTED_DATA_REORG is a good idea when the table becomes fragmented.
Table fragmentation occurs through the process of data modifications (INSERT,
UPDATE and DELETE statements) made against the table.( Whether or not table is
fragmented, is determined from DBCC statement covered later)

SQL SERVER 6.5
Chapter-5/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


IGNORE_DUP_ROW
This option is for creating a nonunique clustered index.

This has no effect on nonclustered index because SQL Server internally assigns
identifiers to the records being indexed and doesnt have to manage the physical order
of the data according to the clustering.

ALLOW_DUP_ROW

Cant be set on an index thats allowed to IGNORE_DUP_ROW.

If enabled, no errors are returned and no data is affected if multiple duplicate records
are created in a clustered index.

The IGNORE_DUP_KEY, IGNORE_DUP_ROW, and ALLOW_DUP_ROW index
options control what happens when a duplicate row is created with the INSERT or
UPDATE statement.

The following table shows when these options can be used

Index type Options

Clustered IGNORE_DUP_ROW,
ALLOW_DUP_ROW
Unique clustered IGNOR_DUP_KEY
Nonclustered None
Unique nonclustered IGNORE_DUP_KEY


The following table illustrates how ALLOW_DUP_ROW and IGNORE_DUP_ROW
attempts to create a nonunique clustered index on a table that includes duplicate rows and
attempts to enter duplicate rows into a table.


Option set Table has duplicate rows Insert duplicate row

Neither option CREATE INDEX statement fails INSERT statement fails
ALLOW_DUP_ROW Statement is completed Statement is completed
IGNORE_DUP_ROW Index is created but duplicate
rows are deleted; error message is
returned.
All rows accepted except
duplicates; error message
is returned.

SQL SERVER 6.5
Chapter-5/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Displaying information about Indexes

SQL Server has two ways to show information about indexes.

(a) The graphical method via SQL Enterprise Managers Index Manager.
(b) The command-line method via the system stored procedure sp_helpindex.

sp_helpindex

Syntax:

sp_helpindex table_name

table_name is the unqualified table name because if the table is not in the active database,
the required database should be made active before executing the procedure.

sp_helpindex returns the first eight indexes found on a database table. It shows the name
of the index, its description (clustered / nonclustered / unique ) and description about the
keys.


Dropping indexes

When an index is no longer needed, it can be removed from a database and the storage
can be reclaimed.

Syntax:

DROP INDEX [owner.] table_name.index_name
[, [owner.]table_name.index_name...]

EXAMPLE
DROP INDEX member.mem_ind

OUTPUT:

The index called mem_ind of the table member is dropped.



Only the owners of the table can drop the index.

Doesnt apply to indexes created by PRIMARY KEY or UNIQUE constraints.

SQL SERVER 6.5
Chapter-5/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


PERFORMANCE ANALYSIS


Table scans Vs Index search

When executing a query, the optimizer has two choices:

(a) Scan the table.
(b) Use the index.

Optimizer performs the following:

Estimates how much work is involved if it uses the index versus how much work is
involved if it doesnt.

The optimizer then determines which method to use based on the information in the
distribution page.

Distribution pages are a sampling of data values that SQL Server uses to decide if the
index is useful. These provide a ratio of the number of rows for which the selection
clause will qualify to the number of rows in table. They are used to determine whether
it is more efficient to use the index or to scan the table. A distribution page occupies
one full data page.

Distribution pages are created when you run UPDATE STATISTICS command on
data containing indexes or when index is created on already existing data.

Performs a table scan if the table is small, or if it expects to return a large percentage
of rows.

Including the name of the indexed column, in the WHERE clause of SELECT
statement, improves the chance that the optimizer will use the index.


SHOWPLAN

Displays detailed information on the final access method that the optimizer chooses
for the query.
The information can be displayed by executing the SET SHOWPLAN ON statement.
Shows each step that optimizer uses in joining tables and which indexes, if any, to
choose to be the least costly method of accessing the data.
Useful to determine if the indexes that have been defined on a table are actually being
used by the optimizer.

SQL SERVER 6.5
Chapter-5/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Optimizer hints

If SQL Server fails to pick an index that should provide better performance and it
chooses some other index, then the use of the index providing the better performance can
be forced by specifying it in the FROM clause.

In most cases, optimizer should be allowed to pick the best optimization method, because
as data changes over time the index specified in the select statement may no longer be
efficient.

The following is an option that can be an optimizer hint:

SELECT ....

FROM table_name (INDEX = index_name | index_id) ...

This specifies the index name or ID to use for that table .

An index_id of 0 forces a table scan. An index_id of 1 forces the use of clustered index
(if exists). The other values of n are determined by the number of indexes on the table.

EXAMPLE
Example 1

SELECT last_name, first_name

FROM member ( INDEX = mem_ind)

WHERE last_name = SOLLY


OUTPUT:
The optimizer is used to force the use of the nonclustered index to retrieve rows from a table.


Example 2

SELECT last_name, first_name , hire_date

FROM emp ( INDEX = 0 )

WHERE hire_date > = 10/10/1996

OUTPUT:

The optimizer is forced for the table scan.

SQL SERVER 6.5
Chapter-5/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.



UPDATE STATISTICS
SQL Server keeps statistics about the distribution of key values for each index in the
distribution page.
This information is used to make decisions about which indexes to use in query
processing.
This requires to issue an UPDATE STATISTICS statement periodically - especially
after extensive changes to a table.
This is because a distribution page contains static information and the UPDATE
STATISTICS statement is required to update the information in the distribution page
based on the current data in a table.

Syntax:

UPDATE STATISTICS [[ database.] owner.] table_name [index_name]

UPDATE STATISTICS guidelines

Runs automatically when an index is created or recreated on a table that already
contains data.
UPDATE_STATISTICS creates one page of distribution statistics per index. This
information is used by the optimizer in deciding whether or not to use the index in
processing a query.
Whenever the distribution of data changes, execute UPDATE STATISTICS to keep
the information current.

EXAMPLE

Example 1

UPDATE STATISTICS loan

OUTPUT:

Will update the statistics for all indexes on the loan table .


Example 2

UPDATE STATISTICS loan loan_ind

OUTPUT:

Will update statistics for only the loan_ind index on the loan table.
SQL SERVER 6.5
Chapter-5/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DBCC commands
DBCC SHOW_STATISTICS
Displays the statistical information in the distribution page for an index on a specified
table.
Indicates the selectivity of an index (lower the density returned, higher the
selectivity).
It provides the basis for determining whether or not an index would be useful to the
optimizer.

Syntax:

DBCC SHOW_STATISTICS ( table_name, index_name )
The system function STATS_DATE can be used to see the last date the statistics were
updated.
DBCC_SHOWCONTIG
Determines if the table is heavily fragmented.
When the table is heavily fragmented, fragmentation can be reduced by dropping and
recreating a clustered index which will compact the data such that data pages are
essentially full again, However, level of fullness can also be configured with the
FILLFACTOR option.


Syntax:

DBCC SHOWCONTIG ( table_id, [index_id] )
CLASSROOM EXERCISES
1. What is the difference between SORTED_DATA and
SORTED_DATA_REORG?
2. Can an index be created on a temporary table?
SQL SERVER 6.5
Chapter-5/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
IMPLEMENTATION OF VIEWS
Views
A view is an alternate way of looking at data derived from one or more tables in the
database.
The user is allowed to see only selected pieces of information in the database.
DIAGRAM
APPLICANT
APPL_NO LAST_NAME FIRST_NAME ADDRESS
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY POND DRIVE
View of
APPLICANT
APPL_NO LAST_NAME
A001 BARR
A002 ALLEN
A003 M
Views also allow you to define calculated or derived information.
EXAMPLE
A view definition can do computation on a column of a table and display the computed field as a field in
the view.
The computed field will appear as a regular column to the users view.
Users view
SQL SERVER 6.5
Chapter-5/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Advantages of view
Allow users to focus on the data of their interest only. Data that is not needed by the
users can be left out of the view.
Manipulation of the data is simplified by defining frequently used queries as views.
Customization of the users view of the database can be done which allows different
users to look at the information in the database specifically for their needs.
It provides security by allowing users to query and modify the data only which they
see; rest of the data is neither visible nor accessible. ( set by using CREATE VIEW
statement with CHECK OPTION).
To provide security, users access can be confined to :
(a) A subset of rows or columns of a base table.
(b) The rows that qualify for a join of more than one base table.
(c) A statistical summary of base table.
(d) A subset of another view or some combination of views and base tables.
With views data can be exported to other applications using bcp utility. (covered
later)
Creation of views
Views can be created by using Enterprise Manager or by Transact-SQL.

A view is stored as a separate object in the database.
Creating views by using Transact-SQL
Syntax:
CREATE VIEW [owner.] view_name
[(column_name [, column_name])]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]
WITH CHECK OPTION
By default, data modification statements on view are not checked to determine
whether the rows affected will be within the definition of the view .
SQL SERVER 6.5
Chapter-5/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
An INSERT statement can be issued on a view to add a row to an underlying table even if that row is
not defined by the view.
An UPDATE statement can be issued that changes a row so that the row no longer meets the criteria
for the view.
If above modifications should be checked, WITH CHECK OPTION should be used.
The WITH CHECK OPTION forces all data modification statements executed
against the view to adhere to the criteria set within the SELECT statement defining
the view.
When this option is set, on row modification through a view guarantees, that data will
remain visible through the view after the modification has been committed.
WITH ENCRYPTION OPTION
This option encrypts the syscomments entries that contain the text of the CREATE
VIEW statement.
Thus, the view definition can not be seen by anyone.
Querying the syscomments table or using sp_helptext will not allow the user to see
the view definition.
To unencrypt, the view should be dropped and recreated.
EXAMPLES
Projection (subset of column) example
CREATE VIEW twocolumns
AS
SELECT appl_no, last_name FROM applicant
SELECT * FROM applicant
SELECT * FROM twocolumns
OUTPUT:
A view called twocolumns is created which will allow the users to view only the two columns appl_no
and last_name.
The other two columns of the table applicant i.e first_name and address are not shown.
SQL SERVER 6.5
Chapter-5/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Appl_no last_name first_name address
-------- ---------- ----------- -------------
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY PND DRIVE
( 3 row(s) affected)
appl_no last_name
-------- ---------
A001 BARR
A002 ALLEN
A003 M
( 3 row(s) affected )
Computed column example
CREATE VIEW fines_due
(title_no, member_no, Amt_due)
AS
SELECT title_no, mem_no, (fine_assessed fine_paid)
FROM loan
SELECT * FROM fine_due
A view of a view example
CREATE VIEW fines_due_view
AS
SELECT * FROM fines_due WHERE Amt_due > 15
SELECT * FROM fines_due_view
View restrictions
A view can be created only in the current database.
One must have permission to SELECT the objects referenced in the view definition
when using the view.
SELECT INTO cannot be used because it creates a temporary table, and temporary
tables cannot be referenced in views.
Outer joins should not be used in view definitions. Because querying such a view
with a qualification on a column from the inner table of the outer join, the result can
be unexpected.
A trigger or an index cannot be created on a view.
A view can reference a maximum of 250 columns.
CREATE VIEW statements cannot be combined with other SQL statements in a
single batch.
The UNION operator cannot be used within a CREATE VIEW statement.
SQL SERVER 6.5
Chapter-5/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Dropping views
When a view is dropped, the definition of the view is deleted. The DROP VIEW
statement removes a view from the database.
Syntax:
DROP VIEW [owner.] view_name [, [owner.] view_name...]
EXAMPLE
DROP VIEW fine_due
OUTPUT:
Drops the view fine_due
Displaying information
To display the text used to create a view, sp_helptext system stored procedure can be
used.
Syntax:
sp_helptext obj_name
EXAMPLE
sp_helptext fines_due_view
OUTPUT:
Displays the text of the view fines_due_view
To get a report of the tables or views on which a view depends, and of the objects that
depend on a view, system stored procedure sp_depends can be used.
Syntax:
sp_depends obj_name
SQL SERVER 6.5
Chapter-5/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Modifying data through views
Whenever data is modified through a view, the modification takes place at the table
level.
A view does not keep a separate copy of data.
A row cannot be inserted into a view unless the NOT NULL columns in the
underlying object have defaults.
Views cannot affect more than one underlying table.
EXAMPLE
Suppose a view is based on columns from two tables table1 and table2, then a modification to the view that
affects just table1 or just table2 is acceptable, but an update that affects both the underlying tables is not
permitted.
Modifications cannot be made to certain columns like, columns with computed
values, built in functions and row aggregate functions.
CLASSROOM EXERCISES
1. Is an INSERT statement allowed if a computed column exists within the view?
2. If a view is defined with a SELECT * clause, and the structure of the underlying
table is altered, what will be the result if the view is used?
SQL SERVER 6.5
Chapter-5/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create a table called students with the following fields:
Rollno - int, Class - int , Name - varchar(10), Age - int, Sex - char(1)
2. Create an index on the column Name .
3. Create a clustered index on the column Rollno that enforces uniqueness. Notice
that index will physically order the data on the disk.
4. Create an index on the Rollno and Class columns of the students table.
5. Create a table called store which has following fields:
stor_id - int, stor_name- varchar(10), city - varchar(10), state - varchar(10),
zip - varchar(10)
6. Create a nonclustered index on the field zip, such that it fills every page
completely.
7. Create a unique clustered index on the table store on field stor_id, such that if a
duplicate key is entered, the INSERT or UPDATE statement will be ignored.
8. Use the sp_helpindex system stored procedure. What are the results?
9. Drop the index created on the Name field of the table students.
10. Execute the statement SET SHOWPLAN ON, and then query the table students
using the index key.
11. Execute the same query by using the index_id 0. Note whether index was
used.
12. Use the DBCC commands on the indexes created and analyze the results.
13. Create a view which will have the fields title, type and price from the table
titles.
14. Create a view called accounts which should have three field called title,
advance, amt_due from the titles table. The due amount is calculated as the
product of the price, royalty and ytd_sales.
15. Show the text of the view accounts.
16. Create a view called CAonly from the table authors who belong to the state
CA only. Any data modifications should apply only to the authors within the
state of California only. Verify by modifying the data for both with and
without the state CA.
SQL SERVER 6.5
Chapter-5/31
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
An index is a collection of data values of a column in a table and their corresponding
pointers to the rows where those values are physically represented in the table.
There are two types of indexes:
a) Clustered indexes - Actual data pages are a part of index. Physical order of the rows is
same.
b) Nonclustered indexes - Actual data pages are unordered.
Index is created using CREATE INDEX statement.
FILLFACTOR tells SQL Server to preserve a percentage of free space on the index page
for future expansion.
Indexes can be dropped by using DROP INDEX statement.
Distribution pages are a sampling of data values that SQL Server uses to decide if the
index is useful.
Distribution pages are updated using UPDATE STATISTICS command.
By using view a user is allowed to have a look at only selected pieces of information in
the database.
A view is created by using CREATE VIEW statement.

Das könnte Ihnen auch gefallen