Académique Documents
Professionnel Documents
Culture Documents
SQL Tutorial
Introduccin a SQL
SQL es un lenguaje estndar para acceder y manipular bases de datos.
Qu es SQL?
SQL significa Lenguaje de consulta estructurado SQL le permite acceder y manipular bases de datos SQL es un ANSI (American National Standards Institute) estndar
RDBMS
RDBMS es sinnimo de base de datos relacional. RDBMS es la base de SQL, y para todos los sistemas de bases de datos modernas, como MS SQL Server, IBM DB2, Oracle, MySQL y Microsoft Access. Los datos de RDBMS se almacenan en objetos de base de datos llamada tablas. Una tabla es una coleccin de entradas de datos relacionados y se compone de columnas y filas.
SQL Sintaxis
Tablas de base de datos
Una base de datos lo ms a menudo contiene una o ms tablas. Cada tabla se identifica por un nombre (por ejemplo, "clientes" o "pedidos"). Las tablas contienen registros (filas) con los datos. A continuacin se muestra un ejemplo de una tabla llamada "Personas":
P_Id 1 2 3
La tabla contiene tres registros (uno para cada persona) y cinco columnas (p_id, Apellidos, Direccin Nombre, y la ciudad).
Sentencias SQL
La mayora de las acciones que debe realizar en una base de datos se hace con las sentencias SQL. La siguiente instruccin SQL selecciona todos los registros de las "Personas" tabla:
SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database
La parte DDL de tablas de bases de datos SQL permite que se creen o eliminen. Tambin se definen los
ndices (llaves), especificar los vnculos entre las tablas, e imponer restricciones entre las tablas. Las instrucciones de DDL ms importantes de SQL son los siguientes:
CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index
Ahora queremos seleccionar el contenido de las columnas denominadas "Apellido" y "Nombre" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * Ejemplo
Ahora queremos seleccionar todas las columnas de la tabla "Personas" . Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 2 3
Ahora queremos seleccionar slo los valores distintos de la columna llamada "Ciudad" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT DISTINCT City FROM Persons The result-set will look like this: City Sandnes Stavanger
La clusula WHERE
La clusula WHERE se utiliza para extraer slo aquellos registros que cumplan un criterio determinado.
WHERE de SQL Sintaxis SELECT column_name(s) FROM table_name WHERE column_name = operator value
Ahora queremos seleccionar slo las personas que viven en la ciudad "Sandnes" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * FROM Persons WHERE City='Sandnes' The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes
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'
Operator = <> > < >= <= LIKE IN Igual No igual Mayor que Menor que Mayor o igual que Menor o igual que Search for a pattern
Description
Ahora queremos seleccionar slo las personas con el nombre igual a "Tove" Y el apellido es igual a "Svendson": Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 2
LastName Svendson
FirstName Tove
Address Borgvn 23
City Sandnes
10
Operador OR Ejemplo
Ahora queremos seleccionar slo las personas con el nombre igual a "Tove" o el nombre de pila es igual a "Ola": Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 2
P_Id 2
LastName Svendson
FirstName Tove
Address Borgvn 23
City Sandnes
11
SQL ORDER BY Sintaxis SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
ORDER BY Example
The "Persons" table: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Tom Address Timoteivn 10 Borgvn 23 Storgt 20 Vingvn 23 City Sandnes Sandnes Stavanger Stavanger
Ahora queremos seleccionar todas las personas de la tabla anterior, sin embargo, queremos clasificar a las personas por su apellido. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 4 3 2
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:
P_Id 2 3 4 1
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
Ahora queremos insertar una nueva fila en la "Personas" tabla. Nosotros utilizamos la siguiente instruccin:
13
INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger') The "Persons" table will now look like this: P_Id 1 2 3 4 LastName Hansen Svendson Pettersen Nilsen FirstName Ola Tove Kari Johan Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 City Sandnes Sandnes Stavanger Stavanger
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
"Personas" tabla ahora se ver as:
P_Id 1 2 3 4 5
14
La instruccin UPDATE
La instruccin UPDATE se utiliza para actualizar los registros existentes en una tabla.
SQL UPDATE Sintaxis UPDATE nombre_tabla SET column1=value, column2=value2,... WHERE some_column=some_value
Nota: Observe la clusula WHERE en la sintaxis de UPDATE. La clusula WHERE especifica qu registros o registros que deben ser actualizadas. Si se omite la clusula WHERE, todos los registros sern actualizados!
Ahora queremos poner al da la persona "Tjessem, Jakob" en las "Personas" tabla. Nosotros utilizamos la siguiente instruccin:
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob' The "Persons" table will now look like this: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 Nissestien 67 City Sandnes Sandnes Stavanger Stavanger Sandnes
15
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' The "Persons" table would have looked like this: P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67 City Sandnes Sandnes Sandnes Sandnes Sandnes
16
La instruccin DELETE
La sentencia DELETE se utiliza para eliminar filas de una tabla.
Ahora queremos borrar a la persona "Tjessem, Jakob" en las "Personas" tabla. Nosotros utilizamos la siguiente instruccin:
P_Id 1 2 3 4
17
SQL Advanced
18
Ejemplo
SELECT * FROM Persons LIMIT 5
Oracle Syntax
SELECT nombre_columna(s) FROM nombre_tabla WHERE ROWNUM <= number
Ejemplo
SELECT * FROM Persons WHERE ROWNUM <=5
19
Ahora queremos seleccionar slo los dos primeros registros en la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT TOP 2 * FROM Persons The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes
Ahora queremos seleccionar slo el 50% de los registros de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT TOP 50 PERCENT * FROM Persons The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes
20
El operador LIKE
El operador LIKE se utiliza para la bsqueda de un patrn especfico en una columna.
SQL como la sintaxis SELECT nombre_columna(s) FROM nombre_tabla WHERE nombre_columna LIKE pattern
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:
P_Id 1 2 3
21
A continuacin, queremos seleccionar a las personas que viven en una ciudad que termina con una "s" de "personas" de tabla.
SELECT * FROM Persons WHERE City LIKE '%s' The result-set will look like this: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes
A continuacin, queremos seleccionar a las personas que viven en una ciudad que contiene el modelo de "tav" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 3
LastName Pettersen
FirstName Kari
Address Storgt 20
City Stavanger
Tambin es posible seleccionar a las personas que viven en una ciudad que no contiene el modelo de "tav" de las "Personas" de tabla, mediante el uso de la palabra NOT. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 2
22
SQL Wildcards(Comidines)
Comodines SQL se pueden utilizar en la bsqueda de datos en una base de datos.
SQL comodines
Comodines SQL puede sustituir a uno o ms personajes en la bsqueda de datos en una base de datos. Comodines SQL debe ser utilizado con el operador LIKE de SQL. Con SQL, los comodines pueden utilizar los siguientes: Comodn
Descripcin A substitute for zero or more characters A substitute for exactly one character Any single character in charlist Any single character not in charlist
P_Id 1 2 3
Utilizando el comodn %
Ahora queremos seleccionar a las personas que viven en una ciudad que empieza con "sa" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 2
A continuacin, queremos seleccionar a las personas que viven en una ciudad que contiene el modelo de "nep" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1 2
Usando el comodn _
Ahora queremos seleccionar a las personas con un nombre que comience con cualquier carcter, seguido por "la" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
P_Id 1
LastName Hansen
FirstName Ola
Address Timoteivn 10
City Sandnes
A continuacin, queremos seleccionar a las personas con un apellido que comienza con "S", seguida de cualquier carcter, seguido de "final", seguida de cualquier carcter, seguido por "a" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * FROM Persons WHERE LastName LIKE 'S_end_on' The result-set will look like this:
SELECT * FROM Persons WHERE LastName LIKE '[bsp]%' The result-set will look like this: P_Id 2 3 LastName Svendson Pettersen FirstName Tove Kari Address Borgvn 23 Storgt 20 City Sandnes Stavanger
A continuacin, queremos seleccionar a las personas con un apellido que no comienzan con "b" o "s" o "p" de las "Personas" tabla. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%' The result-set will look like this: P_Id 1 LastName Hansen FirstName Ola Address Timoteivn 10 City Sandnes
24
SQL IN Operator
El operador IN
El operador IN le permite especificar varios valores en una clusula WHERE.
IN Operator Example
The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger
Ahora queremos seleccionar a las personas con un apellido igual a "Hansen" o "Pettersen" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') The result-set will look like this: P_Id 1 3 LastName Hansen Pettersen FirstName Ola Kari Address Timoteivn 10 Storgt 20 City Sandnes Stavanger
25
El operador BETWEEN
El operador BETWEEN selecciona un rango de datos entre dos valores. Los valores pueden ser nmeros, texto o fechas.
Entre la sintaxis SQL SELECT nombre_columna(s) FROM nombre_tabla WHERE nombre_columna BETWEEN value1 AND value2
Ahora queremos seleccionar a las personas con el apellido en orden alfabtico entre los "Hansen" y "Pettersen" de la tabla anterior. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen' The result-set will look like this: P_Id LastName FirstName 1 Hansen Ola Address Timoteivn 10 City Sandnes
Nota: El operador BETWEEN es tratado de manera diferente en diferentes bases de datos! En algunas bases de datos, las personas con el apellido de "Hansen" o "Pettersen" no aparecer, porque el operador BETWEEN slo selecciona los campos que se encuentran entre los valores y la exclusin de la prueba. En otras bases de datos, las personas con el apellido de "Hansen" o "Pettersen" ser en la lista, debido a que el operador entre selecciona los campos que se entre y como los valores de prueba. Y en otras bases de datos, las personas con el apellido de "Hansen" se mostrar, pero "Pettersen" no aparecer (como el ejemplo anterior), debido a que el operador entre campos selecciona entre los valores de prueba, incluyendo el valor de la prueba inicial y excluyendo el valor de la ltima prueba. Por lo tanto: Comprobacin de la base de datos trata el operador BETWEEN.
Ejemplo 2
use NOT BETWEEN: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
Para mostrar a las personas fuera del rango en el ejemplo anterior,
The result-set will look like this: P_Id LastName FirstName 2 3 Svendson Pettersen Tove Kari
SQL Alias
Con SQL, un nombre de alias se puede dar a una tabla o una columna.
SQL Alias
Usted puede dar a una tabla o una columna de otro nombre mediante el uso de un alias. Esto puede ser una buena cosa que hacer si usted tiene los nombres de tablas muy largas o complejas, o nombres de columna. Un nombre de alias puede ser cualquier cosa, pero por lo general es corta.
Alias Ejemplo
Supongamos que tenemos una tabla llamada "Personas" y otra tabla denominada "Product_Orders". Daremos a los alias de tabla de la "p" y "po", respectivamente. Ahora queremos una lista de todas las rdenes que "Ola Hansen" es responsable. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE p.LastName='Hansen' AND p.FirstName='Ola' The same SELECT statement without aliases: SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons, Product_Orders WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'
Como se ver a partir de las dos sentencias SELECT anterior; alias pueden realizar consultas ms fciles tanto para escribir y leer.
27
SQL Joins
Uniones SQL se utilizan para consultar datos de dos o ms tablas, sobre la base de una relacin entre ciertas columnas en estas tablas.
SQL JOIN
La palabra clave JOIN se utiliza en una sentencia SQL para consultar datos de dos o ms tablas, sobre la base de una relacin entre ciertas columnas en estas tablas. Las tablas de una base de datos a menudo estn relacionados el uno al otro con las llaves. Una clave principal es una columna (o una combinacin de columnas) con un valor nico para cada fila. Cada valor de clave principal debe ser nico dentro de la tabla. El propsito es enlazar los datos en conjunto, a travs de tablas, sin repetir todos los datos en cada tabla. Mira las "Personas" tabla:
P_Id 1 2 3
Tenga en cuenta que el "p_id" columna es la clave principal de las "Personas" tabla. Esto significa que no hay dos filas no pueden tener el mismo p_id. El p_id distingue dos personas aunque tengan el mismo nombre. A continuacin, tenemos la tabla "orders":
O_Id 1 2 3 4 5
P_Id 3 3 1 1 15
Tenga en cuenta que el "O_ID" columna es la clave principal de la tabla "orders" y que "p_id" columna se refiere a las personas en las "Personas" tabla sin usar sus nombres. Tenga en cuenta que la relacin entre las dos tablas anteriores es el "p_id" de la columna
Antes de continuar con los ejemplos, vamos a enumerar los tipos de unin que puede utilizar, y las diferencias entre ellos. JOIN: Devolver filas cuando hay al menos un registo en las dos tablas LEFT JOIN: devolver todas las filas de la tabla de la izquierda, incluso si no hay coincidencias en la tabla de la derecha. RIGHT JOIN: devolver todas las filas de la tabla de la derecha, incluso si no hay coincidencias en la tabla de la izquierda. FULL JOIN: devuelven filas cuando hay un partido en una de las mesas
SQL INNER JOIN Sintaxis SELECT nombre_columna(s) FROM nombre_tabla1 INNER JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna
The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15
Ahora queremos una lista de todas las personas con cualquier orden. Nosotros utilizamos la siguiente sentencia SELECT:
29
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen FirstName Ola Ola Kari Kari OrderNo 22456 24562 77895 44678
El INNER JOIN filas palabra clave return cuando hay al menos un partido en ambas tablas. Si hay filas en "personas" que no tienen coincidencias en "Pedidos", las filas no se enumeran.
SQL LEFT JOIN Sintaxis SELECT nombre_columna(s) FROM nombre_tabla1 LEFT JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna
PS: En algunas bases de datos LEFT JOIN se llama LEFT OUTER JOIN.
The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15
Ahora queremos una lista de todas las personas y sus rdenes - en su caso, a partir de las tablas anteriores. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen FirstName Ola OrderNo 22456
31
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 Sintaxis RIGHT JOIN SELECT nombre_columna(s) FROM nombre_tabla1 RIGHT JOIN nombre_tabla2 ON nombre_tabla1.column_name = nombre_tabla2.column_name
PS: En algunas bases de datos se llama RIGHT JOIN RIGHT OUTER JOIN.
The "Orders" table: O_Id OrderNo 1 2 3 4 5 77895 44678 22456 24562 34764
P_Id 3 3 1 1 15
Ahora queremos una lista de todas las rdenes con las personas que contienen - en su caso, a partir de las tablas anteriores. Nosotros utilizamos la siguiente sentencia SELECT:
FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen FirstName Ola Ola Kari Kari OrderNo 22456 24562 77895 44678 34764
La palabra clave RIGHT JOIN devuelve todas las filas de la tabla de la derecha (rdenes), incluso si no hay coincidencias en la tabla a la izquierda (las personas).
Completo de SQL Sintaxis de JOIN SELECT nombre_columna(s) FROM nombre_tabla1 FULL JOIN nombre_tabla2 ON nombre_tabla1.nombre_columna = nombre_tabla2.nombre_columna
1 2 3
The "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15
Ahora queremos una lista de todas las personas y sus rdenes, y todos los pedidos con sus personas. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName Hansen Hansen Pettersen Pettersen Svendson FirstName Ola Ola Kari Kari Tove 34764 OrderNo 22456 24562 77895 44678
La palabra clave FULL JOIN devuelve todas las filas de la tabla de la izquierda (personas), y todas las filas de la tabla de la derecha (rdenes). Si hay filas en "personas" que no tienen coincidencias en "Pedidos", o si hay filas en "rdenes" que no tienen coincidencias en "Personas", las filas se enumeran tambin.
Sintaxis SQL UNION SELECT nombre_columna(s) FROM nombre_tabla1 UNION SELECT nombre_columna(s) FROM nombre_tabla2
Note: El operador UNION slo selecciona valores distintos por defecto. Para permitir que los valores
duplicados, use UNION ALL.
04
Scott, Stephen
Ahora queremos a la lista de todos los diferentes empleados en Noruega y EE.UU.. Nosotros utilizamos la siguiente sentencia SELECT:
SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA The result-set will look like this:
E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen Note: Este comando no se puede utilizar a la lista de todos los empleados en Noruega y EE.UU.. En el
ejemplo anterior tenemos dos empleados con nombres iguales, y slo uno de ellos se enumeran.El comando UNION slo selecciona valores distintos.
36
SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA Resultado: E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Svendson, Stephen Scott, Stephen
37
SELECT Persons.LastName,Orders.OrderNo INTO Persons_Order_Backup FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id
Ahora queremos crear una base de datos llamada "my_db". Nosotros utilizamos la siguiente instruccin CREATE DATABASE:
39
CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )
La columna p_id es de tipo int y se mantendr un nmero. El Apellido, Nombre, Direccin, y las columnas de la ciudad son de tipo varchar con una longitud mxima de 255 caracteres. El vaco "Personas" tabla ahora se ver as:
P_Id
LastName
FirstName
Address
City
La tabla de vaco puede ser llenada con los datos con la instruccin INSERT INTO.
SQL Constraints
Las restricciones se utilizan para limitar el tipo de datos que pueden ir en una tabla. Las restricciones se pueden especificar cuando se crea una tabla (con la sentencia CREATE TABLE) o despus de crear la tabla (con la instruccin ALTER TABLE). Nos centraremos en las siguientes restricciones:
40
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
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) )
CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
Para permitir la designacin de una restriccin UNIQUE, y para definir una restriccin UNIQUE en varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) )
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD UNIQUE (P_Id)
Para permitir la designacin de una restriccin UNIQUE, y para definir una restriccin UNIQUE en varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
MySQL: ALTER TABLE Persons DROP INDEX uc_PersonID SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT uc_PersonID
MySQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
Para permitir la designacin de una restriccin PRIMARY KEY, y para definir una restriccin PRIMARY KEY en varias columnas, utilice la siguiente sintaxis SQL:
43
MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) )
Nota: En el ejemplo anterior slo hay una clave principal (pk_PersonID). Sin embargo, el valor de la pk_PersonID se compone de dos columnas (p_id y LastName).
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD PRIMARY KEY (P_Id)
Para permitir la designacin de una restriccin PRIMARY KEY, y para definir una restriccin PRIMARY KEY en varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) Note: Si utiliza la instruccin ALTER TABLE para agregar una clave principal, la columna de clave
principal (s) ya deben haber sido declaradas para no contener valores NULL (cuando la tabla se cre por primera vez).
44
MySQL: ALTER TABLE Persons DROP PRIMARY KEY SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT pk_PersonID
P_Id 1 2 3
The "Orders" table: O_Id 1 2 3 4 OrderNo 77895 44678 22456 24562 P_Id 3 3 2 1
Tenga en cuenta que el "p_id" columna en los puntos de "pedidos" a la mesa "p_id" en la columna de "Personas" tabla. El "p_id" columna de la "Personas" tabla es la clave principal de la "Personas" tabla. El "p_id" columna de la tabla "orders" es una clave externa en la tabla "orders". La restriccin FOREIGN KEY se utiliza para evitar acciones que pudieran destruir los vnculos entre las tablas. La restriccin de clave externa tambin impide que los datos no vlidos forma que se inserta en la columna de clave externa, ya que tiene que ser uno de los valores contenidos en la tabla al que apunta.
MySQL:
45
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) )
Para permitir la designacin de una restriccin FOREIGN KEY, y para la definicin de una restriccin FOREIGN KEY de varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )
46
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
Para permitir la designacin de una restriccin FOREIGN KEY, y para la definicin de una restriccin FOREIGN KEY de varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
MySQL: ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders SQL Server / Oracle / MS Access: ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders
47
My SQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address archar(255), City varchar(255) )
Para permitir la designacin de una restriccin CHECK, y para definir una restriccin CHECK en varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )
Para crear una restriccin CHECK en el "p_id" columna de la tabla cuando ya se ha creado, utilice el siguiente SQL:
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CHECK (P_Id>0)
Para permitir la designacin de una restriccin CHECK, y para definir una restriccin CHECK en varias columnas, utilice la siguiente sintaxis SQL:
MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT chk_Person
La restriccin DEFAULT se utiliza para insertar un valor predeterminado en una columna. El valor por defecto ser aadido a todos los nuevos registros, si no hay otro valor especificado.
My SQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' )
La restriccin DEFAULT tambin puede ser utilizado para insertar los valores del sistema, mediante el uso de funciones como GETDATE ():
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, OrderDate date DEFAULT GETDATE() )
MySQL: ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES' SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES'
SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City DROP DEFAUL
50
ndices
Un ndice se puede crear en una tabla para encontrar datos ms rpido y eficaces. Los usuarios no pueden ver los ndices, que son utilizados para acelerar las bsquedas / consultas. Nota: Actualizando una tabla con los ndices lleva ms tiempo que la actualizacin de una tabla sin (ya que los ndices tambin se necesita una actualizacin). Por lo que slo debe crear ndices en columnas (y tablas) que con frecuencia se realizaron bsquedas en contra
CREATE UNIQUE INDEX index_name ON table_name (column_name) Note: La sintaxis para la creacin de ndices vara entre diferentes bases de datos. Por lo tanto:
Compruebe la sintaxis para la creacin de ndices en la base de datos.
51
52
53
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ADD DateOfBirth date Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference. The "Persons" table will now like this: P_Id LastName 1 2 3 Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger DateOfBirth
54
55
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE Persons AUTO_INCREMENT=100 To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically): INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
56
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.
Another view in the Northwind sample database selects every product in the "Products" table with a unit price higher than the average unit price: CREATE VIEW [Products Above Average Price] AS SELECT ProductName,UnitPrice FROM Products
59
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products) We can query the view above as follows: SELECT * FROM [Products Above Average Price] Another view in the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called "Product Sales for 1997": CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for 1997] GROUP BY CategoryName We can query the view above as follows: SELECT * FROM [Category Sales For 1997] We can also add a condition to the query. Now we want to see the total sale only for the category "Beverages": SELECT * FROM [Category Sales For 1997] WHERE CategoryName='Beverages'
Description Returns the current date and time Returns the current date Returns the current time Extracts the date part of a date or date/time expression Returns a single part of a date/time Adds a specified time interval to a date Subtracts a specified time interval from a date Returns the number of days between two dates
61
Description Returns the current date and time Returns a single part of a date/time Adds or subtracts a specified time interval from a date Returns the time between two dates Displays date/time data in different formats
DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: YYYY-MM-DD HH:MM:SS YEAR - format YYYY or YY
SQL Server comes with the following data types for storing a date or a date/time value in the database:
DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: a unique number
Note: The date types are chosen for a column when you create a new table in your database! For an overview of all data types available, go to our complete Data Types reference.
62
Now we want to select the records with an OrderDate of "2008-11-11" from the table above. We use the following SELECT statement: SELECT * FROM Orders WHERE OrderDate='2008-11-11' The result-set will look like this:
OrderId 1
ProductName Geitost
OrderDate 2008-11-11
3 Mozzarella di Giovanni 2008-11-11 Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column): OrderId 1 2 3 4 ProductName Geitost Camembert Pierrot Mozzarella di Giovanni Mascarpone Fabioli OrderDate 2008-11-11 13:23:44 2008-11-09 15:45:21 2008-11-11 11:12:01 2008-10-29 14:56:59
If we use the same SELECT statement as above: SELECT * FROM Orders WHERE OrderDate='2008-11-11' we will get no result! This is because the query is looking only for dates with no time portion. Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your dates!
63
Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value. How can we test for NULL values? It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.
64
SQL IS NULL
How do we select only the records with NULL values in the "Address" column? We will have to use the IS NULL operator: SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NULL The result-set will look like this: LastName Hansen Pettersen FirstName Ola Kari Address
LastName Svendson
FirstName Tove
Address Borgvn 23
In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.
65
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values. We have the following SELECT statement: SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder) FROM Products In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL. Microsoft's ISNULL() function is used to specify how we want to treat NULL values. The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result. In this case we want NULL values to be zero. Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL: SQL Server / MS Access SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0)) FROM Products Oracle Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result: SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0)) FROM Products
66
MySQL MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function. In MySQL we can use the IFNULL() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0)) FROM Products or we can use the COALESCE() function, like this: SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0)) FROM Products
67
Use for currency. Holds up to 15 digits of whole dollars, plus 48 bytes decimal places. Tip: You can choose which country's currency to use AutoNumber fields automatically give each record its own number, usually starting at 1 Use for dates and times 4 bytes 8 bytes
A logical field can be displayed as Yes/No, True/False, or 1 bit On/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) Contain links to other files, including web pages up to 1GB
Lookup Wizard Let you type a list of options, which can then be chosen from a 4 bytes drop-down list
68
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type TINYTEXT TEXT BLOB Holds a string with a maximum length of 255 characters Holds a string with a maximum length of 65,535 characters For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXT LONGBLOB Holds a string with a maximum length of 4,294,967,295 characters For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice
Number types:
69
Description -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) BIGINT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
FLOAT(size,d)
DOUBLE(size,d)
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number.
70
Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME()
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYYMM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC TIME() A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' YEAR() A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.
Character strings: Data type char(n) varchar(n) varchar(max) text Description Fixed-length character string. Maximum 8,000 characters Variable-length character string. Maximum 8,000 characters Variable-length character string. Maximum 1,073,741,824 characters Variable-length character string. Maximum 2GB of text data Storage n
Unicode strings: Data type nchar(n) nvarchar(n) nvarchar(max) ntext Description Fixed-length Unicode data. Maximum 4,000 characters Variable-length Unicode data. Maximum 4,000 characters Variable-length Unicode data. Maximum 536,870,912 characters Variable-length Unicode data. Maximum 2GB of text data Storage
Binary types: Data type bit binary(n) varbinary(n) image Description Allows 0, 1, or NULL Fixed-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 2GB Storage
72
Number types: Data type tinyint smallint int bigint decimal(p,s) Description Allows whole numbers from 0 to 255 Allows whole numbers between -32,768 and 32,767 Allows whole numbers between -2,147,483,648 and 2,147,483,647 Storage 1 byte 2 bytes 4 bytes
Allows whole numbers between -9,223,372,036,854,775,808 8 bytes and 9,223,372,036,854,775,807 Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 Fixed precision and scale numbers. 5-17 bytes Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 Monetary data from -214,748.3648 to 214,748.3647 4 bytes Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes 5-17 bytes
numeric(p,s)
Floating precision number data from -1.79E + 308 to 1.79E + 4 or 8 308. bytes The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8byte field. Default value of n is 53.
real
4 bytes
73
Date types: Data type datetime datetime2 smalldatetime date time datetimeoffset timestamp Description Storage
From January 1, 1753 to December 31, 9999 with an accuracy 8 bytes of 3.33 milliseconds From January 1, 0001 to December 31, 9999 with an accuracy 6-8 bytes of 100 nanoseconds From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute Store a time only to an accuracy of 100 nanoseconds 4 bytes
Store a date only. From January 1, 0001 to December 31, 9999 3 bytes 3-5 bytes The same as datetime2 with the addition of a time zone offset 8-10 bytes Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable
Other data types: Data type sql_variant Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing
74
SQL Functions
SQL has many built-in functions for performing calculations on data.
75
Now we want to find the average value of the "OrderPrice" fields. We use the following SQL statement: SELECT AVG(OrderPrice) AS OrderAverage FROM Orders The result-set will look like this: OrderAverage 950
76
Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value. We use the following SQL statement: SELECT Customer FROM Orders WHERE OrderPrice > (SELECT AVG(OrderPrice) FROM Orders) The result-set will look like this:
O_Id 1 2 3 4 5 6
Now we want to count the number of orders from "Customer Nilsen".We use the following SQL statement: SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Nilsen' The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total: CustomerNilsen 2
78
NumberOfCustomers 3 which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.
Now we want to find the first value of the "OrderPrice" column. We use the following SQL statement: SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders Tip: Workaround if FIRST() function is not supported: SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1 The result-set will look like this: FirstOrderPrice 1000
79
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
The MAX() function returns the largest value of the selected column.
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
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
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
Now we want to find the total sum (total order) of each customer. We will have to use the GROUP BY statement to group the customers.We use the following SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
84
The result-set will look like this: Customer Hansen Nilsen Jensen SUM(OrderPrice) 2000 1700 2000
Nice! Isn't it? :) Let's see what happens if we omit the GROUP BY statement: SELECT Customer,SUM(OrderPrice) FROM Orders The result-set will look like this: Customer Hansen Nilsen Hansen Hansen Jensen Nilsen SUM(OrderPrice) 5700 5700 5700 5700 5700 5700
The result-set above is not what we wanted. Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value (that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each row in the "Orders" table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
Now we want to find if any of the customers have a total order of less than 2000.We use the following SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000
86
The result-set will look like this: Customer Nilsen SUM(OrderPrice) 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500. We add an ordinary WHERE clause to the SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders WHERE Customer='Hansen' OR Customer='Jensen' GROUP BY Customer HAVING SUM(OrderPrice)>1500 The result-set will look like this: Customer Hansen Jensen SUM(OrderPrice) 2000 2000
87
Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to uppercase. We use the following SELECT statement: SELECT UCASE(LastName) as LastName,FirstName FROM Persons The result-set will look like this: LastName HANSEN SVENDSON PETTERSEN FirstName Ola Tove Kari
88
Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to lowercase. We use the following SELECT statement: SELECT LCASE(LastName) as LastName,FirstName FROM Persons The result-set will look like this: LastName hansen svendson pettersen FirstName Ola Tove Kari
89
Description Required. The field to extract characters from Required. Specifies the starting position (starts at 1) Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text
Now we want to extract the first four characters of the "City" column above. We use the following SELECT statement: SELECT MID(City,1,4) as SmallCity FROM Persons The result-set will look like this: SmallCity Sand Sand Stav
90
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
Now we want to display the product name and the price rounded to the nearest integer. We use the following SELECT statement: SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10 33 16
92
Now we want to display the products and prices per today's date. We use the following SELECT statement: SELECT ProductName, UnitPrice, Now() as PerDate FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.45 32.56 15.67 PerDate 10/7/2008 11:25:02 AM 10/7/2008 11:25:02 AM 10/7/2008 11:25:02 AM
Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD"). We use the following SELECT statement: SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.45 32.56 15.67 PerDate 2008-10-07 2008-10-07 2008-10-07
94
AS (alias)
BETWEEN
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name CREATE TABLE CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name2 data_type, ... ) CREATE INDEX index_name ON table_name (column_name) or CREATE UNIQUE INDEX index_name ON table_name (column_name) CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition DELETE FROM table_name WHERE some_column=some_value
CREATE INDEX
CREATE VIEW
DELETE
95
or DELETE FROM table_name (Note: Deletes the entire table!!) DELETE * FROM table_name (Note: Deletes the entire table!!) DROP DATABASE database_name DROP INDEX table_name.index_name (SQL Server) DROP INDEX index_name ON table_name (MS Access) DROP INDEX index_name (DB2/Oracle) ALTER TABLE table_name DROP INDEX index_name (MySQL) DROP TABLE table_name SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..) INSERT INTO table_name VALUES (value1, value2, value3,....) or INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....) SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
HAVING
IN
INSERT INTO
INNER JOIN
LEFT JOIN
RIGHT JOIN
96
FULL JOIN
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC] SELECT column_name(s) FROM table_name SELECT * FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT * INTO new_table_name [IN externaldatabase] FROM old_table_name or SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name
SELECT TOP
SELECT TOP number|percent column_name(s) FROM table_name SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 UPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value SELECT column_name(s) FROM table_name WHERE column_name operator value
UNION ALL
UPDATE
WHERE
Source : http://www.w3schools.com/sql/sql_quickref.asp
SQL Hosting
97
SQL Hosting
If you want your web site to be able to store and display data from a database, your web server should have access to a database system that uses the SQL language. If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans. The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access. You can have SQL databases on both Windows and Linux/UNIX operating systems. Below is an overview of which database system that runs on which OS. MS SQL Server Runs only on Windows OS. MySQL Runs on both Windows and Linux/UNIX operating systems. MS Access (recommended only for small websites) Runs only on Windows OS. To learn more about web hosting, please visit our Hosting tutorial.
98