Está en la página 1de 3

Para crear ndices empleamos la instruccin "create index".

La sintaxis bsica es la siguiente:


create TIPODEINDICE index NOMBREINDICE
on TABLA(CAMPO);
"TIPODEINDICE" indica si es agrupado (clustered) o no agrupado (nonclustered). Si no
especificamos crea uno No agrupado. Independientemente de si es agrupado o no, tambin se
puede especificar que sea "unique", es decir, no haya valores repetidos. Si se intenta crear un
ndice unique para un campo que tiene valores duplicados, SQL Server no lo permite.
En este ejemplo se crea un ndice agrupado nico para el campo "codigo" de la tabla "libros":
create unique clustered index I_libros_codigo
on libros(codigo);
Para identificar los ndices fcilmente, podemos agregar un prefijo al nombre del ndice, por
ejemplo "I" y luego el nombre de la tabla y/o campo.
En este ejemplo se crea un ndice no agrupado para el campo "titulo" de la tabla "libros":
create nonclustered index I_libros_titulo
on libros(titulo);
Un ndice puede tener ms de un campo como clave, son ndices compuestos. Los campos de un
ndice compuesto tienen que ser de la misma tabla (excepto cuando se crea en una vista - tema
que veremos posteriormente).
Creamos un ndice compuesto para el campo "autor" y "editorial":
create index I_libros_autoreditorial
on libros(autor,editorial);
SQL Server crea automticamente ndices cuando se establece una restriccin "primary key" o
"unique" en una tabla. Al crear una restriccin "primary key", si no se especifica, el ndice ser
agrupado (clustered) a menos que ya exista un ndice agrupado para dicha tabla. Al crear una
restriccin "unique", si no se especifica, el ndice ser no agrupado (non-clustered).
Ahora podemos entender el resultado del procedimiento almacenado "sp_helpconstraint" cuando
en la columna "constraint_type" mostraba el tipo de ndice seguido de las palabras "clustered" o
"non_clustered".
Puede especificarse que un ndice sea agrupado o no agrupado al agregar estas restricciones.
Agregamos una restriccin "primary key" al campo "codigo" de la tabla "libros" especificando que
cree un ndice NO agrupado:
alter table libros
add constraint PK_libros_codigo
primary key nonclustered (codigo);
Para ver los indices de una tabla:
sp_helpindex libros;
Muestra el nombre del ndice, si es agrupado (o no), primary (o unique) y el campo por el cual se
indexa.
Todos los ndices de la base de datos activa se almacenan en la tabla del sistema "sysindexes",
podemos consultar dicha tabla tipeando:
select name from sysindexes;
Para ver todos los ndices de la base de datos activa creados por nosotros podemos tipear la
siguiente consulta:
select name from sysindexes
where name like 'I_%';

Sintaxis
-- SQL Server Syntax

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON <object> ( column [ ASC | DESC ] [ ,...n ] )
[ INCLUDE ( column_name [ ,...n ] ) ]
[ WHERE <filter_predicate> ]
[ WITH ( <relational_index_option> [ ,...n ] ) ]
[ ON { partition_scheme_name ( column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]

[ ; ]

<object> ::=
{
[ database_name. [ schema_name ] . | schema_name. ]
table_or_view_name
}

<relational_index_option> ::=
{
PAD_INDEX = { ON | OFF }
| FILLFACTOR = fillfactor
| SORT_IN_TEMPDB = { ON | OFF }
| IGNORE_DUP_KEY = { ON | OFF }
| STATISTICS_NORECOMPUTE = { ON | OFF }
| STATISTICS_INCREMENTAL = { ON | OFF }
| DROP_EXISTING = { ON | OFF }
| ONLINE = { ON | OFF }
| ALLOW_ROW_LOCKS = { ON | OFF }
| ALLOW_PAGE_LOCKS = { ON | OFF }
| MAXDOP = max_degree_of_parallelism
| DATA_COMPRESSION = { NONE | ROW | PAGE}
[ ON PARTITIONS ( { <partition_number_expression> | <range> }
[ , ...n ] ) ]
}

<filter_predicate> ::=
<conjunct> [ AND <conjunct> ]

<conjunct> ::=
<disjunct> | <comparison>

<disjunct> ::=
column_name IN (constant ,...n)

<comparison> ::=
column_name <comparison_op> constant

<comparison_op> ::=
{ IS | IS NOT | = | <> | != | > | >= | !> | < | <= | !< }

<range> ::=
<partition_number_expression> TO <partition_number_expression>


Backward Compatible Relational Index
Important The backward compatible relational index syntax structure will be removed in a
future version of SQL Server. Avoid using this syntax structure in new development work, and
plan to modify applications that currently use the feature. Use the syntax structure
specified in <relational_index_option> instead.

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON <object> ( column_name [ ASC | DESC ] [ ,...n ] )
[ WITH <backward_compatible_index_option> [ ,...n ] ]
[ ON { filegroup_name | "default" } ]

<object> ::=
{
[ database_name. [ owner_name ] . | owner_name. ]
table_or_view_name
}

<backward_compatible_index_option> ::=
{
PAD_INDEX
| FILLFACTOR = fillfactor
| SORT_IN_TEMPDB
| IGNORE_DUP_KEY
| STATISTICS_NORECOMPUTE
| DROP_EXISTING
}
-- Windows Azure SQL Database Syntax

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON <object> ( column [ ASC | DESC ] [ ,...n ] )
[ INCLUDE ( column_name [ ,...n ] ) ]
[ WHERE <filter_predicate> ]
[ WITH ( <relational_index_option> [ ,...n ] ) ]
[ ; ]

<object> ::=
{
[ database_name. [ schema_name ] . | schema_name. ]
table_or_view_name
}

<relational_index_option> ::=
{
| IGNORE_DUP_KEY = { ON | OFF }
| STATISTICS_NORECOMPUTE = { ON | OFF }

| DROP_EXISTING = { ON | OFF }
| ONLINE = { ON | OFF }
}

<filter_predicate> ::=
<conjunct> [ AND <conjunct> ]

<conjunct> ::=
<disjunct> | <comparison>

<disjunct> ::=
column_name IN (constant ,)

<comparison> ::=
column_name <comparison_op> constant

<comparison_op> ::=
{ IS | IS NOT | = | <> | != | > | >= | !> | < | <= | !< }

También podría gustarte