Introducción rápida a SQL

55
Introducción rápida a SQL Usando MySQL y Workbench Carlos Hernando Carasol [email protected] 5 y 9 de Mayo de 2011

description

Curso de introducción a SQL utilizando MySQL y Workbench.

Transcript of Introducción rápida a SQL

Page 1: Introducción rápida a SQL

Introducción rápida a SQLUsando MySQL y Workbench

Carlos Hernando [email protected]

5 y 9 de Mayo de 2011

Page 2: Introducción rápida a SQL

Índice de contenidos

Introducción a las bases de datosIntroducción a MySQLSintaxis de SQL

Uso de MySQL Worbench

Page 3: Introducción rápida a SQL

Advertencia

Esto no es un curso formal en teoríaEs una introducción rápida y sucia de SQLBasado en el temario del curso: MySQL for Developers

Page 4: Introducción rápida a SQL

Introducción a las bases de datos

Page 5: Introducción rápida a SQL

Conceptos

EntidadAtributo, una propiedad de la EntidadRegistro, una fi la que representa la Entidad con sus atributosTabla, una sucesión de registros tabulados por sus atributos de un mismo tipo de Entidad

Page 6: Introducción rápida a SQL

Conceptos

Base de datos, conjunto de Tablas

Servidor, lugar dónde residen las Bases de DatosBases de datos relacionalesSQL, Structured Query Language

DDL, Data Defi nition LanguageDML, Data Manipulation Language

Page 7: Introducción rápida a SQL

Introducción a MySQL

Page 8: Introducción rápida a SQL

Servidor MySQL

Http://www.mysql.com/Comprado por OracleDisponible gratuitamenteMuy extendido

Page 9: Introducción rápida a SQL

Estructura Cliente / Servidor

El servidor mantiene las bases de datosEl cliente realiza operaciones mediante sentencias SQL.La principal carga de trabajo recae en el servidor.

Page 10: Introducción rápida a SQL

Instalación de MySQL

ServidorMySQL Community Serverhttp://www.mysql.com/downloads/mysql/

El CCFI ya ha instalado el servidor pero no está activado

Page 11: Introducción rápida a SQL

MySQL Workbench

Herramienta de gestión, consulta y diseñohttp://wb.mysql.com/Lo utilizaremos como apoyo

Page 12: Introducción rápida a SQL
Page 13: Introducción rápida a SQL

Sintaxis SQL

Page 14: Introducción rápida a SQL

Tipos de sentencias

De consulta:SHOWDESCSELECT

De manipulación:CREATEINSERTUPDATEALTER

Page 15: Introducción rápida a SQL

Obtener información de una tabla

SHOW TABLESDESC tabla

http://dev.mysql.com/doc/refman/5.1/en/describe.html

Page 16: Introducción rápida a SQL

QuerySELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr ...] [FROM table_references [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]

[HAVING where_condition]

[ORDER BY {col_name | expr | position}

[ASC | DESC], ...]

[LIMIT {[offset,] row_count | row_count OFFSET offset}]

[PROCEDURE procedure_name(argument_list)]

[INTO OUTFILE 'file_name'

[CHARACTER SET charset_name]

export_options

| INTO DUMPFILE 'file_name'

| INTO var_name [, var_name]]

[FOR UPDATE | LOCK IN SHARE MODE]]

http://dev.mysql.com/doc/refman/5.1/en/select.html

Page 17: Introducción rápida a SQL

Condicionales

expr OR expr | expr || expr | expr XOR expr | expr AND expr | expr && expr | NOT expr | ! expr | boolean_primary IS [NOT] {TRUE | FALSE | UNKNOWN} | boolean_primary

comparison_operator: = | >= | > | <= | < | <> | !=

predicate: bit_expr [NOT] IN (subquery) | bit_expr [NOT] IN (expr [, expr] ...) | bit_expr [NOT] BETWEEN bit_expr AND predicate | bit_expr SOUNDS LIKE bit_expr | bit_expr [NOT] LIKE simple_expr [ESCAPE simple_expr] | bit_expr [NOT] REGEXP bit_expr | bit_expr

http://dev.mysql.com/doc/refman/5.1/en/expressions.html

Page 18: Introducción rápida a SQL

Funciones

AVG()CONCAT()COUNT()CURRENT_DATE()IF()TRIM()LOWER()

http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html

Page 19: Introducción rápida a SQL

Union

Agregación de tablasMismas columnas

SELECT ...UNION [ALL | DISTINCT] SELECT ...[UNION [ALL | DISTINCT] SELECT ...]

Page 20: Introducción rápida a SQL

Creación de una base de datos

CREATE DATABASE curso;

Page 21: Introducción rápida a SQL

Fijar la base de datos

Un servidor puede alojar múltiples bases de datosLas operaciones SQL pueden referirse a cualquiera de estas tablasPara utilizar una base de datos en concreto utilizamosUSE pruebas;

Page 22: Introducción rápida a SQL

Destruir una base de datos

DROP DATABASE pruebas;

Page 23: Introducción rápida a SQL

Cargar y guardar volcados

Base de datos � FicheroMySQLdump

Fichero � Base de datosEjecutar sentencias SQL

Page 24: Introducción rápida a SQL

Creación de una tabla

CREATE TABLE `jugador` ( `id` int(11) NOT NULL, `nombre` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1

Page 25: Introducción rápida a SQL

Propiedades de una tabla

Tipo de ENGINEMyISAMInnoDB

CharsetLatin1UTF8

Page 26: Introducción rápida a SQL

Tipos de datos

NuméricosCadenasBinariosTiempo

Page 27: Introducción rápida a SQL

Numéricos

EnterosTINYINTINTBIGINT

Coma fl otanteFLOAT

Coma fi jaDECIMAL

http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html

Page 28: Introducción rápida a SQL

Cadenas

CHARVARCHARBLOBENUMSET

http://dev.mysql.com/doc/refman/5.1/en/string-types.html

Page 29: Introducción rápida a SQL

Binarios

BINARYVARBINARY

http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html

Page 30: Introducción rápida a SQL

Tiempo

DATETIMEDATETIMETIMESTAMPYEAR

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html

Page 31: Introducción rápida a SQL

Tipos de datos (de nuevo) BIT[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFILL] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] | INT[(length)] [UNSIGNED] [ZEROFILL] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL] | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL] | DATE | TIME | TIMESTAMP | DATETIME | YEAR

| CHAR[(length)]

[CHARACTER SET charset_name] [COLLATE collation_name]

| VARCHAR(length)

[CHARACTER SET charset_name] [COLLATE collation_name]

| BINARY[(length)]

| VARBINARY(length)

| TINYBLOB

| BLOB

| MEDIUMBLOB

| LONGBLOB

| TINYTEXT [BINARY]

[CHARACTER SET charset_name] [COLLATE collation_name]

| TEXT [BINARY]

[CHARACTER SET charset_name] [COLLATE collation_name]

| MEDIUMTEXT [BINARY]

[CHARACTER SET charset_name] [COLLATE collation_name]

| LONGTEXT [BINARY]

[CHARACTER SET charset_name] [COLLATE collation_name]

| ENUM(value1,value2,value3,...)

[CHARACTER SET charset_name] [COLLATE collation_name]

| SET(value1,value2,value3,...)

[CHARACTER SET charset_name] [COLLATE collation_name]

| spatial_type

Page 32: Introducción rápida a SQL

NULL y valores de fábrica

NULL | NOT NULLDEFAULT 'valor'

Page 33: Introducción rápida a SQL

Alterar una tabla

ALTER TABLE jugador ADD COLUMN universo VARCHAR(20) NOT NULL AFTER nombre;

ALTER TABLE jugador DROP COLUMN universo;

ALTER TABLE jugador ADD KEY universo;

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Page 34: Introducción rápida a SQL

Eliminar una tabla

DROP TABLE jugador;

Page 35: Introducción rápida a SQL

Foreign Keys

En tiempo de creación: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option]

http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

Page 36: Introducción rápida a SQL

Foreign Keys

Una vez creada la tabla:ALTER TABLE jugador ADD FOREIGN KEY index_name (index_col_name) reference_defi nition

Page 37: Introducción rápida a SQL

CASCADE

ON UPDATEON DELETE

Page 38: Introducción rápida a SQL

INSERT

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] ... ]

Page 39: Introducción rápida a SQL

DELETE

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]

Page 40: Introducción rápida a SQL

UPDATE

UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]

Page 41: Introducción rápida a SQL

REPLACE

REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...

Page 42: Introducción rápida a SQL

INSERT ON DUPLICATE KEY

INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

Page 43: Introducción rápida a SQL

TRUNCATE

TRUNCATE [TABLE] tbl_name

Page 44: Introducción rápida a SQL

Transacciones

START TRANSACTION [WITH CONSISTENT SNAPSHOT] | BEGIN [WORK]COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]ROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]SET autocommit = {0 | 1}

Page 45: Introducción rápida a SQL

LOCK

LOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ...

lock_type: READ [LOCAL] | [LOW_PRIORITY] WRITE

UNLOCK TABLES

Page 46: Introducción rápida a SQL

Consultas a múltiples tablas

JOINSubquery

Page 47: Introducción rápida a SQL

JOIN

SELECT t1.name, t2.salary FROM employee t1 INNER JOIN info t2 ON t1.name = t2.name

SELECT t1.name, t2.salay FROM employee t1, info t2 WHERE t1.name = t2.name

Page 48: Introducción rápida a SQL

Tipos de JOIN

table_reference [INNER | CROSS] JOIN table_factor [join_condition] | table_reference STRAIGHT_JOIN table_factor | table_reference STRAIGHT_JOIN table_factor ON conditional_expr | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_condition | table_reference NATURAL [{LEFT|RIGHT} [OUTER]] JOIN table_factor

Page 49: Introducción rápida a SQL

Subqueries

SELECT * FROM t1 WHERE column1 =(SELECT column1 FROM t2);

Page 50: Introducción rápida a SQL

Vistas

CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]

Page 51: Introducción rápida a SQL

Procedimientos

CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body

Page 52: Introducción rápida a SQL

Triggers

CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body

Page 53: Introducción rápida a SQL

Caso práctico

Page 54: Introducción rápida a SQL

Ejercicio

Crear las tablas del siguiente diagramaCrear las vistas asociadas (SELECT)Insertar una Notifi cación al insertar una nueva tarea (TRIGGER)Crear un procedimiento “tarea_notifi cada” (STORED PROCEDURE) que elimine la notifi cación y ponga la tarea en el estado “progreso”

Page 55: Introducción rápida a SQL

Diseño orientativo