Top Banner
2010 SQL Tutorial 1
135
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SQL Tutorial English-PDF

2010SQL Tutorial

Transcrito por Braulio, From W3SChools

SQL Developers

12/03/2010

1

Page 2: SQL Tutorial English-PDF

S QL T utor ial

SQL Basic

SQL es un lenguaje estándar para acceder a bases de datos.Nuestro manual de SQL le enseñará cómo utilizar SQL para acceder y manipular datos en:MySQL, SQL Server, Access, Oracle, Sybase, DB2, y otros sistemas de base de datos.

2

Page 3: SQL Tutorial English-PDF

Introducción a SQLSQL es un lenguaje estándar 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) estándar

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

SQL es un estándar - pero ....Aunque SQL es un ANSI (American National Standards Institute) estándar, hay muchas versiones diferentes del lenguaje SQL.Sin embargo, para ser compatible con el estándar ANSI, que todo el apoyo por lo menos los comandos principales (tales como SELECT, UPDATE, DELETE, INSERT, WHERE) de una manera similar.Nota: La mayoría de los programas de base de datos de SQL también tienen sus propias extensiones propietarias además del estándar SQL!0

Uso de SQL en su sitio webPara 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

RDBMSRDBMS es sinónimo 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 colección de entradas de datos relacionados y se compone de columnas y filas.

3

Page 4: SQL Tutorial English-PDF

SQL SintaxisTablas de base de datosUna base de datos lo más a menudo contiene una o más tablas. Cada tabla se identifica por un nombre (por ejemplo, "clientes" o "pedidos"). Las tablas contienen registros (filas) con los datos.

A continuación se muestra un ejemplo de una tabla llamada "Personas":P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

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

Sentencias SQLLa mayoría de las acciones que debe realizar en una base de datos se hace con las sentencias SQL.La siguiente instrucción SQL selecciona todos los registros de las "Personas" tabla:

SELECT * FROM Persons

En este tutorial te enseñará todo acerca de las diferentes sentencias SQL.

Tenga en cuenta que ... SQL no es sensible a mayúsculas ni minúsculas.

Punto y coma después 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 estándar para separar cada sentencia de SQL en sistemas de bases de datos que permiten más 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 después de cada sentencia SQL, pero algunos programas de bases de datos obligan a usarlo.

SQL DML y DDLSQL se pueden dividir en dos partes: el lenguaje de manipulación de datos (DML) y el Data Definición Lenguaje (DDL).La consulta y comandos de actualización 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. También se definen los

4

Page 5: SQL Tutorial English-PDF

índices (llaves), especificar los vínculos entre las tablas, e imponer restricciones entre las tablas. Las instrucciones de DDL más 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 instrucción SELECT de SQLLa 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 SintaxisSELECT column_name(s) FROM table_name

and

SELECT * FROM table_name

Nota: SQL no distingue entre mayúsculas y minúsculas. SELECT es lo mismo que select.

Un ejemplo SQL SELECT

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Ahora queremos seleccionar el contenido de las columnas denominadas "Apellido" y "Nombre" de la tabla anterior.

5

Page 6: SQL Tutorial English-PDF

Nosotros utilizamos la siguiente sentencia SELECT:SELECT LastName,FirstName FROM Persons

El conjunto de resultados se verá así:

LastName FirstName

Hansen Ola

Svendson Tove

Pettersen Kari

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

SELECT * FROM Persons

Consejo: El asterisco (*) es una forma rápida de seleccionar todas las columnas!El conjunto de resultados se verá así:P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

La navegación en un conjunto de resultadosLa mayoría de los sistemas de software de bases de datos permiten la navegación en el conjunto de resultados con funciones de programación, tales como: movimiento-hasta el primer registro, Get-Content-Registro, de movimiento al siguiente-Record, etcFunciones de programación, como no se trata de una parte de este tutorial. Para obtener información sobre cómo acceder a los datos con llamadas a funciones, por favor visite nuestra ADO tutorial o nuestro tutorial PHP .

SQL SELECT DISTINCT Declaración6

Page 7: SQL Tutorial English-PDF

En este capítulo se explicará la instrucción SELECT DISTINCT.

El SQL SELECT DISTINCT DeclaraciónEn una tabla, algunas de las columnas pueden contener valores duplicados. Esto no es un problema, sin embargo, a veces se quiere mostrar sólo las diferentes (distintos) en una tabla de valores.La palabra clave DISTINCT se puede utilizar para devolver los valores sólo distintos (diferentes).

SQL SELECT DISTINCT Sintaxis

SELECT DISTINCT column_name(s) FROM table_name

SELECT DISTINCT Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Ahora queremos seleccionar sólo 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:

CitySandnes

Stavanger

7

Page 8: SQL Tutorial English-PDF

SQL WHERE Clause

La cláusula WHERE se utiliza para filtrar los registros.

La cláusula WHERE La cláusula WHERE se utiliza para extraer sólo aquellos registros que cumplan un criterio determinado.

WHERE de SQL SintaxisSELECT column_name(s) FROM table_nameWHERE column_name = operator value

WHERE Clause Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Ahora queremos seleccionar sólo 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

8

Page 9: SQL Tutorial English-PDF

Quotes Around Text Fields

SQL usa comillas simples alrededor de valores de texto (la mayoría de los sistemas de base de datos también se aceptan comillas dobles).Aunque, los valores numéricos 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 cláusula WHERE

Con la cláusula WHERE, los operadores pueden utilizar los siguientes:

Operator Description

= Igual

<> No igual

> Mayor que

< Menor que

>= Mayor o igual que

<= Menor o igual que

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN 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 =!

9

Page 10: SQL Tutorial English-PDF

SQL AND & OR Operadores

La AND & OR operadores se utilizan para filtrar los registros basados en más de una condición.

La AND & OR OperadoresEl operador AND muestra un registro si tanto la primera condición y la segunda condición es verdadera.El operador OR muestra un registro, si bien la condición de primer o la segunda condición es verdadera.

AND Operadores Ejemplos

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Ahora queremos seleccionar sólo 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 LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

10

Page 11: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

Operador OR Ejemplo

Ahora queremos seleccionar sólo 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

La combinación de AND & ORTambién se pueden combinar AND y OR (utilizar paréntesis para formar expresiones complejas).Ahora queremos seleccionar sólo 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í:

11

Page 12: SQL Tutorial English-PDF

SQL ORDER BY Palabra clave

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

La palabra clave ORDER BYLa 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 SintaxisSELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

ORDER BY Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

4 Nilsen Tom Vingvn 23 Stavanger

3 Pettersen Kari Storgt 20 Stavanger

2 Svendson Tove Borgvn 23 Sandnes

12

Page 13: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

1 Hansen Ola Timoteivn 10 Sandnes

ORDER BY DESC Ejemplo

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í:

SQL INSERT INTO SentenciaLa instrucción INSERT INTO se utiliza para insertar nuevos registros en una tabla.

La instrucción INSERT INTOLa instrucción INSERT INTO se utiliza para insertar una nueva fila en una tabla.

SQL INSERT INTO Sintaxis

Es posible escribir la instrucción INSERT INTO en dos formas.La primera forma no especifica los nombres de columna en la que los datos se insertan, sólo sus valores:

INSERT INTO table_nameVALUES (value1, value2, value3,...)

La segunda forma específica 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

13

Page 14: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

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

INSERT INTO PersonsVALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

The "Persons" table will now look like this:

Introduzca los datos sólo en las columnas especificadasTambién es posible añadir sólo los datos en columnas específicas.La siguiente sentencia SQL se añade una nueva fila, pero sólo añadir 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob

14

Page 15: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob Nissestien 67 Sandnes

SQL UPDATE StatementLa instrucción UPDATE se utiliza para actualizar los registros en una tabla.

La instrucción UPDATELa instrucción UPDATE se utiliza para actualizar los registros existentes en una tabla.SQL UPDATE Sintaxis

UPDATE nombre_tablaSET column1=value, column2=value2,... WHERE some_column=some_value

Nota: Observe la cláusula WHERE en la sintaxis de UPDATE. La cláusula WHERE especifica qué registros o registros que deben ser actualizadas. Si se omite la cláusula WHERE, todos los registros serán actualizados!

SQL UPDATE Ejemplo

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob

Ahora queremos poner al día la persona "Tjessem, Jakob" en las "Personas" tabla.Nosotros utilizamos la siguiente instrucción:

UPDATE PersonsSET Address='Nissestien 67', City='Sandnes'WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:

15

Page 16: SQL Tutorial English-PDF

Advertencia de actualización de SQLTenga cuidado al actualizar los registros. Si se había omitido la cláusula WHERE en el ejemplo anterior, así:

UPDATE Persons SET Address='Nissestien 67', City='Sandnes'

The "Persons" table would have looked like this:

P_Id LastName FirstName Address City

1 Hansen Ola Nissestien 67 Sandnes

2 Svendson Tove Nissestien 67 Sandnes

3 Pettersen Kari Nissestien 67 Sandnes

4 Nilsen Johan Nissestien 67 Sandnes

5 Tjessem Jakob Nissestien 67 Sandnes

16

Page 17: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

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

La instrucción DELETELa sentencia DELETE se utiliza para eliminar filas de una tabla.

SQL DELETE SintaxisDELETE FROM nombre_tabla WHERE some_column=some_value

Nota: Observe la cláusula WHERE en la sintaxis de DELETE. La cláusula WHERE especifica qué registros o registros que se deben eliminar. Si se omite la cláusula WHERE, todos los registros serán borrados!

SQL DELETE Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob Nissestien 67 Sandnes

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

DELETE FROM PersonsWHERE LastName='Tjessem' AND FirstName='Jakob'

"Personas" tabla ahora se verá así:

17

Page 18: SQL Tutorial English-PDF

Eliminar todas las filasEs 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 orDELETE * FROM table_name

Nota: Tenga mucho cuidado al eliminar registros. No se puede deshacer esta declaración!

18

Page 19: SQL Tutorial English-PDF

SQL Advanced

SQL TOP Clause

La cláusula TOPLa cláusula TOP se utiliza para especificar el número de registros para volver.La cláusula TOP puede ser muy útil en tablas grandes con miles de registros. La devolución de un gran número de registros puede tener un impacto en el rendimiento.

Nota: No todos los sistemas de bases de datos apoyan la cláusula TOP.

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

SQL SELECT TOP equivalente en MySQL y Oracle

MySQL SintaxisSELECT nombre_columna(s) FROM nombre_tabla LIMIT number

EjemploSELECT * FROM Persons LIMIT 5

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

EjemploSELECT * FROM Persons WHERE ROWNUM <=5

19

Page 20: SQL Tutorial English-PDF

SQL TOP Ejemplo

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

Ahora queremos seleccionar sólo 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

SQL TOP PERCENT Ejemplo

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

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

SELECT TOP 50 PERCENT * FROM PersonsThe result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

20

Page 21: SQL Tutorial English-PDF

SQL LIKE OperadorEl operador LIKE se utiliza en una cláusula WHERE para buscar un patrón específico en una columna.

El operador LIKEEl operador LIKE se utiliza para la búsqueda de un patrón específico 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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 patrón), tanto antes como después de que el patrón.El conjunto de resultados se verá así:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

21

Page 22: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

A continuación, 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

A continuación, 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 LastName FirstName Address City

3 Pettersen Kari Storgt 20 Stavanger

También 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í:

22

Page 23: SQL Tutorial English-PDF

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

SQL comodines Comodines SQL puede sustituir a uno o más personajes en la búsqueda 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:

Comodín Descripción

% A substitute for zero or more characters

_ A substitute for exactly one character

[charlist] Any single character in charlist

[^charlist]

or

[!charlist]

Any single character not in charlist

SQL Wildcard Ejemplos

Tenemos lo siguiente "Personas" tabla:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Utilizando el comodín %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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

A continuación, 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:

23

Page 24: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

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

El conjunto de resultados se verá así:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

Usando el comodín _Ahora queremos seleccionar a las personas con un nombre que comience con cualquier carácter, 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í:

A continuación, queremos seleccionar a las personas con un apellido que comienza con "S", seguida de cualquier carácter, seguido de "final", seguida de cualquier carácter, 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

Utilizando los botones [charlist] comodínAhora 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:

A continuación, 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:

24

Page 25: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL IN Operator

El operador INEl operador IN le permite especificar varios valores en una cláusula 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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:

25

Page 26: SQL Tutorial English-PDF

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL BETWEEN OperadorEl operador BETWEEN se utiliza en una cláusula WHERE para seleccionar un rango de datos entre dos valores.

El operador BETWEENEl operador BETWEEN selecciona un rango de datos entre dos valores. Los valores pueden ser números, texto o fechas.

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

BETWEEN Operator EjemploThe "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Ahora queremos seleccionar a las personas con el apellido en orden alfabético 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:

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 sólo selecciona los campos que se encuentran entre los valores y la exclusión 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: Comprobación de la base de datos trata el operador BETWEEN.

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

The result-set will look like this:

26

Page 27: SQL Tutorial English-PDF

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

SQL AliasUsted 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 TablesSELECT nombre_columna(s) FROM nombre_tablaAS nombre_alias

SQL Alias Syntax for ColumnsSELECT nombre_columna AS nombre_aliasFROM 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.FirstNameFROM Persons AS p, Product_Orders AS poWHERE p.LastName='Hansen' AND p.FirstName='Ola'

The same SELECT statement without aliases:

SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstNameFROM Persons, Product_OrdersWHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'

Como se verá a partir de las dos sentencias SELECT anterior; alias pueden realizar consultas más fáciles tanto para escribir y leer.

27

Page 28: SQL Tutorial English-PDF

SQL Joins

Uniones SQL se utilizan para consultar datos de dos o más tablas, sobre la base de una relación entre ciertas columnas en estas tablas.

SQL JOINLa palabra clave JOIN se utiliza en una sentencia SQL para consultar datos de dos o más tablas, sobre la base de una relación entre ciertas columnas en estas tablas.Las tablas de una base de datos a menudo están relacionados el uno al otro con las llaves.Una clave principal es una columna (o una combinación de columnas) con un valor único para cada fila. Cada valor de clave principal debe ser único dentro de la tabla. El propósito es enlazar los datos en conjunto, a través de tablas, sin repetir todos los datos en cada tabla.Mira las "Personas" tabla:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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 continuación, tenemos la tabla "orders":O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 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 relación entre las dos tablas anteriores es el "p_id" de la columna

28

Page 29: SQL Tutorial English-PDF

Different SQL JOINs

Antes de continuar con los ejemplos, vamos a enumerar los tipos de unión 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_tabla2ON 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

29

Page 30: SQL Tutorial English-PDF

5 34764 15

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

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 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.

30

Page 31: SQL Tutorial English-PDF

SQL LEFT JOIN Keyword

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 SintaxisSELECT nombre_columna(s) FROM nombre_tabla1LEFT JOIN nombre_tabla2ON 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 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.OrderNoFROM Persons LEFT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName

The result-set will look like this:

31

Page 32: SQL Tutorial English-PDF

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

Svendson Tove

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 JOINSELECT nombre_columna(s) FROM nombre_tabla1RIGHT JOIN nombre_tabla2ON 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 FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

32

Page 33: SQL Tutorial English-PDF

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.OrderNoFROM PersonsRIGHT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 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_tabla1FULL JOIN nombre_tabla2ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna

33

Page 34: SQL Tutorial English-PDF

SQL FULL JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 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.OrderNoFROM PersonsFULL JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

Svendson Tove

34764

34

Page 35: SQL Tutorial English-PDF

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 también.

SQL UNION Operador

El operador de SQL UNION combina dos o más instrucciones SELECT.

El operador UNION SQLEl operador UNION se utiliza para combinar el conjunto de resultados de dos o más sentencias SELECT.Observe que cada instrucción SELECT dentro de la Unión deben tener el mismo número de columnas. Las columnas también deben tener tipos de datos similares. Además, las columnas de cada instrucción SELECT debe ir en el mismo orden.

Sintaxis SQL UNIONSELECT nombre_columna(s) FROM nombre_tabla1UNIONSELECT nombre_columna(s) FROM nombre_tabla2

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

SQL UNION ALL SyntaxSELECT nombre_columna(s) FROM nombre_tabla1UNION ALLSELECT 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 instrucción SELECT de la UNION.

SQL UNION EjemploLook at the following tables:

"Employees_Norway":

E_ID E_Name

01 Hansen, Ola

02 Svendson, Tove

03 Svendson, Stephen

04 Pettersen, Kari

35

Page 36: SQL Tutorial English-PDF

E_Name

Hansen, Ola

Svendson, Tove

Svendson, Stephen

Pettersen, Kari

Turner, Sally

Kent, Clark

Scott, Stephen

"Employees_USA":

E_ID E_Name

01 Turner, Sally

02 Kent, Clark

03 Svendson, Stephen

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_NorwayUNIONSELECT E_Name FROM Employees_USA The result-set will look like this:

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 sólo uno de ellos se enumeran.El comando UNION sólo selecciona valores distintos.

36

Page 37: SQL Tutorial English-PDF

SQL UNION ALL EjemploAhora queremos a la lista de todos los empleados en Noruega y EE.UU.:SELECT E_Name FROM Employees_NorwayUNION ALLSELECT 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 INTOLa instrucción SELECT INTO selecciona datos de una tabla y lo inserta en una tabla diferente.La instrucción SELECT INTO se utiliza con mayor frecuencia para crear copias de seguridad de las tablas.SQL SELECT en la sintaxisPodemos seleccionar todas las columnas en la nueva tabla:SELECT * INTO nombre_tabla_nueva [IN externaldatabase] FROM nombre_tabla_vieja

O se puede seleccionar sólo 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 instrucción:SELECT * INTO Persons_BackupFROM Persons

37

Page 38: SQL Tutorial English-PDF

También podemos utilizar la cláusula IN para copiar la tabla en otra base de datos:SELECT * INTO Persons_Backup IN 'Backup.mdb' FROM Persons

También puede copiar sólo unos pocos campos en la nueva tabla:

SELECT LastName,FirstNameINTO Persons_BackupFROM Persons

SQL SELECT INTO - With a WHERE Clause

También puede agregar una cláusula WHERE.La siguiente sentencia SQL crea una "Persons_Backup" tabla con sólo las personas que vive en la ciudad "Sandnes":

SELECT LastName,Firstname INTO Persons_BackupFROM PersonsWHERE City = 'Sandnes'

SQL SELECT INTO - tablas combinadasSelección de los datos de más de una tabla también 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.OrderNoINTO Persons_Order_BackupFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_Id

SQL CREATE DATABASE Sentencia

The CREATE DATABASE Statement

La instrucción CREATE DATABASE se utiliza para crear una base de datos.

SQL CREATE DATABASE SyntaxCREATE DATABASE database_name

38

Page 39: SQL Tutorial English-PDF

CREATE DATABASE Example

Ahora queremos crear una base de datos llamada "my_db".Nosotros utilizamos la siguiente instrucción 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

Page 40: SQL Tutorial English-PDF

CREATE TABLE EjemploAhora queremos crear una tabla llamada "Personas", que contiene cinco columnas: p_id, Apellidos, Dirección 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 número. El Apellido, Nombre, Dirección, y las columnas de la ciudad son de tipo varchar con una longitud máxima de 255 caracteres.El vacío "Personas" tabla ahora se verá así:

P_Id LastName FirstName Address City

La tabla de vacío puede ser llenada con los datos con la instrucción INSERT INTO.

SQL ConstraintsLas 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 después de crear la tabla (con la instrucción ALTER TABLE).Nos centraremos en las siguientes restricciones:

NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT

Los siguientes capítulos se describen cada una restricción en detalle.

40

Page 41: SQL Tutorial English-PDF

SQL NOT NULL ConstraintDe manera predeterminada, una columna de tabla puede contener valores NULL.

SQL NOT NULL Constraint

La restricción NOT NULL cumplir una columna para que no acepte valores NULL.La restricción 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 añadir 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 ConstraintLa restricción UNIQUE identifica de forma única cada registro de una tabla de base de datos.Las restricciones UNIQUE y PRIMARY KEY tanto una garantía de la unicidad de una columna o conjunto de columnas.Una restricción PRIMARY KEY, automáticamente tiene una restricción UNIQUE definidos en él.Tenga en cuenta que puede tener muchas restricciones UNIQUE por tabla, pero sólo una restricción PRIMARY KEY por cada tabla.

SQL UNIQUE Constraint on CREATE TABLE

El siguiente SQL crea una restricción 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))

41

Page 42: SQL Tutorial English-PDF

SQL Server / Oracle / MS Access: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 designación de una restricción UNIQUE, y para definir una restricción 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 restricción 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 designación de una restricción UNIQUE, y para definir una restricción 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 Constraint42

Page 43: SQL Tutorial English-PDF

Para eliminar una restricción 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 ConstraintLa restricción 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 sólo 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 designación de una restricción PRIMARY KEY, y para definir una restricción PRIMARY

43

Page 44: SQL Tutorial English-PDF

KEY 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 pk_PersonID PRIMARY KEY (P_Id,LastName))

Nota: En el ejemplo anterior sólo 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 restricción 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 PersonsADD PRIMARY KEY (P_Id)

Para permitir la designación de una restricción PRIMARY KEY, y para definir una restricción PRIMARY KEY en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

Note: Si utiliza la instrucción 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

44

Page 45: SQL Tutorial English-PDF

Para eliminar una restricción PRIMARY KEY, utilice las siguientes instrucciones:

MySQL:ALTER TABLE PersonsDROP PRIMARY KEY

SQL Server / Oracle / MS Access:ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY ConstraintUna clave foránea 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 2

4 24562 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 restricción FOREIGN KEY se utiliza para evitar acciones que pudieran destruir los vínculos entre las tablas.La restricción de clave externa también impide que los datos no válidos 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

45

Page 46: SQL Tutorial English-PDF

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

MySQL:

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 designación de una restricción FOREIGN KEY, y para la definición de una restricción 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

Page 47: SQL Tutorial English-PDF

SQL FOREIGN KEY Constraint on ALTER TABLE

Para crear una restricción 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 OrdersADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

Para permitir la designación de una restricción FOREIGN KEY, y para la definición de una restricción FOREIGN KEY de varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE OrdersADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint

Para eliminar una restricción FOREIGN KEY, utilice el siguiente SQL:

MySQL:

ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrders

SQL Server / Oracle / MS Access:

ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders

47

Page 48: SQL Tutorial English-PDF

SQL CHECK ConstraintLa restricción CHECK se utiliza para limitar el rango de valores que se pueden colocar en una columna.Si se define una restricción CHECK en una columna que sólo permite ciertos valores para esta columna.Si se define una restricción 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 restricción CHECK en el "p_id" columna cuando las "personas" se crea la tabla. La restricción CHECK especifica que la columna "p_id" sólo pueden ser números 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 designación de una restricción CHECK, y para definir una restricción 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'))

48

Page 49: SQL Tutorial English-PDF

SQL CHECK Constraint on ALTER TABLE

Para crear una restricción 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 PersonsADD CHECK (P_Id>0)

Para permitir la designación de una restricción CHECK, y para definir una restricción CHECK en varias columnas, utilice la siguiente sintaxis SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE PersonsADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint

Para eliminar una restricción CHECK, utilice las siguientes instrucciones:

SQL Server / Oracle / MS Access:

ALTER TABLE PersonsDROP CONSTRAINT chk_Person

49

Page 50: SQL Tutorial English-PDF

SQL DEFAULT ConstraintLa restricción DEFAULT se utiliza para insertar un valor predeterminado en una columna.El valor por defecto será añadido a todos los nuevos registros, si no hay otro valor especificado.

SQL restricción DEFAULT en CREATE TABLEEl siguiente SQL crea una restricción 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 restricción DEFAULT también 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 restricción DEFAULT en la "City" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:

MySQL:ALTER TABLE PersonsALTER City SET DEFAULT 'SANDNES'

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

To DROP a DEFAULT ConstraintPara eliminar una restricción DEFAULT, utilice las siguientes instrucciones:

MySQL:ALTER TABLE PersonsALTER City DROP DEFAULT

50

Page 51: SQL Tutorial English-PDF

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

SQL CREATE INDEX Statement

La instrucción CREATE INDEX se utiliza para crear índices de las tablas.Índices permiten la aplicación de base de datos para encontrar rápidamente los datos, sin necesidad de leer toda la tabla.

ÍndicesUn índice se puede crear en una tabla para encontrar datos más rápido y eficaces.Los usuarios no pueden ver los índices, que son utilizados para acelerar las búsquedas / consultas.Nota: Actualizando una tabla con los índices lleva más tiempo que la actualización de una tabla sin (ya que los índices también se necesita una actualización). Por lo que sólo debe crear índices en columnas (y tablas) que con frecuencia se realizaron búsquedas en contra

SQL CREATE INDEX SyntaxCreates an index on a table. Duplicate values are allowed: CREATE INDEX index_nameON table_name (column_name)

SQL CREATE UNIQUE INDEX SyntaxCrea un índice en una tabla. Los valores duplicados están permitidos: CREATE UNIQUE INDEX index_nameON table_name (column_name)

Note: La sintaxis para la creación de índices varía entre diferentes bases de datos. Por lo tanto: Compruebe la sintaxis para la creación 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 PIndexON Persons (LastName)

Si desea crear un índice en una combinación de columnas, se pueden listar los nombres de columna entre paréntesis, separados por comas:

CREATE INDEX PIndexON Persons (LastName, FirstName)

51

Page 52: SQL Tutorial English-PDF

SQL DROP INDEX, DROP TABLE, and DROP DATABASE

Índices, tablas y bases de datos pueden ser fácilmente eliminadas / elimina con la sentencia DROP.

The DROP INDEX Statement

La instrucción 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

Page 53: SQL Tutorial English-PDF

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 SyntaxTo add a column in a table, use the following syntax: ALTER TABLE table_nameADD 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_nameDROP COLUMN column_name

To change the data type of a column in a table, use the following syntax: ALTER TABLE table_nameALTER COLUMN column_name datatype

53

Page 54: SQL Tutorial English-PDF

SQL ALTER TABLE Example

Look at the "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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 typespecifies what type of data the column can hold. For a complete reference of all the data types available inMS Access, MySQL, and SQL Server, go to our complete D a t a T y p e s r e f e r enc e .

The "Persons" table will now like this:

P_Id LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

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 four- digit format.

54

Page 55: SQL Tutorial English-PDF

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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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),

55

Page 56: SQL Tutorial English-PDF

PRIMARY KEY (P_Id))

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" columnwould 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 toIDENTITY(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)

56

Page 57: SQL Tutorial English-PDF

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" columnwould be set to "Monsen".

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 toAUTOINCREMENT(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" columnwould 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_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10

57

Page 58: SQL Tutorial English-PDF

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. Itwill also cache up to 10 values for performance. The cache option specifies how many sequence values willbe 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):

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 SyntaxCREATE VIEW view_name AS SELECT column_name(s)FROM table_nameWHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQLstatement, 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:

58

Page 59: SQL Tutorial English-PDF

CREATE VIEW [Current Product List] AS SELECT ProductID,ProductNameFROM ProductsWHERE Discontinued=No

We can query the view above as follows: SELECT * FROM [Current Product List]

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,UnitPriceFROM Products

59

Page 60: SQL Tutorial English-PDF

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] ASSELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySalesFROM [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 SyntaxCREATE OR REPLACE VIEW view_name AS SELECT column_name(s)FROM table_nameWHERE 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 ProductsWHERE Discontinued=No

SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW SyntaxDROP VIEW view_name

60

Page 61: SQL Tutorial English-PDF

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 Description

NOW() Returns the current date and time CURDATE() Returns the current date CURTIME() Returns the current timeDATE() Extracts the date part of a date or date/time expression

EXTRACT() Returns a single part of a date/time DATE_ADD() Adds a specified time interval to a date DATE_SUB() Subtracts a specified time interval from a dateDATEDIFF() Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats

61

Page 62: SQL Tutorial English-PDF

SQL Server Date Functions

The following table lists the most important built-in date functions in SQL Server:

Function Description

GETDATE() Returns the current date and time

DATEPART() Returns a single part of a date/time

DATEADD() Adds or subtracts a specified time interval from a date

DATEDIFF() Returns the time between two dates

CONVERT() 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 D a t a T y p es r e f e r en c e .

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 Geitost 2008-11-11

2 Camembert Pierrot 2008-11-09

3 Mozzarella di Giovanni 2008-11-11

4 Mascarpone Fabioli 2008-10-29

62

Page 63: SQL Tutorial English-PDF

OrderId ProductName OrderDate

1 Geitost 2008-11-11

3 Mozzarella di Giovanni 2008-11-11

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:

Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column):

OrderId ProductName OrderDate

1 Geitost 2008-11-11 13:23:44

2 Camembert Pierrot 2008-11-09 15:45:21

3 Mozzarella di Giovanni 2008-11-11 11:12:01

4 Mascarpone Fabioli 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

Page 64: SQL Tutorial English-PDF

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 LastName FirstName Address City

1 Hansen Ola Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Stavanger

Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a recordwith 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

Page 65: SQL Tutorial English-PDF

LastName FirstName Address

Svendson Tove Borgvn 23

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 PersonsWHERE Address IS NULL

The result-set will look like this:

LastName FirstName Address

Hansen Ola

Pettersen Kari

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 PersonsWHERE Address IS NOT NULL The result-set will look like this:

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

65

Page 66: SQL Tutorial English-PDF

SQL NULL Functions

SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions

Look at the following "Products" table:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder

1 Jarlsberg 10.45 16 15

2 Mascarpone 32.56 23

3 Gorgonzola 15.67 9 20

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

Page 67: SQL Tutorial English-PDF

MySQL

MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft'sISNULL() 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

Page 68: SQL Tutorial English-PDF

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

Microsoft Access Data Types

Data type Description Storage

Text Use for text or combinations of text and numbers. 255characters maximum

Memo 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

Byte Allows whole numbers from 0 to 255 1 byte

Integer Allows whole numbers between -32,768 and 32,767 2 bytes

Long Allows whole numbers between -2,147,483,648 and2,147,483,647

4 bytes

Single Single precision floating-point. Will handle most decimals 4 bytes

Double Double precision floating-point. Will handle most decimals 8 bytes

Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4decimal places. Tip: You can choose which country's currency to use

8 bytes

AutoNumber AutoNumber fields automatically give each record its own number, usually starting at 1

4 bytes

Date/Time Use for dates and times 8 bytes

Yes/No A logical field can be displayed as Yes/No, True/False, orOn/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/Nofields

1 bit

Ole Object Can store pictures, audio, video, or other BLOBs (BinaryLarge OBjects)

up to1GB

Hyperlink Contain links to other files, including web pages

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

4 bytes

68

Page 69: SQL Tutorial English-PDF

MySQL Data Types

In MySQL there are three main types : text, number, and Date/Time types.

Text types:

Data type Description

CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to255 characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store upto 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT Holds a string with a maximum length of 65,535 characters

BLOB 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 Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB 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 valuewill 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

Page 70: SQL Tutorial English-PDF

Data type Description

TINYINT(size) -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) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis

BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis

FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximumnumber of digits to the right of the decimal point is specified in the d parameter

DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximumnumber of digits to the right of the decimal point is specified in the d parameter

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 sizeparameter. 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 topositive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number.

70

Page 71: SQL Tutorial English-PDF

Data type Description

DATE() 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-3123: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: YYYY-MM-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 allowedin 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 INSERTor UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.

71

Page 72: SQL Tutorial English-PDF

SQL Server Data Types

Character strings:

Data type Description Storage

char(n) Fixed-length character string. Maximum 8,000 characters n

varchar(n) Variable-length character string. Maximum 8,000 characters

varchar(max) Variable-length character string. Maximum 1,073,741,824characters

text Variable-length character string. Maximum 2GB of text data

Unicode strings:

Data type Description Storage

nchar(n) Fixed-length Unicode data. Maximum 4,000 characters

nvarchar(n) Variable-length Unicode data. Maximum 4,000 characters

nvarchar(max) Variable-length Unicode data. Maximum 536,870,912characters

ntext Variable-length Unicode data. Maximum 2GB of text data

Binary types:

Data type Description Storage

bit Allows 0, 1, or NULL

binary(n) Fixed-length binary data. Maximum 8,000 bytes

varbinary(n) Variable-length binary data. Maximum 8,000 bytes

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

image Variable-length binary data. Maximum 2GB

72

Page 73: SQL Tutorial English-PDF

Number types:

Data type Description Storage

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and2,147,483,647

4 bytes

bigint Allows whole numbers between -9,223,372,036,854,775,808and 9,223,372,036,854,775,807

8 bytes

decimal(p,s) 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 thedecimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digitsstored to the right of the decimal point. s must be a value from0 to p. Default value is 0

5-17bytes

numeric(p,s) 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 thedecimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digitsstored to the right of the decimal point. s must be a value from0 to p. Default value is 0

5-17bytes

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to922,337,203,685,477.5807

8 bytes

float(n) Floating precision number data from -1.79E + 308 to 1.79E +308.

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 8- byte field. Default value of n is 53.

4 or 8bytes

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

4 bytes

73

Page 74: SQL Tutorial English-PDF

Date types:

Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds

8 bytes

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds

6-8 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1minute

4 bytes

date Store a date only. From January 1, 0001 to December 31, 99993 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes

datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10bytes

timestamp 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 Description

sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for database operations

table Stores a result-set for later processing

74

Page 75: SQL Tutorial English-PDF

S QL F un ctio n s

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

Page 76: SQL Tutorial English-PDF

SQL AVG() Function

The AVG() Function

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

SQL AVG() SyntaxSELECT AVG(column_name) FROM table_name

SQL AVG() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

Page 77: SQL Tutorial English-PDF

Customer

Hansen

Nilsen

Jensen

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 OrdersWHERE OrderPrice > (SELECT AVG(OrderPrice) FROM Orders) The result-set will look like this:

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 MicrosoftAccess.

SQL COUNT(column_name) Example

We have the following "Orders" table:

77

Page 78: SQL Tutorial English-PDF

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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 OrdersWHERE 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

Page 79: SQL Tutorial English-PDF

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() SyntaxSELECT FIRST(column_name) FROM table_name

SQL FIRST() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

100079

Page 80: SQL Tutorial English-PDF

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 OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

80

Page 81: SQL Tutorial English-PDF

SQL MAX() FunctionThe 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 OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

Page 82: SQL Tutorial English-PDF

SQL MIN() Function

The MIN() Function

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

SQL MIN() SyntaxSELECT MIN(column_name) FROM table_name

SQL MIN() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

Page 83: SQL Tutorial English-PDF

SQL SUM() Function

The SUM() Function

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

SQL SUM() SyntaxSELECT SUM(column_name) FROM table_name

SQL SUM() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 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

83

Page 84: SQL Tutorial English-PDF

SQL GROUP BY Statement

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 oneor more columns.

SQL GROUP BY SyntaxSELECT column_name, aggregate_function(column_name) FROM table_nameWHERE column_name operator valueGROUP BY column_name

SQL GROUP BY Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

84

Page 85: SQL Tutorial English-PDF

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 OrdersGROUP BY Customer

The result-set will look like this:

Customer SUM(OrderPrice)

Hansen 2000

Nilsen 1700

Jensen 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 SUM(OrderPrice)

Hansen 5700

Nilsen 5700

Hansen 5700

Hansen 5700

Jensen 5700

Nilsen 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 eachrow in the "Orders" table). This will therefore not give us the correct result. However, you have seen that theGROUP BY statement solves this problem.

GROUP BY More Than One ColumnWe can also use the GROUP BY statement on more than one column, like this: SELECT Customer,OrderDate,SUM(OrderPrice) FROM OrdersGROUP BY Customer,OrderDate

85

Page 86: SQL Tutorial English-PDF

SQL HAVING Clause

The HAVING Clause

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

SQL HAVING SyntaxSELECT column_name, aggregate_function(column_name) FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value

SQL HAVING Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

86

Page 87: SQL Tutorial English-PDF

Now we want to find if any of the customers have a total order of less than 2000.We use the following SQLstatement:

SELECT Customer,SUM(OrderPrice) FROM OrdersGROUP BY CustomerHAVING SUM(OrderPrice)<2000

The result-set will look like this:

Customer SUM(OrderPrice)

Nilsen 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 OrdersWHERE Customer='Hansen' OR Customer='Jensen' GROUP BY CustomerHAVING SUM(OrderPrice)>1500

The result-set will look like this:

Customer SUM(OrderPrice)

Hansen 2000

Jensen 2000

87

Page 88: SQL Tutorial English-PDF

88

Page 89: SQL Tutorial English-PDF

SQL UCASE() Function

The UCASE() Function

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

SQL UCASE() SyntaxSELECT UCASE(column_name) FROM table_name

Syntax for SQL ServerSELECT UPPER(column_name) FROM table_name

SQL UCASE() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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 FirstName

HANSEN Ola

SVENDSON Tove

PETTERSEN Kari

89

Page 90: SQL Tutorial English-PDF

SQL LCASE() Function

The LCASE() Function

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

SQL LCASE() SyntaxSELECT LCASE(column_name) FROM table_name

Syntax for SQL ServerSELECT LOWER(column_name) FROM table_name

SQL LCASE() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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 FirstName

hansen Ola

svendson Tove

pettersen Kari

90

Page 91: SQL Tutorial English-PDF

SQL MID() Function

The MID() Function

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

SQL MID() SyntaxSELECT MID(column_name,start[,length]) FROM table_name

Parameter Description

column_name Required. The field to extract characters from

start Required. Specifies the starting position (starts at 1)

length 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 LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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

91

Page 92: SQL Tutorial English-PDF

Stav

SQL LEN() Function

The LEN() Function

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

SQL LEN() SyntaxSELECT LEN(column_name) FROM table_name

SQL LEN() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 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

92

Page 93: SQL Tutorial English-PDF

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

SQL ROUND() SyntaxSELECT ROUND(column_name,decimals) FROM table_name

Parameter Description

column_name Required. The field to round.

decimals Required. Specifies the number of decimals to be returned.

SQL ROUND() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 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 UnitPrice

Jarlsberg 10

Mascarpone 33

Gorgonzola 16

93

Page 94: SQL Tutorial English-PDF

SQL NOW() Function

The NOW() Function

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

SQL NOW() SyntaxSELECT NOW() FROM table_name

SQL NOW() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 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 UnitPrice PerDate

Jarlsberg 10.45 10/7/2008 11:25:02 AM

Mascarpone 32.56 10/7/2008 11:25:02 AM

Gorgonzola 15.67 10/7/2008 11:25:02 AM

94

Page 95: SQL Tutorial English-PDF

SQL FORMAT() Function

The FORMAT() Function

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

SQL FORMAT() SyntaxSELECT FORMAT(column_name,format) FROM table_name

Parameter Description

column_name Required. The field to be formatted.

format Required. Specifies the format.

SQL FORMAT() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 15.67

Now we want to display the products and prices per today's date (with today's date displayed in thefollowing format "YYYY-MM-DD").

We use the following SELECT statement:

SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDateFROM Products

The result-set will look like this:

ProductName UnitPrice PerDate

Jarlsberg 10.45 2008-10-07

Mascarpone 32.56 2008-10-07

Gorgonzola 15.67 2008-10-07

95

Page 96: SQL Tutorial English-PDF

SQL Quick Reference From W3Schools

SQL Statement Syntax

AND / OR SELECT column_name(s) FROM table_name WHERE condition AND|OR condition

ALTER TABLE ALTER TABLE table_name ADD column_name datatype orALTER TABLE table_nameDROP COLUMN column_name

AS (alias) SELECT column_name AS column_aliasFROM table_name orSELECT column_nameFROM table_name AS table_alias

BETWEEN SELECT column_name(s) FROM table_name WHERE column_nameBETWEEN 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 CREATE INDEX index_nameON table_name (column_name)orCREATE UNIQUE INDEX index_nameON table_name (column_name)

CREATE VIEW CREATE VIEW view_name AS SELECT column_name(s)FROM table_nameWHERE condition

DELETE DELETE FROM table_nameWHERE some_column=some_value

96

Page 97: SQL Tutorial English-PDF

or

DELETE FROM table_name(Note: Deletes the entire table!!)

DELETE * FROM table_name(Note: Deletes the entire table!!)

DROP DATABASE DROP DATABASE database_name

DROP INDEX 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_nameDROP INDEX index_name (MySQL)

DROP TABLE DROP TABLE table_name

GROUP BY SELECT column_name, aggregate_function(column_name) FROM table_nameWHERE column_name operator valueGROUP BY column_name

HAVING SELECT column_name, aggregate_function(column_name) FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value

IN SELECT column_name(s) FROM table_name WHERE column_nameIN (value1,value2,..)

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

INNER JOIN SELECT column_name(s) FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name

LEFT JOIN SELECT column_name(s) FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name

RIGHT JOIN SELECT column_name(s) FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name

97

Page 98: SQL Tutorial English-PDF

FULL JOIN SELECT column_name(s) FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name

LIKE SELECT column_name(s) FROM table_nameWHERE column_name LIKE pattern

ORDER BY SELECT column_name(s) FROM table_nameORDER BY column_name [ASC|DESC]

SELECT SELECT column_name(s) FROM table_name

SELECT * SELECT * FROM table_name

SELECT DISTINCT SELECT DISTINCT column_name(s) FROM table_name

SELECT INTO 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

SELECT TOP SELECT TOP number|percent column_name(s) FROM table_name

TRUNCATE TABLE TRUNCATE TABLE table_name

UNION SELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2

UNION ALL SELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2

UPDATE UPDATE table_nameSET column1=value, column2=value,... WHERE some_column=some_value

WHERE SELECT column_name(s) FROM table_nameWHERE column_name operator value

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

98

Page 99: SQL Tutorial English-PDF

SQL Hosting

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 SQLhosting 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 H os ti ng t u t o r i al .

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 likeMS 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 AD O t u t o r i al .If you want to learn more about MySQL, please visit our P H P t u t o r i al .

99