Sei sulla pagina 1di 98

2010

SQL Tutorial

Transcrito por Braulio, From W3SChools SQL Developers 12/03/2010 1

SQL Tutorial SQL Basic


SQL es un lenguaje estndar para acceder a bases de datos. Nuestro manual de SQL le ensear cmo utilizar SQL para acceder y manipular datos en: MySQL, SQL Server, Access, Oracle, Sybase, DB2, y otros sistemas de base de datos.

Introduccin a SQL
SQL es un lenguaje estndar para acceder y manipular bases de datos.

Qu es SQL?

SQL significa Lenguaje de consulta estructurado SQL le permite acceder y manipular bases de datos SQL es un ANSI (American National Standards Institute) estndar

Qu se puede hacer SQL?



SQL SQL SQL SQL SQL SQL SQL SQL SQL SQL puede puede puede puede puede puede puede puede puede puede ejecutar consultas en una base de datos recuperar datos de una base de datos insertar registros en una base de datos actualizar los registros en una base de datos eliminar registros de una base de datos crear nuevas bases de datos crear nuevas tablas en una base de datos crear procedimientos almacenados en una base de datos crear vistas de una base de datos establecer permisos en las tablas, los procedimientos y puntos de vista

SQL es un estndar - pero ....


Aunque SQL es un ANSI (American National Standards Institute) estndar, hay muchas versiones diferentes del lenguaje SQL. Sin embargo, para ser compatible con el estndar ANSI, que todo el apoyo por lo menos los comandos principales (tales como SELECT, UPDATE, DELETE, INSERT, WHERE) de una manera similar. Nota: La mayora de los programas de base de datos de SQL tambin tienen sus propias extensiones propietarias adems del estndar SQL! 0

Uso de SQL en su sitio web


Para construir un sitio web que muestra algunos datos de una base de datos, se necesita lo siguiente: Un programa de base de datos de RDBMS (es decir, MS Access, SQL Server, MySQL) A lado del servidor lenguaje de scripting, como PHP o ASP SQL HTML / CSS

RDBMS

RDBMS es sinnimo de base de datos relacional. RDBMS es la base de SQL, y para todos los sistemas de bases de datos modernas, como MS SQL Server, IBM DB2, Oracle, MySQL y Microsoft Access. Los datos de RDBMS se almacenan en objetos de base de datos llamada tablas. Una tabla es una coleccin de entradas de datos relacionados y se compone de columnas y filas.

SQL Sintaxis
Tablas de base de datos
Una base de datos lo ms a menudo contiene una o ms tablas. Cada tabla se identifica por un nombre (por ejemplo, "clientes" o "pedidos"). Las tablas contienen registros (filas) con los datos. A continuacin se muestra un ejemplo de una tabla llamada "Personas":

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

La tabla contiene tres registros (uno para cada persona) y cinco columnas (p_id, Apellidos, Direccin Nombre, y la ciudad).

Sentencias SQL
La mayora de las acciones que debe realizar en una base de datos se hace con las sentencias SQL. La siguiente instruccin SQL selecciona todos los registros de las "Personas" tabla:

SELECT * FROM Persons


En este tutorial te ensear todo acerca de las diferentes sentencias SQL.

Tenga en cuenta que ...

SQL no es sensible a maysculas ni minsculas.

Punto y coma despus de sentencias SQL?


Algunos sistemas de bases de datos requieren un punto y coma al final de cada sentencia SQL. Punto y coma es la manera estndar para separar cada sentencia de SQL en sistemas de bases de datos que permiten ms de una sentencia SQL que se ejecutar en la misma llamada al servidor. Estamos usando MS Access y SQL Server 2000 y no tenemos que poner un punto y coma despus de cada sentencia SQL, pero algunos programas de bases de datos obligan a usarlo.

SQL DML y DDL


SQL se pueden dividir en dos partes: el lenguaje de manipulacin de datos (DML) y el Data Definicin Lenguaje (DDL). La consulta y comandos de actualizacin que forman parte del DML de SQL:

SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database

La parte DDL de tablas de bases de datos SQL permite que se creen o eliminen. Tambin se definen los

ndices (llaves), especificar los vnculos entre las tablas, e imponer restricciones entre las tablas. Las instrucciones de DDL ms importantes de SQL son los siguientes:

CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index

SQL SELECT Statement


La instruccin SELECT de SQL
La sentencia SELECT se utiliza para seleccionar datos de una base de datos. El resultado se almacena en una tabla de resultados, llamado el conjunto de resultados.

SQL SELECT Sintaxis SELECT column_name(s) FROM table_name

and SELECT * FROM table_name


Nota: SQL no distingue entre maysculas y minsculas. SELECT es lo mismo que select.

Un ejemplo SQL SELECT


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar el contenido de las columnas denominadas "Apellido" y "Nombre" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT LastName,FirstName FROM Persons


El conjunto de resultados se ver as:

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

SELECT * Ejemplo
Ahora queremos seleccionar todas las columnas de la tabla "Personas" . Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons


Consejo: El asterisco (*) es una forma rpida de seleccionar todas las columnas! El conjunto de resultados se ver as:

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

La navegacin en un conjunto de resultados


La mayora de los sistemas de software de bases de datos permiten la navegacin en el conjunto de resultados con funciones de programacin, tales como: movimiento-hasta el primer registro, GetContent-Registro, de movimiento al siguiente-Record, etc Funciones de programacin, como no se trata de una parte de este tutorial. Para obtener informacin sobre cmo acceder a los datos con llamadas a funciones, por favor visite nuestra ADO tutorial o nuestro tutorial PHP .

SQL SELECT DISTINCT Declaracin


6

En este captulo se explicar la instruccin SELECT DISTINCT.

El SQL SELECT DISTINCT Declaracin


En una tabla, algunas de las columnas pueden contener valores duplicados. Esto no es un problema, sin embargo, a veces se quiere mostrar slo las diferentes (distintos) en una tabla de valores. La palabra clave DISTINCT se puede utilizar para devolver los valores slo distintos (diferentes).

SQL SELECT DISTINCT Sintaxis

SELECT DISTINCT column_name(s) FROM table_name

SELECT DISTINCT Example


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar slo los valores distintos de la columna llamada "Ciudad" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT DISTINCT City FROM Persons The result-set will look like this: City Sandnes Stavanger

SQL WHERE Clause


La clusula WHERE se utiliza para filtrar los registros.

La clusula WHERE
La clusula WHERE se utiliza para extraer slo aquellos registros que cumplan un criterio determinado.

WHERE de SQL Sintaxis SELECT column_name(s) FROM table_name WHERE column_name = operator value

WHERE Clause Example


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar slo las personas que viven en la ciudad "Sandnes" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City='Sandnes' The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes

Quotes Around Text Fields


SQL usa comillas simples alrededor de valores de texto (la mayora de los sistemas de base de datos tambin se aceptan comillas dobles). Aunque, los valores numricos no deben ir entre comillas. Para los valores de texto:

This is correct: SELECT * FROM Persons WHERE FirstName= 'Tove' This is wrong: SELECT * FROM Persons WHERE FirstName= Tove For numeric values: This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965'

Los operadores permitidos en la clusula WHERE


Con la clusula WHERE, los operadores pueden utilizar los siguientes:

Operator = <> > < >= <= LIKE IN Igual No igual Mayor que Menor que Mayor o igual que Menor o igual que Search for a pattern

Description

BETWEEN Between an inclusive range


Si conoce el valor exacto que desea devolver por lo menos una de las columnas

Note: En algunas versiones de SQL el operador <> se puede escribir como =!

SQL AND & OR Operadores


La AND & OR operadores se utilizan para filtrar los registros basados en ms de una condicin.

La AND & OR Operadores


El operador AND muestra un registro si tanto la primera condicin y la segunda condicin es verdadera. El operador OR muestra un registro, si bien la condicin de primer o la segunda condicin es verdadera.

AND Operadores Ejemplos


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar slo las personas con el nombre igual a "Tove" Y el apellido es igual a "Svendson": Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'


El conjunto de resultados se ver as:

P_Id 2

LastName Svendson

FirstName Tove

Address Borgvn 23

City Sandnes

10

Operador OR Ejemplo
Ahora queremos seleccionar slo las personas con el nombre igual a "Tove" o el nombre de pila es igual a "Ola": Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola'


El conjunto de resultados se ver as:

P_Id 1 2

LastName Hansen Svendson

FirstName Ola Tove

Address Timoteivn 10 Borgvn 23

City Sandnes Sandnes

La combinacin de AND & OR


Tambin se pueden combinar AND y OR (utilizar parntesis para formar expresiones complejas). Ahora queremos seleccionar slo las personas con el apellido igual a "Svendson" Y el primer nombre es igual a "Tove" o "Ola": Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName = 'Svendson' AND (FirstName='Tove' OR FirstName='Ola')


El conjunto de resultados se ver as:

P_Id 2

LastName Svendson

FirstName Tove

Address Borgvn 23

City Sandnes

11

SQL ORDER BY Palabra clave


La palabra clave ORDER BY se utiliza para ordenar el conjunto de resultados.

La palabra clave ORDER BY


La palabra clave ORDER BY se utiliza para ordenar el conjunto de resultados de una columna especificada. La palabra clave ORDER BY ordenar los registros en orden ascendente por defecto. Si desea ordenar los registros en orden descendente, puede utilizar la palabra clave DESC.

SQL ORDER BY Sintaxis SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

ORDER BY Example
The "Persons" table: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Tom Address Timoteivn 10 Borgvn 23 Storgt 20 Vingvn 23 City Sandnes Sandnes Stavanger Stavanger

Ahora queremos seleccionar todas las personas de la tabla anterior, sin embargo, queremos clasificar a las personas por su apellido. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons ORDER BY LastName


El conjunto de resultados se ver as:

P_Id 1 4 3 2

LastName Hansen Nilsen Pettersen Svendson

FirstName Ola Tom Kari Tove

Address Timoteivn 10 Vingvn 23 Storgt 20 Borgvn 23

City Sandnes Stavanger Stavanger Sandnes

ORDER BY DESC Ejemplo


12

Ahora queremos seleccionar todas las personas de la tabla anterior, sin embargo, queremos clasificar a las personas descendentes por su apellido. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons ORDER BY LastName DESC


El conjunto de resultados se ver as:

P_Id 2 3 4 1

LastName Svendson Pettersen Nilsen Hansen

FirstName Tove Kari Tom Ola

Address Borgvn 23 Storgt 20 Vingvn 23 Timoteivn 10

City Sandnes Stavanger Stavanger Sandnes

SQL INSERT INTO Sentencia


La instruccin INSERT INTO se utiliza para insertar nuevos registros en una tabla.

La instruccin INSERT INTO


La instruccin INSERT INTO se utiliza para insertar una nueva fila en una tabla.

SQL INSERT INTO Sintaxis


Es posible escribir la instruccin INSERT INTO en dos formas. La primera forma no especifica los nombres de columna en la que los datos se insertan, slo sus valores:

INSERT INTO table_name VALUES (value1, value2, value3,...)


La segunda forma especfica tanto los nombres de las columnas y los valores a insertar:

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

SQL INSERT INTO Example


We have the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos insertar una nueva fila en la "Personas" tabla. Nosotros utilizamos la siguiente instruccin:

13

INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger') The "Persons" table will now look like this: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Johan Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 City Sandnes Sandnes Stavanger Stavanger

Introduzca los datos slo en las columnas especificadas


Tambin es posible aadir slo los datos en columnas especficas. La siguiente sentencia SQL se aade una nueva fila, pero slo aadir los datos en el "p_id", "Apellido" y las columnas "Nombre":

INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
"Personas" tabla ahora se ver as:

P_Id 1 2 3 4 5

LastName Hansen Svendson Pettersen Nilsen Tjessem

FirstName Ola Tove Kari Johan Jakob

Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2

City Sandnes Sandnes Stavanger Stavanger

14

SQL UPDATE Statement


La instruccin UPDATE se utiliza para actualizar los registros en una tabla.

La instruccin UPDATE
La instruccin UPDATE se utiliza para actualizar los registros existentes en una tabla.

SQL UPDATE Sintaxis UPDATE nombre_tabla SET column1=value, column2=value2,... WHERE some_column=some_value

Nota: Observe la clusula WHERE en la sintaxis de UPDATE. La clusula WHERE especifica qu registros o registros que deben ser actualizadas. Si se omite la clusula WHERE, todos los registros sern actualizados!

SQL UPDATE Ejemplo


The "Persons" table: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 City Sandnes Sandnes Stavanger Stavanger

Ahora queremos poner al da la persona "Tjessem, Jakob" en las "Personas" tabla. Nosotros utilizamos la siguiente instruccin:

UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob' The "Persons" table will now look like this: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 Nissestien 67 City Sandnes Sandnes Stavanger Stavanger Sandnes

15

Advertencia de actualizacin de SQL


Tenga cuidado al actualizar los registros. Si se haba omitido la clusula WHERE en el ejemplo anterior, as:

UPDATE Persons SET Address='Nissestien 67', City='Sandnes' The "Persons" table would have looked like this: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67 City Sandnes Sandnes Sandnes Sandnes Sandnes

16

SQL DELETE Statement


La sentencia DELETE se utiliza para eliminar los registros en una tabla.

La instruccin DELETE
La sentencia DELETE se utiliza para eliminar filas de una tabla.

SQL DELETE Sintaxis DELETE FROM nombre_tabla WHERE some_column=some_value


Nota: Observe la clusula WHERE en la sintaxis de DELETE. La clusula WHERE especifica qu registros o registros que se deben eliminar. Si se omite la clusula WHERE, todos los registros sern borrados!

SQL DELETE Example


The "Persons" table: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 Nissestien 67 City Sandnes Sandnes Stavanger Stavanger Sandnes

Ahora queremos borrar a la persona "Tjessem, Jakob" en las "Personas" tabla. Nosotros utilizamos la siguiente instruccin:

DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'


"Personas" tabla ahora se ver as:

P_Id 1 2 3 4

LastName Hansen Svendson Pettersen Nilsen

FirstName Ola Tove Kari Johan

Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2

City Sandnes Sandnes Stavanger Stavanger

17

Eliminar todas las filas


Es posible eliminar todas las filas de una tabla sin borrar la tabla. Esto significa que la estructura de la tabla, los atributos y los ndices son intactos:

DELETE FROM table_name or DELETE * FROM table_name


Nota: Tenga mucho cuidado al eliminar registros. No se puede deshacer esta declaracin!

SQL Advanced
18

SQL TOP Clause


La clusula TOP
La clusula TOP se utiliza para especificar el nmero de registros para volver. La clusula TOP puede ser muy til en tablas grandes con miles de registros. La devolucin de un gran nmero de registros puede tener un impacto en el rendimiento. Nota: No todos los sistemas de bases de datos apoyan la clusula TOP.

Sintaxis SQL Server SELECT TOP number|percent nombre_columna(s) FROM nombre_tabla

SQL SELECT TOP equivalente en MySQL y Oracle


MySQL Sintaxis SELECT nombre_columna(s) FROM nombre_tabla LIMIT number

Ejemplo
SELECT * FROM Persons LIMIT 5

Oracle Syntax
SELECT nombre_columna(s) FROM nombre_tabla WHERE ROWNUM <= number

Ejemplo
SELECT * FROM Persons WHERE ROWNUM <=5

19

SQL TOP Ejemplo


The "Persons" table: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Tom Address Timoteivn 10 Borgvn 23 Storgt 20 Vingvn 23 City Sandnes Sandnes Stavanger Stavanger

Ahora queremos seleccionar slo los dos primeros registros en la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT TOP 2 * FROM Persons The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes

SQL TOP PERCENT Ejemplo


The "Persons" table: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Tom Address Timoteivn 10 Borgvn 23 Storgt 20 Vingvn 23 City Sandnes Sandnes Stavanger Stavanger

Ahora queremos seleccionar slo el 50% de los registros de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT TOP 50 PERCENT * FROM Persons The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes

20

SQL LIKE Operador


El operador LIKE se utiliza en una clusula WHERE para buscar un patrn especfico en una columna.

El operador LIKE
El operador LIKE se utiliza para la bsqueda de un patrn especfico en una columna.

SQL como la sintaxis SELECT nombre_columna(s) FROM nombre_tabla WHERE nombre_columna LIKE pattern

Operador LIKE Ejemplo


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar a las personas que viven en una ciudad que empieza con "s" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City LIKE 's%'


El signo "%" se puede utilizar para definir comodines (las letras que faltan en el patrn), tanto antes como despus de que el patrn. El conjunto de resultados se ver as:

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

21

A continuacin, queremos seleccionar a las personas que viven en una ciudad que termina con una "s" de "personas" de tabla.

SELECT * FROM Persons WHERE City LIKE '%s' The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes

A continuacin, queremos seleccionar a las personas que viven en una ciudad que contiene el modelo de "tav" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City LIKE '%tav%'


El conjunto de resultados se ver as:

P_Id 3

LastName Pettersen

FirstName Kari

Address Storgt 20

City Stavanger

Tambin es posible seleccionar a las personas que viven en una ciudad que no contiene el modelo de "tav" de las "Personas" de tabla, mediante el uso de la palabra NOT. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City NOT LIKE '%tav%'


El conjunto de resultados se ver as:

P_Id 1 2

LastName Hansen Svendson

FirstName Ola Tove

Address Timoteivn 10 Borgvn 23

City Sandnes Sandnes

22

SQL Wildcards(Comidines)
Comodines SQL se pueden utilizar en la bsqueda de datos en una base de datos.

SQL comodines
Comodines SQL puede sustituir a uno o ms personajes en la bsqueda de datos en una base de datos. Comodines SQL debe ser utilizado con el operador LIKE de SQL. Con SQL, los comodines pueden utilizar los siguientes: Comodn

Descripcin A substitute for zero or more characters A substitute for exactly one character Any single character in charlist Any single character not in charlist

% _ [charlist] [^charlist] or [!charlist]

SQL Wildcard Ejemplos


Tenemos lo siguiente "Personas" tabla:

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

Utilizando el comodn %
Ahora queremos seleccionar a las personas que viven en una ciudad que empieza con "sa" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City LIKE 'sa%'


El conjunto de resultados se ver as:

P_Id 1 2

LastName Hansen Svendson

FirstName Ola Tove

Address Timoteivn 10 Borgvn 23

City Sandnes Sandnes

A continuacin, queremos seleccionar a las personas que viven en una ciudad que contiene el modelo de "nep" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE City LIKE '%nes%'


23

El conjunto de resultados se ver as:

P_Id 1 2

LastName Hansen Svendson

FirstName Ola Tove

Address Timoteivn 10 Borgvn 23

City Sandnes Sandnes

Usando el comodn _
Ahora queremos seleccionar a las personas con un nombre que comience con cualquier carcter, seguido por "la" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE FirstName LIKE '_la'


El conjunto de resultados se ver as:

P_Id 1

LastName Hansen

FirstName Ola

Address Timoteivn 10

City Sandnes

A continuacin, queremos seleccionar a las personas con un apellido que comienza con "S", seguida de cualquier carcter, seguido de "final", seguida de cualquier carcter, seguido por "a" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName LIKE 'S_end_on' The result-set will look like this:

Using the [charlist] Wildcard


P_Id 2 LastName Svendson FirstName Tove Address Borgvn 23 City Sandnes

Utilizando los botones [charlist] comodn


Ahora queremos seleccionar a las personas con un apellido que comienza con "b" o "s" o "p" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName LIKE '[bsp]%' The result-set will look like this: P_Id 2 3 LastName Svendson Pettersen FirstName Tove Kari Address Borgvn 23 Storgt 20 City Sandnes Stavanger

A continuacin, queremos seleccionar a las personas con un apellido que no comienzan con "b" o "s" o "p" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%' The result-set will look like this: P_Id 1 LastName Hansen FirstName Ola Address Timoteivn 10 City Sandnes
24

SQL IN Operator
El operador IN
El operador IN le permite especificar varios valores en una clusula WHERE.

En la sintaxis SQL SELECT nombre_colunma(s) FROM nombre_tabla WHERE nombre_columna IN (value1,value2,...)

IN Operator Example
The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar a las personas con un apellido igual a "Hansen" o "Pettersen" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') The result-set will look like this: P_Id 1 3 LastName Hansen Pettersen FirstName Ola Kari Address Timoteivn 10 Storgt 20 City Sandnes Stavanger

25

SQL BETWEEN Operador


El operador BETWEEN se utiliza en una clusula WHERE para seleccionar un rango de datos entre dos valores.

El operador BETWEEN
El operador BETWEEN selecciona un rango de datos entre dos valores. Los valores pueden ser nmeros, texto o fechas.

Entre la sintaxis SQL SELECT nombre_columna(s) FROM nombre_tabla WHERE nombre_columna BETWEEN value1 AND value2

BETWEEN Operator Ejemplo


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Ahora queremos seleccionar a las personas con el apellido en orden alfabtico entre los "Hansen" y "Pettersen" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen' The result-set will look like this: P_Id LastName FirstName 1 Hansen Ola Address Timoteivn 10 City Sandnes

Nota: El operador BETWEEN es tratado de manera diferente en diferentes bases de datos! En algunas bases de datos, las personas con el apellido de "Hansen" o "Pettersen" no aparecer, porque el operador BETWEEN slo selecciona los campos que se encuentran entre los valores y la exclusin de la prueba. En otras bases de datos, las personas con el apellido de "Hansen" o "Pettersen" ser en la lista, debido a que el operador entre selecciona los campos que se entre y como los valores de prueba. Y en otras bases de datos, las personas con el apellido de "Hansen" se mostrar, pero "Pettersen" no aparecer (como el ejemplo anterior), debido a que el operador entre campos selecciona entre los valores de prueba, incluyendo el valor de la prueba inicial y excluyendo el valor de la ltima prueba. Por lo tanto: Comprobacin de la base de datos trata el operador BETWEEN.

Ejemplo 2
use NOT BETWEEN: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
Para mostrar a las personas fuera del rango en el ejemplo anterior,

The result-set will look like this: P_Id LastName FirstName 2 3 Svendson Pettersen Tove Kari

Address Borgvn 23 Storgt 20

City Sandnes Stavanger


26

SQL Alias
Con SQL, un nombre de alias se puede dar a una tabla o una columna.

SQL Alias
Usted puede dar a una tabla o una columna de otro nombre mediante el uso de un alias. Esto puede ser una buena cosa que hacer si usted tiene los nombres de tablas muy largas o complejas, o nombres de columna. Un nombre de alias puede ser cualquier cosa, pero por lo general es corta.

Alias SQL Sintaxis para las tablas

SQL Alias Syntax for Tables


SELECT nombre_columna(s) FROM nombre_tabla AS nombre_alias

SQL Alias Syntax for Columns


SELECT nombre_columna AS nombre_alias FROM nombre_tabla

Alias Ejemplo
Supongamos que tenemos una tabla llamada "Personas" y otra tabla denominada "Product_Orders". Daremos a los alias de tabla de la "p" y "po", respectivamente. Ahora queremos una lista de todas las rdenes que "Ola Hansen" es responsable. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE p.LastName='Hansen' AND p.FirstName='Ola' The same SELECT statement without aliases: SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons, Product_Orders WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'
Como se ver a partir de las dos sentencias SELECT anterior; alias pueden realizar consultas ms fciles tanto para escribir y leer.

27

SQL Joins
Uniones SQL se utilizan para consultar datos de dos o ms tablas, sobre la base de una relacin entre ciertas columnas en estas tablas.

SQL JOIN
La palabra clave JOIN se utiliza en una sentencia SQL para consultar datos de dos o ms tablas, sobre la base de una relacin entre ciertas columnas en estas tablas. Las tablas de una base de datos a menudo estn relacionados el uno al otro con las llaves. Una clave principal es una columna (o una combinacin de columnas) con un valor nico para cada fila. Cada valor de clave principal debe ser nico dentro de la tabla. El propsito es enlazar los datos en conjunto, a travs de tablas, sin repetir todos los datos en cada tabla. Mira las "Personas" tabla:

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

Tenga en cuenta que el "p_id" columna es la clave principal de las "Personas" tabla. Esto significa que no hay dos filas no pueden tener el mismo p_id. El p_id distingue dos personas aunque tengan el mismo nombre. A continuacin, tenemos la tabla "orders":

O_Id 1 2 3 4 5

OrderNo 77895 44678 22456 24562 34764

P_Id 3 3 1 1 15

Tenga en cuenta que el "O_ID" columna es la clave principal de la tabla "orders" y que "p_id" columna se refiere a las personas en las "Personas" tabla sin usar sus nombres. Tenga en cuenta que la relacin entre las dos tablas anteriores es el "p_id" de la columna

Different SQL JOINs


28

Antes de continuar con los ejemplos, vamos a enumerar los tipos de unin que puede utilizar, y las diferencias entre ellos. JOIN: Devolver filas cuando hay al menos un registo en las dos tablas LEFT JOIN: devolver todas las filas de la tabla de la izquierda, incluso si no hay coincidencias en la tabla de la derecha. RIGHT JOIN: devolver todas las filas de la tabla de la derecha, incluso si no hay coincidencias en la tabla de la izquierda. FULL JOIN: devuelven filas cuando hay un partido en una de las mesas

SQL INNER JOIN Keyword


SQL INNER JOIN Keyword
El INNER JOIN filas palabra clave return cuando hay al menos un partido en ambas tablas.

SQL INNER JOIN Sintaxis SELECT nombre_columna(s) FROM nombre_tabla1 INNER JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna

PS: INNER JOIN es lo mismo que JOIN.

SQL INNER JOIN Ejemplo


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15

Ahora queremos una lista de todas las personas con cualquier orden. Nosotros utilizamos la siguiente sentencia SELECT:

29

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen FirstName Ola Ola Kari Kari OrderNo 22456 24562 77895 44678

El INNER JOIN filas palabra clave return cuando hay al menos un partido en ambas tablas. Si hay filas en "personas" que no tienen coincidencias en "Pedidos", las filas no se enumeran.

SQL LEFT JOIN Keyword


30

SQL LEFT JOIN Keyword


La palabra clave LEFT JOIN devuelve todas las filas de la tabla de la izquierda (table_name1), incluso si no hay coincidencias en la tabla a la derecha (table_name2).

SQL LEFT JOIN Sintaxis SELECT nombre_columna(s) FROM nombre_tabla1 LEFT JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna

PS: En algunas bases de datos LEFT JOIN se llama LEFT OUTER JOIN.

SQL LEFT JOIN Ejemplo


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15

Ahora queremos una lista de todas las personas y sus rdenes - en su caso, a partir de las tablas anteriores. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen FirstName Ola OrderNo 22456
31

Hansen Pettersen Pettersen Svendson

Ola Kari Kari Tove

24562 77895 44678

La palabra clave JOIN devuelve todas las filas de la tabla de la izquierda (personas), incluso si no hay coincidencias en la tabla a la derecha (rdenes).

SQL RIGHT JOIN Keyword


SQL RIGHT JOIN Keyword
La palabra clave RIGHT JOIN devuelve todas las filas de la tabla de la derecha (table_name2), incluso si no hay coincidencias en la tabla a la izquierda (table_name1).

SQL Sintaxis RIGHT JOIN SELECT nombre_columna(s) FROM nombre_tabla1 RIGHT JOIN nombre_tabla2 ON nombre_tabla1.column_name = nombre_tabla2.column_name

PS: En algunas bases de datos se llama RIGHT JOIN RIGHT OUTER JOIN.

SQL RIGHT JOIN Ejemplo


The "Persons" table: P_Id LastName 1 2 3 Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

The "Orders" table: O_Id OrderNo 1 2 3 4 5 77895 44678 22456 24562 34764

P_Id 3 3 1 1 15

Ahora queremos una lista de todas las rdenes con las personas que contienen - en su caso, a partir de las tablas anteriores. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo


32

FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen FirstName Ola Ola Kari Kari OrderNo 22456 24562 77895 44678 34764

La palabra clave RIGHT JOIN devuelve todas las filas de la tabla de la derecha (rdenes), incluso si no hay coincidencias en la tabla a la izquierda (las personas).

SQL FULL JOIN Keyword


SQL FULL JOIN Keyword
El Join completo filas palabra clave return cuando hay un partido en una de las mesas.

Completo de SQL Sintaxis de JOIN SELECT nombre_columna(s) FROM nombre_tabla1 FULL JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna

SQL FULL JOIN Example


The "Persons" table: P_Id LastName FirstName Address City
33

1 2 3

Hansen Svendson Pettersen

Ola Tove Kari

Timoteivn 10 Borgvn 23 Storgt 20

Sandnes Sandnes Stavanger

The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15

Ahora queremos una lista de todas las personas y sus rdenes, y todos los pedidos con sus personas. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen Svendson FirstName Ola Ola Kari Kari Tove 34764 OrderNo 22456 24562 77895 44678

La palabra clave FULL JOIN devuelve todas las filas de la tabla de la izquierda (personas), y todas las filas de la tabla de la derecha (rdenes). Si hay filas en "personas" que no tienen coincidencias en "Pedidos", o si hay filas en "rdenes" que no tienen coincidencias en "Personas", las filas se enumeran tambin.

SQL UNION Operador


34

El operador de SQL UNION combina dos o ms instrucciones SELECT.

El operador UNION SQL


El operador UNION se utiliza para combinar el conjunto de resultados de dos o ms sentencias SELECT. Observe que cada instruccin SELECT dentro de la Unin deben tener el mismo nmero de columnas. Las columnas tambin deben tener tipos de datos similares. Adems, las columnas de cada instruccin SELECT debe ir en el mismo orden.

Sintaxis SQL UNION SELECT nombre_columna(s) FROM nombre_tabla1 UNION SELECT nombre_columna(s) FROM nombre_tabla2

Note: El operador UNION slo selecciona valores distintos por defecto. Para permitir que los valores
duplicados, use UNION ALL.

SQL UNION ALL Syntax


SELECT nombre_columna(s) FROM nombre_tabla1 UNION ALL SELECT nombre_columna(s) FROM nombre_tabla2 PS: Los nombres de columna en el conjunto de resultados de una UNION son siempre iguales a los
nombres de columna en la primera instruccin SELECT de la UNION.

SQL UNION Ejemplo


Look at the following tables: "Employees_Norway": E_ID 01 02 03 04 E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari

"Employees_USA": E_ID 01 02 03 E_Name Turner, Sally Kent, Clark Svendson, Stephen


35

04

Scott, Stephen

Ahora queremos a la lista de todos los diferentes empleados en Noruega y EE.UU.. Nosotros utilizamos la siguiente sentencia SELECT:

SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA The result-set will look like this:

E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen Note: Este comando no se puede utilizar a la lista de todos los empleados en Noruega y EE.UU.. En el
ejemplo anterior tenemos dos empleados con nombres iguales, y slo uno de ellos se enumeran.El comando UNION slo selecciona valores distintos.

36

SQL UNION ALL Ejemplo


Ahora queremos a la lista de todos los empleados en Noruega y EE.UU.:

SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA Resultado: E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Svendson, Stephen Scott, Stephen

SQL SELECT INTO Sentencia


El SQL SELECT INTO se puede utilizar para crear copias de seguridad de las tablas.

El SQL SELECT INTO


La instruccin SELECT INTO selecciona datos de una tabla y lo inserta en una tabla diferente. La instruccin SELECT INTO se utiliza con mayor frecuencia para crear copias de seguridad de las tablas.

SQL SELECT en la sintaxis

Podemos seleccionar todas las columnas en la nueva tabla:

SELECT * INTO nombre_tabla_nueva [IN externaldatabase] FROM nombre_tabla_vieja


O se puede seleccionar slo las columnas que desea en la nueva tabla:table:

SELECT nombre_columna(s) INTO nombre_tabla_nueva [IN externaldatabase] FROM nombre_tabla_vieja

SQL SELECT INTO Ejemplo


Haga una copia de seguridad - Ahora queremos hacer una copia exacta de los datos en nuestro "Personas" tabla. Nosotros utilizamos la siguiente instruccin:

SELECT * INTO Persons_Backup FROM Persons


Tambin podemos utilizar la clusula IN para copiar la tabla en otra base de datos:

37

SELECT * INTO Persons_Backup IN 'Backup.mdb' FROM Persons


Tambin puede copiar slo unos pocos campos en la nueva tabla:

SELECT LastName,FirstName INTO Persons_Backup FROM Persons

SQL SELECT INTO - With a WHERE Clause


Tambin puede agregar una clusula WHERE. La siguiente sentencia SQL crea una "Persons_Backup" tabla con slo las personas que vive en la ciudad "Sandnes":

SELECT LastName,Firstname INTO Persons_Backup FROM Persons WHERE City = 'Sandnes'

SQL SELECT INTO - tablas combinadas


Seleccin de los datos de ms de una tabla tambin es posible. El siguiente ejemplo se crea un "Persons_Order_Backup" tabla contiene datos de las dos tablas "Personas" y "Pedidos":

SELECT Persons.LastName,Orders.OrderNo INTO Persons_Order_Backup FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id

SQL CREATE DATABASE Sentencia


The CREATE DATABASE Statement
La instruccin CREATE DATABASE se utiliza para crear una base de datos.

SQL CREATE DATABASE Syntax


CREATE DATABASE database_name

CREATE DATABASE Example


38

Ahora queremos crear una base de datos llamada "my_db". Nosotros utilizamos la siguiente instruccin CREATE DATABASE:

CREATE DATABASE my_db


Tablas de bases de datos se pueden agregar con el comando CREATE TABLE.

SQL CREATE TABLE Statement


The CREATE TABLE Statement
La sentencia CREATE TABLE se utiliza para crear una tabla en una base de datos.

SQL CREATE TABLE Syntax


CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
El tipo de datos especifica qu tipo de datos de la columna puede contener. Para una referencia completa de todos los tipos de datos disponibles en MS Access, MySQL y SQL Server, vaya a nuestra completa Referencia Tipos de datos .

39

CREATE TABLE Ejemplo


Ahora queremos crear una tabla llamada "Personas", que contiene cinco columnas: p_id, Apellidos, Direccin Nombre, y la ciudad. Nosotros utilizamos la siguiente sentencia CREATE TABLE:

CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )
La columna p_id es de tipo int y se mantendr un nmero. El Apellido, Nombre, Direccin, y las columnas de la ciudad son de tipo varchar con una longitud mxima de 255 caracteres. El vaco "Personas" tabla ahora se ver as:

P_Id

LastName

FirstName

Address

City

La tabla de vaco puede ser llenada con los datos con la instruccin INSERT INTO.

SQL Constraints
Las restricciones se utilizan para limitar el tipo de datos que pueden ir en una tabla. Las restricciones se pueden especificar cuando se crea una tabla (con la sentencia CREATE TABLE) o despus de crear la tabla (con la instruccin ALTER TABLE). Nos centraremos en las siguientes restricciones:

NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT

Los siguientes captulos se describen cada una restriccin en detalle.

40

SQL NOT NULL Constraint


De manera predeterminada, una columna de tabla puede contener valores NULL.

SQL NOT NULL Constraint


La restriccin NOT NULL cumplir una columna para que no acepte valores NULL. La restriccin NOT NULL aplica un campo para contener siempre un valor. Esto significa que no se puede insertar un nuevo registro, o actualizar un registro sin necesidad de aadir un valor a este campo. El siguiente SQL cumplir las "p_id columna" y "LastName" columna no acepta valores NULL:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

SQL UNIQUE Constraint


La restriccin UNIQUE identifica de forma nica cada registro de una tabla de base de datos. Las restricciones UNIQUE y PRIMARY KEY tanto una garanta de la unicidad de una columna o conjunto de columnas. Una restriccin PRIMARY KEY, automticamente tiene una restriccin UNIQUE definidos en l. Tenga en cuenta que puede tener muchas restricciones UNIQUE por tabla, pero slo una restriccin PRIMARY KEY por cada tabla.

SQL UNIQUE Constraint on CREATE TABLE


El siguiente SQL crea una restriccin UNIQUE en la "p_id" columna cuando las "personas" se crea la tabla:

MySQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) )

SQL Server / Oracle / MS Access:


41

CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
Para permitir la designacin de una restriccin UNIQUE, y para definir una restriccin UNIQUE en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) )

SQL UNIQUE Constraint on ALTER TABLE


Para crear una restriccin UNIQUE en la "p_id" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD UNIQUE (P_Id)
Para permitir la designacin de una restriccin UNIQUE, y para definir una restriccin UNIQUE en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

To DROP a UNIQUE Constraint


42

Para eliminar una restriccin UNIQUE, utilice las siguientes instrucciones:

MySQL: ALTER TABLE Persons DROP INDEX uc_PersonID SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT uc_PersonID

SQL PRIMARY KEY Constraint


La restriccin PRIMARY KEY identifica de forma nica cada registro de una tabla de base de datos. Las claves principales deben contener valores nicos. Una columna de clave principal no puede contener valores NULL. Cada tabla debe tener una clave principal y cada tabla slo puede tener una clave principal.

SQL PRIMARY KEY Constraint on CREATE TABLE


El siguiente SQL crea una clave principal en la "p_id" columna cuando las "personas" se crea la tabla:

MySQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

Para permitir la designacin de una restriccin PRIMARY KEY, y para definir una restriccin PRIMARY KEY en varias columnas, utilice la siguiente sintaxis SQL:

43

MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) )
Nota: En el ejemplo anterior slo hay una clave principal (pk_PersonID). Sin embargo, el valor de la pk_PersonID se compone de dos columnas (p_id y LastName).

SQL PRIMARY KEY Constraint on ALTER TABLE


Para crear una restriccin PRIMARY KEY en el "p_id" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD PRIMARY KEY (P_Id)
Para permitir la designacin de una restriccin PRIMARY KEY, y para definir una restriccin PRIMARY KEY en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) Note: Si utiliza la instruccin ALTER TABLE para agregar una clave principal, la columna de clave
principal (s) ya deben haber sido declaradas para no contener valores NULL (cuando la tabla se cre por primera vez).

To DROP a PRIMARY KEY Constraint


Para eliminar una restriccin PRIMARY KEY, utilice las siguientes instrucciones:

44

MySQL: ALTER TABLE Persons DROP PRIMARY KEY SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY Constraint


Una clave fornea en una tabla de puntos a una clave principal de otra tabla. Vamos a ilustrar la clave externa con un ejemplo. Mira a los dos cuadros siguientes: "Personas" tabla:

P_Id 1 2 3

LastName Hansen Svendson Pettersen

FirstName Ola Tove Kari

Address Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

The "Orders" table: O_Id 1 2 3 4 OrderNo 77895 44678 22456 24562 P_Id 3 3 2 1

Tenga en cuenta que el "p_id" columna en los puntos de "pedidos" a la mesa "p_id" en la columna de "Personas" tabla. El "p_id" columna de la "Personas" tabla es la clave principal de la "Personas" tabla. El "p_id" columna de la tabla "orders" es una clave externa en la tabla "orders". La restriccin FOREIGN KEY se utiliza para evitar acciones que pudieran destruir los vnculos entre las tablas. La restriccin de clave externa tambin impide que los datos no vlidos forma que se inserta en la columna de clave externa, ya que tiene que ser uno de los valores contenidos en la tabla al que apunta.

SQL FOREIGN KEY Constraint on CREATE TABLE


El siguiente SQL crea una clave externa en la "p_id" columna cuando las "rdenes" se crea la tabla:

MySQL:
45

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) )
Para permitir la designacin de una restriccin FOREIGN KEY, y para la definicin de una restriccin FOREIGN KEY de varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )

46

SQL FOREIGN KEY Constraint on ALTER TABLE


Para crear una restriccin FOREIGN KEY de la "p_id" columna cuando la tabla "orders" ya est creado, utilice el siguiente SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
Para permitir la designacin de una restriccin FOREIGN KEY, y para la definicin de una restriccin FOREIGN KEY de varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint


Para eliminar una restriccin FOREIGN KEY, utilice el siguiente SQL:

MySQL: ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders SQL Server / Oracle / MS Access: ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders

47

SQL CHECK Constraint


La restriccin CHECK se utiliza para limitar el rango de valores que se pueden colocar en una columna. Si se define una restriccin CHECK en una columna que slo permite ciertos valores para esta columna. Si se define una restriccin CHECK en una tabla se puede limitar los valores de determinadas columnas basadas en los valores de otras columnas de la fila.

SQL CHECK Constraint on CREATE TABLE


El siguiente SQL crea una restriccin CHECK en el "p_id" columna cuando las "personas" se crea la tabla. La restriccin CHECK especifica que la columna "p_id" slo pueden ser nmeros enteros mayores que 0.

My SQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address archar(255), City varchar(255) )
Para permitir la designacin de una restriccin CHECK, y para definir una restriccin CHECK en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )

SQL CHECK Constraint on ALTER TABLE


48

Para crear una restriccin CHECK en el "p_id" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CHECK (P_Id>0)
Para permitir la designacin de una restriccin CHECK, y para definir una restriccin CHECK en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint


Para eliminar una restriccin CHECK, utilice las siguientes instrucciones:

SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT chk_Person

SQL DEFAULT Constraint


49

La restriccin DEFAULT se utiliza para insertar un valor predeterminado en una columna. El valor por defecto ser aadido a todos los nuevos registros, si no hay otro valor especificado.

SQL restriccin DEFAULT en CREATE TABLE


El siguiente SQL crea una restriccin DEFAULT en la "City" columna cuando las "personas" se crea la tabla:

My SQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' )
La restriccin DEFAULT tambin puede ser utilizado para insertar los valores del sistema, mediante el uso de funciones como GETDATE ():

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, OrderDate date DEFAULT GETDATE() )

SQL DEFAULT Constraint on ALTER TABLE


Para crear una restriccin DEFAULT en la "City" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:

MySQL: ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES' SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES'

To DROP a DEFAULT Constraint


Para eliminar una restriccin DEFAULT, utilice las siguientes instrucciones:

MySQL: ALTER TABLE Persons ALTER City DROP DEFAULT

SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City DROP DEFAUL
50

SQL CREATE INDEX Statement


La instruccin CREATE INDEX se utiliza para crear ndices de las tablas. ndices permiten la aplicacin de base de datos para encontrar rpidamente los datos, sin necesidad de leer toda la tabla.

ndices
Un ndice se puede crear en una tabla para encontrar datos ms rpido y eficaces. Los usuarios no pueden ver los ndices, que son utilizados para acelerar las bsquedas / consultas. Nota: Actualizando una tabla con los ndices lleva ms tiempo que la actualizacin de una tabla sin (ya que los ndices tambin se necesita una actualizacin). Por lo que slo debe crear ndices en columnas (y tablas) que con frecuencia se realizaron bsquedas en contra

SQL CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed: CREATE INDEX index_name ON table_name (column_name)

SQL CREATE UNIQUE INDEX Syntax


Crea un ndice en una tabla. Los valores duplicados estn permitidos:

CREATE UNIQUE INDEX index_name ON table_name (column_name) Note: La sintaxis para la creacin de ndices vara entre diferentes bases de datos. Por lo tanto:
Compruebe la sintaxis para la creacin de ndices en la base de datos.

CREATE INDEX Example


La sentencia SQL siguiente crea un ndice llamado "PINDEX" en el "Apellidos" en la columna "Personas" tabla:

CREATE INDEX PIndex ON Persons (LastName)


Si desea crear un ndice en una combinacin de columnas, se pueden listar los nombres de columna entre parntesis, separados por comas:

CREATE INDEX PIndex ON Persons (LastName, FirstName)

51

SQL DROP INDEX, DROP TABLE, and DROP DATABASE


ndices, tablas y bases de datos pueden ser fcilmente eliminadas / elimina con la sentencia DROP.

The DROP INDEX Statement


La instruccin DROP INDEX se utiliza para eliminar un ndice en una tabla..

DROP INDEX Syntax for MS Access:


DROP INDEX index_name ON table_name

DROP INDEX Syntax for MS SQL Server:


DROP INDEX table_name.index_name

DROP INDEX Syntax for DB2/Oracle:


DROP INDEX index_name

DROP INDEX Syntax for MySQL:


ALTER TABLE table_name DROP INDEX index_name

The DROP TABLE Statement


La sentencia DROP DATABASE se usa para borrar una base de datos.

DROP TABLE table_name

The DROP DATABASE Statement


The DROP DATABASE statement is used to delete a database. DROP DATABASE database_name

The TRUNCATE TABLE Statement


What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement: TRUNCATE TABLE table_name

52

SQL ALTER TABLE Statement


The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

SQL ALTER TABLE Syntax


To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name To change the data type of a column in a table, use the following syntax: ALTER TABLE table_name ALTER COLUMN column_name datatype

53

SQL ALTER TABLE Example


Look at the "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ADD DateOfBirth date Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference. The "Persons" table will now like this: P_Id LastName 1 2 3 Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger DateOfBirth

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ALTER COLUMN DateOfBirth year Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or fourdigit format.

54

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons DROP COLUMN DateOfBirth The "Persons" table will now like this: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

SQL AUTO INCREMENT Field


Auto-increment allows a unique number to be generated when a new record is inserted into a table.

AUTO INCREMENT a Field


Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. We would like to create an auto-increment field in a table.

Syntax for MySQL


The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE Persons ( P_Id int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) )

55

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE Persons AUTO_INCREMENT=100 To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically): INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

Syntax for SQL Server


The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE Persons ( P_Id int PRIMARY KEY IDENTITY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. To specify that the "P_Id" column should start at value 10 and increment by 5, change the identity to IDENTITY(10,5). To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically): INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

56

Syntax for Access


The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE Persons ( P_Id PRIMARY KEY AUTOINCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record. To specify that the "P_Id" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5). To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically): INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

Syntax for Oracle


In Oracle the code is a little bit more tricky. You will have to create an auto-increment field with the sequence object (this object generates a number sequence). Use the following CREATE SEQUENCE syntax: CREATE SEQUENCE seq_person MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10 The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access. To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
57

INSERT INTO Persons (P_Id,FirstName,LastName) VALUES (seq_person.nextval,'Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

SQL Views
A view is a virtual table. This chapter shows how to create, update, and delete a view.

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

SQL CREATE VIEW Syntax


CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the "Products" table. The view is created with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No We can query the view above as follows: SELECT * FROM [Current Product List]
58

Another view in the Northwind sample database selects every product in the "Products" table with a unit price higher than the average unit price: CREATE VIEW [Products Above Average Price] AS SELECT ProductName,UnitPrice FROM Products

59

WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products) We can query the view above as follows: SELECT * FROM [Products Above Average Price] Another view in the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called "Product Sales for 1997": CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for 1997] GROUP BY CategoryName We can query the view above as follows: SELECT * FROM [Category Sales For 1997] We can also add a condition to the query. Now we want to see the total sale only for the category "Beverages": SELECT * FROM [Category Sales For 1997] WHERE CategoryName='Beverages'

SQL Updating a View


You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No

SQL Dropping a View


You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name
60

SQL Date Functions


SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database. As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets complicated. Before talking about the complications of querying for dates, we will look at the most important built-in functions for working with dates.

MySQL Date Functions


The following table lists the most important built-in date functions in MySQL: Function
NOW() CURDATE() CURTIME() DATE() EXTRACT() DATE_ADD() DATE_SUB() DATEDIFF()

Description Returns the current date and time Returns the current date Returns the current time Extracts the date part of a date or date/time expression Returns a single part of a date/time Adds a specified time interval to a date Subtracts a specified time interval from a date Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats

61

SQL Server Date Functions


The following table lists the most important built-in date functions in SQL Server: Function
GETDATE() DATEPART() DATEADD() DATEDIFF() CONVERT()

Description Returns the current date and time Returns a single part of a date/time Adds or subtracts a specified time interval from a date Returns the time between two dates Displays date/time data in different formats

SQL Date Data Types


MySQL comes with the following data types for storing a date or a date/time value in the database:

DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: YYYY-MM-DD HH:MM:SS YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in the database:

DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your database! For an overview of all data types available, go to our complete Data Types reference.

SQL Working with Dates


You can compare two dates easily if there is no time component involved! Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 2 3 4 Geitost Camembert Pierrot Mozzarella di Giovanni Mascarpone Fabioli 2008-11-11 2008-11-09 2008-11-11 2008-10-29

62

Now we want to select the records with an OrderDate of "2008-11-11" from the table above. We use the following SELECT statement: SELECT * FROM Orders WHERE OrderDate='2008-11-11' The result-set will look like this:

OrderId 1

ProductName Geitost

OrderDate 2008-11-11

3 Mozzarella di Giovanni 2008-11-11 Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column): OrderId 1 2 3 4 ProductName Geitost Camembert Pierrot Mozzarella di Giovanni Mascarpone Fabioli OrderDate 2008-11-11 13:23:44 2008-11-09 15:45:21 2008-11-11 11:12:01 2008-10-29 14:56:59

If we use the same SELECT statement as above: SELECT * FROM Orders WHERE OrderDate='2008-11-11' we will get no result! This is because the query is looking only for dates with no time portion. Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your dates!

63

SQL NULL Values


NULL values represent missing unknown data. By default, a table column can hold NULL values. This chapter will explain the IS NULL and IS NOT NULL operators.

SQL NULL Values


If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value. NULL values are treated differently from other values. NULL is used as a placeholder for unknown or inapplicable values. Note: It is not possible to compare NULL and 0; they are not equivalent.

SQL Working with NULL Values


Look at the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Borgvn 23 Address City Sandnes Sandnes Stavanger

Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value. How can we test for NULL values? It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.

64

SQL IS NULL
How do we select only the records with NULL values in the "Address" column? We will have to use the IS NULL operator: SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NULL The result-set will look like this: LastName Hansen Pettersen FirstName Ola Kari Address

Tip: Always use IS NULL to look for NULL values.

SQL IS NOT NULL


How do we select only the records with no NULL values in the "Address" column? We will have to use the IS NOT NULL operator: SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NOT NULL The result-set will look like this:

LastName Svendson

FirstName Tove

Address Borgvn 23

In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.

65

SQL NULL Functions


SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions
Look at the following "Products" table: P_Id 1 2 3 ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.45 32.56 15.67 UnitsInStock 16 23 9 20 UnitsOnOrder 15

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values. We have the following SELECT statement: SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder) FROM Products In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL. Microsoft's ISNULL() function is used to specify how we want to treat NULL values. The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result. In this case we want NULL values to be zero. Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL: SQL Server / MS Access SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0)) FROM Products Oracle Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result: SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0)) FROM Products

66

MySQL MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function. In MySQL we can use the IFNULL() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0)) FROM Products or we can use the COALESCE() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0)) FROM Products

67

SQL Data Types


Data types and ranges for Microsoft Access, MySQL and SQL Server.

Microsoft Access Data Types


Data type Text Memo Description Use for text or combinations of text and numbers. 255 characters maximum Memo is used for larger amounts of text. Stores up to 65,536 characters. Note: You cannot sort a memo field. However, they are searchable Allows whole numbers from 0 to 255 Allows whole numbers between -32,768 and 32,767 Allows whole numbers between -2,147,483,648 and 2,147,483,647 Single precision floating-point. Will handle most decimals Double precision floating-point. Will handle most decimals 1 byte 2 bytes 4 bytes 4 bytes 8 bytes Storage

Byte Integer Long Single Double Currency

Use for currency. Holds up to 15 digits of whole dollars, plus 48 bytes decimal places. Tip: You can choose which country's currency to use AutoNumber fields automatically give each record its own number, usually starting at 1 Use for dates and times 4 bytes 8 bytes

AutoNumber Date/Time Yes/No

A logical field can be displayed as Yes/No, True/False, or 1 bit On/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) Contain links to other files, including web pages up to 1GB

Ole Object Hyperlink

Lookup Wizard Let you type a list of options, which can then be chosen from a 4 bytes drop-down list

68

MySQL Data Types


In MySQL there are three main types : text, number, and Date/Time types. Text types: Data type CHAR(size) Description Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type TINYTEXT TEXT BLOB Holds a string with a maximum length of 255 characters Holds a string with a maximum length of 65,535 characters For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXT LONGBLOB Holds a string with a maximum length of 4,294,967,295 characters For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

Number types:

69

Data type TINYINT(size)

Description -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis

SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) BIGINT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

FLOAT(size,d)

DOUBLE(size,d)

DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number.

70

Data type DATE()

Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31'

DATETIME()

*A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYYMM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC TIME() A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' YEAR() A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.

SQL Server Data Types


71

Character strings: Data type char(n) varchar(n) varchar(max) text Description Fixed-length character string. Maximum 8,000 characters Variable-length character string. Maximum 8,000 characters Variable-length character string. Maximum 1,073,741,824 characters Variable-length character string. Maximum 2GB of text data Storage n

Unicode strings: Data type nchar(n) nvarchar(n) nvarchar(max) ntext Description Fixed-length Unicode data. Maximum 4,000 characters Variable-length Unicode data. Maximum 4,000 characters Variable-length Unicode data. Maximum 536,870,912 characters Variable-length Unicode data. Maximum 2GB of text data Storage

Binary types: Data type bit binary(n) varbinary(n) image Description Allows 0, 1, or NULL Fixed-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 2GB Storage

varbinary(max) Variable-length binary data. Maximum 2GB

72

Number types: Data type tinyint smallint int bigint decimal(p,s) Description Allows whole numbers from 0 to 255 Allows whole numbers between -32,768 and 32,767 Allows whole numbers between -2,147,483,648 and 2,147,483,647 Storage 1 byte 2 bytes 4 bytes

Allows whole numbers between -9,223,372,036,854,775,808 8 bytes and 9,223,372,036,854,775,807 Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 Fixed precision and scale numbers. 5-17 bytes Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 Monetary data from -214,748.3648 to 214,748.3647 4 bytes Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes 5-17 bytes

numeric(p,s)

smallmoney money float(n)

Floating precision number data from -1.79E + 308 to 1.79E + 4 or 8 308. bytes The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8byte field. Default value of n is 53.

real

Floating precision number data from -3.40E + 38 to 3.40E + 38

4 bytes

73

Date types: Data type datetime datetime2 smalldatetime date time datetimeoffset timestamp Description Storage

From January 1, 1753 to December 31, 9999 with an accuracy 8 bytes of 3.33 milliseconds From January 1, 0001 to December 31, 9999 with an accuracy 6-8 bytes of 100 nanoseconds From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute Store a time only to an accuracy of 100 nanoseconds 4 bytes

Store a date only. From January 1, 0001 to December 31, 9999 3 bytes 3-5 bytes The same as datetime2 with the addition of a time zone offset 8-10 bytes Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable

Other data types: Data type sql_variant Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing

uniqueidentifier Stores a globally unique identifier (GUID) xml cursor table

74

SQL Functions
SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value. Useful scalar functions: UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed Tip: The aggregate functions and the scalar functions will be explained in details in the next chapters.

75

SQL AVG() Function


The AVG() Function
The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax


SELECT AVG(column_name) FROM table_name

SQL AVG() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the average value of the "OrderPrice" fields. We use the following SQL statement: SELECT AVG(OrderPrice) AS OrderAverage FROM Orders The result-set will look like this: OrderAverage 950

76

Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value. We use the following SQL statement: SELECT Customer FROM Orders WHERE OrderPrice > (SELECT AVG(OrderPrice) FROM Orders) The result-set will look like this:

Customer Hansen Nilsen Jensen

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax


The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax


The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_name) FROM table_name Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.

SQL COUNT(column_name) Example


We have the following "Orders" table:
77

O_Id 1 2 3 4 5 6

OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04

OrderPrice 1000 1600 700 300 2000 100

Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to count the number of orders from "Customer Nilsen".We use the following SQL statement: SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Nilsen' The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total: CustomerNilsen 2

SQL COUNT(*) Example


If we omit the WHERE clause, like this: SELECT COUNT(*) AS NumberOfOrders FROM Orders The result-set will look like this: NumberOfOrders 6 which is the total number of rows in the table.

SQL COUNT(DISTINCT column_name) Example


Now we want to count the number of unique customers in the "Orders" table. We use the following SQL statement: SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders

The result-set will look like this:

78

NumberOfCustomers 3 which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.

SQL FIRST() Function


The FIRST() function returns the first value of the selected column.

SQL FIRST() Syntax


SELECT FIRST(column_name) FROM table_name

SQL FIRST() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the first value of the "OrderPrice" column. We use the following SQL statement: SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders Tip: Workaround if FIRST() function is not supported: SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1 The result-set will look like this: FirstOrderPrice 1000

79

SQL LAST() Function


The LAST() Function
The LAST() function returns the last value of the selected column.

SQL LAST() Syntax


SELECT LAST(column_name) FROM table_name

SQL LAST() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the last value of the "OrderPrice" column. We use the following SQL statement: SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders Tip: Workaround if LAST() function is not supported: SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1 The result-set will look like this: LastOrderPrice 100

SQL MAX() Function


80

The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax


SELECT MAX(column_name) FROM table_name

SQL MAX() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the largest value of the "OrderPrice" column. We use the following SQL statement: SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders The result-set will look like this: LargestOrderPrice 2000

81

SQL MIN() Function


The MIN() Function
The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax


SELECT MIN(column_name) FROM table_name

SQL MIN() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the smallest value of the "OrderPrice" column. We use the following SQL statement: SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders The result-set will look like this: SmallestOrderPrice 100

82

SQL SUM() Function


The SUM() Function
The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax


SELECT SUM(column_name) FROM table_name

SQL SUM() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the sum of all "OrderPrice" fields". We use the following SQL statement: SELECT SUM(OrderPrice) AS OrderTotal FROM Orders The result-set will look like this: OrderTotal 5700

SQL GROUP BY Statement


83

Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SQL GROUP BY Syntax


SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name

SQL GROUP BY Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the total sum (total order) of each customer. We will have to use the GROUP BY statement to group the customers.We use the following SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
84

The result-set will look like this: Customer Hansen Nilsen Jensen SUM(OrderPrice) 2000 1700 2000

Nice! Isn't it? :) Let's see what happens if we omit the GROUP BY statement: SELECT Customer,SUM(OrderPrice) FROM Orders The result-set will look like this: Customer Hansen Nilsen Hansen Hansen Jensen Nilsen SUM(OrderPrice) 5700 5700 5700 5700 5700 5700

The result-set above is not what we wanted. Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value (that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each row in the "Orders" table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.

GROUP BY More Than One Column


We can also use the GROUP BY statement on more than one column, like this: SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate

SQL HAVING Clause


The HAVING Clause
85

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SQL HAVING 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

SQL HAVING Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find if any of the customers have a total order of less than 2000.We use the following SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000
86

The result-set will look like this: Customer Nilsen SUM(OrderPrice) 1700

Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500. We add an ordinary WHERE clause to the SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders WHERE Customer='Hansen' OR Customer='Jensen' GROUP BY Customer HAVING SUM(OrderPrice)>1500 The result-set will look like this: Customer Hansen Jensen SUM(OrderPrice) 2000 2000

87

SQL UCASE() Function


The UCASE() Function
The UCASE() function converts the value of a field to uppercase.

SQL UCASE() Syntax


SELECT UCASE(column_name) FROM table_name

Syntax for SQL Server


SELECT UPPER(column_name) FROM table_name

SQL UCASE() Example


We have the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to uppercase. We use the following SELECT statement: SELECT UCASE(LastName) as LastName,FirstName FROM Persons The result-set will look like this: LastName HANSEN SVENDSON PETTERSEN FirstName Ola Tove Kari

88

SQL LCASE() Function


The LCASE() Function
The LCASE() function converts the value of a field to lowercase.

SQL LCASE() Syntax


SELECT LCASE(column_name) FROM table_name

Syntax for SQL Server


SELECT LOWER(column_name) FROM table_name

SQL LCASE() Example


We have the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to lowercase. We use the following SELECT statement: SELECT LCASE(LastName) as LastName,FirstName FROM Persons The result-set will look like this: LastName hansen svendson pettersen FirstName Ola Tove Kari

89

SQL MID() Function


The MID() Function
The MID() function is used to extract characters from a text field.

SQL MID() Syntax


SELECT MID(column_name,start[,length]) FROM table_name

Parameter column_name start length

Description Required. The field to extract characters from Required. Specifies the starting position (starts at 1) Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text

SQL MID() Example


We have the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to extract the first four characters of the "City" column above. We use the following SELECT statement: SELECT MID(City,1,4) as SmallCity FROM Persons The result-set will look like this: SmallCity Sand Sand Stav
90

SQL LEN() Function


The LEN() Function
The LEN() function returns the length of the value in a text field.

SQL LEN() Syntax


SELECT LEN(column_name) FROM table_name

SQL LEN() Example


We have the following "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select the length of the values in the "Address" column above. We use the following SELECT statement: SELECT LEN(Address) as LengthOfAddress FROM Persons The result-set will look like this: LengthOfAddress 12 9 9

SQL ROUND() Function


The ROUND() function is used to round a numeric field to the number of decimals specified.
91

SQL ROUND() Syntax


SELECT ROUND(column_name,decimals) FROM table_name Parameter column_name decimals Description Required. The field to round. Required. Specifies the number of decimals to be returned.

SQL ROUND() Example


We have the following "Products" table: Prod_Id 1 2 3 ProductName Jarlsberg Mascarpone Gorgonzola Unit 1000 g 1000 g 1000 g UnitPrice 10.45 32.56 15.67

Now we want to display the product name and the price rounded to the nearest integer. We use the following SELECT statement: SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10 33 16

92

SQL NOW() Function


The NOW() Function
The NOW() function returns the current system date and time.

SQL NOW() Syntax


SELECT NOW() FROM table_name

SQL NOW() Example


We have the following "Products" table: Prod_Id 1 2 3 ProductName Jarlsberg Mascarpone Gorgonzola Unit 1000 g 1000 g 1000 g UnitPrice 10.45 32.56 15.67

Now we want to display the products and prices per today's date. We use the following SELECT statement: SELECT ProductName, UnitPrice, Now() as PerDate FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.45 32.56 15.67 PerDate 10/7/2008 11:25:02 AM 10/7/2008 11:25:02 AM 10/7/2008 11:25:02 AM

SQL FORMAT() Function


93

The FORMAT() Function


The FORMAT() function is used to format how a field is to be displayed.

SQL FORMAT() Syntax


SELECT FORMAT(column_name,format) FROM table_name Parameter column_name format Description Required. The field to be formatted. Required. Specifies the format.

SQL FORMAT() Example


We have the following "Products" table: Prod_Id 1 2 3 ProductName Jarlsberg Mascarpone Gorgonzola Unit 1000 g 1000 g 1000 g UnitPrice 10.45 32.56 15.67

Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD"). We use the following SELECT statement: SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.45 32.56 15.67 PerDate 2008-10-07 2008-10-07 2008-10-07

94

SQL Quick Reference From W3Schools


SQL Statement AND / OR ALTER TABLE Syntax SELECT column_name(s) FROM table_name WHERE condition AND|OR condition ALTER TABLE table_name ADD column_name datatype or ALTER TABLE table_name DROP COLUMN column_name SELECT column_name AS column_alias FROM table_name or SELECT column_name FROM table_name AS table_alias

AS (alias)

BETWEEN

SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

CREATE DATABASE CREATE DATABASE database_name CREATE TABLE CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name2 data_type, ... ) CREATE INDEX index_name ON table_name (column_name) or CREATE UNIQUE INDEX index_name ON table_name (column_name) CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition DELETE FROM table_name WHERE some_column=some_value

CREATE INDEX

CREATE VIEW

DELETE

95

or DELETE FROM table_name (Note: Deletes the entire table!!) DELETE * FROM table_name (Note: Deletes the entire table!!) DROP DATABASE database_name DROP INDEX table_name.index_name (SQL Server) DROP INDEX index_name ON table_name (MS Access) DROP INDEX index_name (DB2/Oracle) ALTER TABLE table_name DROP INDEX index_name (MySQL) DROP TABLE table_name SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name 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 SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..) INSERT INTO table_name VALUES (value1, value2, value3,....) or INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....) SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

DROP DATABASE DROP INDEX

DROP TABLE GROUP BY

HAVING

IN

INSERT INTO

INNER JOIN

LEFT JOIN

RIGHT JOIN

96

FULL JOIN

SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC] SELECT column_name(s) FROM table_name SELECT * FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT * INTO new_table_name [IN externaldatabase] FROM old_table_name or SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name

LIKE ORDER BY SELECT SELECT * SELECT DISTINCT SELECT INTO

SELECT TOP

SELECT TOP number|percent column_name(s) FROM table_name SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 UPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value SELECT column_name(s) FROM table_name WHERE column_name operator value

TRUNCATE TABLE TRUNCATE TABLE table_name UNION

UNION ALL

UPDATE

WHERE

Source : http://www.w3schools.com/sql/sql_quickref.asp

SQL Hosting
97

SQL Hosting
If you want your web site to be able to store and display data from a database, your web server should have access to a database system that uses the SQL language. If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans. The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access. You can have SQL databases on both Windows and Linux/UNIX operating systems. Below is an overview of which database system that runs on which OS. MS SQL Server Runs only on Windows OS. MySQL Runs on both Windows and Linux/UNIX operating systems. MS Access (recommended only for small websites) Runs only on Windows OS. To learn more about web hosting, please visit our Hosting tutorial.

You Have Learned SQL, Now What?


SQL Summary
This SQL tutorial has taught you the standard computer language for accessing and manipulating database systems. You have learned how to execute queries, retrieve data, insert new records, delete records and update records in a database with SQL. You have also learned how to create databases, tables, and indexes with SQL, and how to drop them. You have learned the most important aggregate functions in SQL. You now know that SQL is the standard language that works with all the well-known database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and MS Access.

Now You Know SQL, What's Next?


Our recommendation is to learn about ADO or PHP MySQL. If you want to learn more about ADO, please visit our ADO tutorial. If you want to learn more about MySQL, please visit our PHP tutorial.

98

Potrebbero piacerti anche