SlideShare une entreprise Scribd logo
1  sur  55
Télécharger pour lire hors ligne
Introducción rápida a SQL
   Usando MySQL y Workbench




                 Carlos Hernando Carasol
                     chernando@acm.org
                   5 y 9 de Mayo de 2011
Índice de contenidos
 Introducción a las bases de datos
 Introducción a MySQL
 Sintaxis de SQL
   Uso de MySQL Worbench
Advertencia
 Esto no es un curso formal en teoría
 Es una introducción rápida y sucia de
 SQL
 Basado en el temario del curso:
 MySQL for Developers
Introducción a las bases de datos
Conceptos
 Entidad
 Atributo, una propiedad de la Entidad
 Registro, una f la que representa la
                i
 Entidad con sus atributos
 Tabla, una sucesión de registros
 tabulados por sus atributos de un mismo
 tipo de Entidad
Conceptos
 Base de datos, conjunto de Tablas
 Servidor, lugar dónde residen las Bases
 de Datos
 Bases de datos relacionales
 SQL, Structured Query Language
   DDL, Data Def nition Language
               i
   DML, Data Manipulation Language
Introducción a MySQL
Servidor MySQL
 Http://www.mysql.com/
 Comprado por Oracle
 Disponible gratuitamente
 Muy extendido
Estructura Cliente / Servidor
 El servidor mantiene las bases de datos
 El cliente realiza operaciones mediante
 sentencias SQL.
 La principal carga de trabajo recae en el
 servidor.
Instalación de MySQL
 Servidor
   MySQL Community Server
   http://www.mysql.com/downloads/mysql/
 El CCFI ya ha instalado el servidor pero
 no está activado
MySQL Workbench
 Herramienta de gestión, consulta y diseño
 http://wb.mysql.com/
 Lo utilizaremos como apoyo
Sintaxis SQL
Tipos de sentencias
 De consulta:
   SHOW
   DESC
   SELECT
 De manipulación:
   CREATE
   INSERT
   UPDATE
   ALTER
Obtener información de una tabla
 SHOW TABLES
 DESC tabla




      http://dev.mysql.com/doc/refman/5.1/en/describe.html
Query
SELECT                                      [HAVING where_condition]
  [ALL | DISTINCT | DISTINCTROW ]             [ORDER BY {col_name | expr | position}
   [HIGH_PRIORITY]                             [ASC | DESC], ...]
   [STRAIGHT_JOIN]
                                              [LIMIT {[offset,] row_count | row_count
   [SQL_SMALL_RESULT]                       OFFSET offset}]
[SQL_BIG_RESULT]
[SQL_BUFFER_RESULT]                           [PROCEDURE
   [SQL_CACHE | SQL_NO_CACHE]               procedure_name(argument_list)]
[SQL_CALC_FOUND_ROWS]                         [INTO OUTFILE 'file_name'
  select_expr [, select_expr ...]                [CHARACTER SET charset_name]
  [FROM table_references
                                                 export_options
  [WHERE where_condition]
                                               | INTO DUMPFILE 'file_name'
  [GROUP BY {col_name | expr | position}
                                               | INTO var_name [, var_name]]
   [ASC | DESC], ... [WITH ROLLUP]]
                                             [FOR UPDATE | LOCK IN SHARE
                                            MODE]]


                  http://dev.mysql.com/doc/refman/5.1/en/select.html
Condicionales
   expr OR expr                      comparison_operator: = | >= | > | <= | < |
                                     <> | !=
 | expr || expr
                                     predicate:
 | expr XOR expr
                                        bit_expr [NOT] IN (subquery)
 | expr AND expr                      | bit_expr [NOT] IN (expr [, expr] ...)
 | expr && expr                       | bit_expr [NOT] BETWEEN bit_expr
                                     AND predicate
 | NOT expr                           | bit_expr SOUNDS LIKE bit_expr
                                      | bit_expr [NOT] LIKE simple_expr
 | ! expr                            [ESCAPE simple_expr]
 | boolean_primary IS                 | bit_expr [NOT] REGEXP bit_expr
[NOT] {TRUE | FALSE |                 | bit_expr
UNKNOWN}
 | boolean_primary
         http://dev.mysql.com/doc/refman/5.1/en/expressions.html
Funciones
 AVG()
 CONCAT()
 COUNT()
 CURRENT_DATE()
 IF()
 TRIM()
 LOWER()

   http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html
Union
 Agregación de     SELECT ...
 tablas            UNION [ALL |
 Mismas columnas   DISTINCT]
                   SELECT ...
                   [UNION [ALL |
                   DISTINCT]
                   SELECT ...]
Creación de una base de datos
CREATE DATABASE curso;
Fijar la base de datos
 Un servidor puede alojar múltiples bases
 de datos
 Las operaciones SQL pueden referirse a
 cualquiera de estas tablas
 Para utilizar una base de datos en
 concreto utilizamos
 USE pruebas;
Destruir una base de datos
DROP DATABASE pruebas;
Cargar y guardar volcados
 Base de datos     Fichero
   MySQLdump
 Fichero    Base de datos
   Ejecutar sentencias 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
Propiedades de una tabla
 Tipo de ENGINE
   MyISAM
   InnoDB
 Charset
   Latin1
   UTF8
Tipos de datos
 Numéricos
 Cadenas
 Binarios
 Tiempo
Numéricos
 Enteros
   TINYINT
   INT
   BIGINT
 Coma f otante
      l
   FLOAT
 Coma f ja
      i
   DECIMAL

      http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html
Cadenas
 CHAR
 VARCHAR
 BLOB
 ENUM
 SET




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




     http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html
Tiempo
 DATETIME
 DATE
 TIME
 TIMESTAMP
 YEAR




   http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html
Tipos de datos (de nuevo)
  BIT[(length)]                                        | CHAR[(length)]
| TINYINT[(length)] [UNSIGNED] [ZEROFILL]                 [CHARACTER SET charset_name] [COLLATE collation_name]
| SMALLINT[(length)] [UNSIGNED] [ZEROFILL]              | VARCHAR(length)
| MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]               [CHARACTER SET charset_name] [COLLATE collation_name]
| INT[(length)] [UNSIGNED] [ZEROFILL]                   | BINARY[(length)]
| INTEGER[(length)] [UNSIGNED] [ZEROFILL]               | VARBINARY(length)
| BIGINT[(length)] [UNSIGNED] [ZEROFILL]                | TINYBLOB
| REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]         | BLOB
| DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]       | MEDIUMBLOB
| FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]        | LONGBLOB
| DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL]    | TINYTEXT [BINARY]
| NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL]      [CHARACTER SET charset_name] [COLLATE collation_name]
| DATE                                                  | TEXT [BINARY]
| TIME                                                    [CHARACTER SET charset_name] [COLLATE collation_name]
| TIMESTAMP                                             | MEDIUMTEXT [BINARY]
| DATETIME                                                [CHARACTER SET charset_name] [COLLATE collation_name]
| YEAR                                                  | 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
NULL y valores de fábrica
 NULL | NOT NULL
 DEFAULT 'valor'
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
Eliminar una tabla
DROP TABLE jugador;
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
Foreign Keys
 Una vez creada la tabla:
   ALTER TABLE jugador ADD FOREIGN KEY
   index_name (index_col_name)
   reference_def nition
               i
CASCADE
 ON UPDATE
 ON DELETE
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] ... ]
DELETE
DELETE [LOW_PRIORITY] [QUICK]
[IGNORE] FROM tbl_name
   [WHERE where_condition]
   [ORDER BY ...]
   [LIMIT row_count]
UPDATE
UPDATE [LOW_PRIORITY] [IGNORE]
table_reference
   SET col_name1={expr1|DEFAULT} [,
col_name2={expr2|DEFAULT}] ...
   [WHERE where_condition]
   [ORDER BY ...]
   [LIMIT row_count]
REPLACE
REPLACE [LOW_PRIORITY | DELAYED]
  [INTO] tbl_name [(col_name,...)]
  {VALUES | VALUE} ({expr |
DEFAULT},...),(...),...
INSERT ON DUPLICATE KEY
INSERT INTO table (a,b,c) VALUES (1,2,3)
 ON DUPLICATE KEY UPDATE c=c+1;
TRUNCATE
TRUNCATE [TABLE] tbl_name
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}
LOCK
LOCK TABLES
  tbl_name [[AS] alias] lock_type
  [, tbl_name [[AS] alias] lock_type] ...

lock_type:
    READ [LOCAL]
  | [LOW_PRIORITY] WRITE

UNLOCK TABLES
Consultas a múltiples tablas
 JOIN
 Subquery
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
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
Subqueries
SELECT * FROM t1 WHERE column1 =
(SELECT column1 FROM t2);
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]
Procedimientos
CREATE
   [DEFINER = { user | CURRENT_USER }]
   PROCEDURE sp_name
([proc_parameter[,...]])
   [characteristic ...] routine_body
Triggers
CREATE
    [DEFINER = { user | CURRENT_USER }]
    TRIGGER trigger_name trigger_time
trigger_event
    ON tbl_name FOR EACH ROW
trigger_body
Caso práctico
Ejercicio
 Crear las tablas del siguiente diagrama
 Crear las vistas asociadas (SELECT)
 Insertar una Notif cación al insertar una
                  i
 nueva tarea (TRIGGER)
 Crear un procedimiento “tarea_notif cada”
                                      i
 (STORED PROCEDURE) que elimine la
 notif cación y ponga la tarea en el estado
     i
 “progreso”
Diseño orientativo

Contenu connexe

Tendances

Linguagem sql
Linguagem sqlLinguagem sql
Linguagem sqlTic Eslc
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma IntroduçãoÍgor Bonadio
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console componentHugo Hamon
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubyJason Yeo Jie Shun
 
Syntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLSyntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLAntony Abramchenko
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 

Tendances (20)

Linguagem sql
Linguagem sqlLinguagem sql
Linguagem sql
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
ES6 and BEYOND
ES6 and BEYONDES6 and BEYOND
ES6 and BEYOND
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
 
Syntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLSyntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQL
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 

Similaire à Introducción rápida a SQL

Unit_III_SQL-MySQL-Commands-Basic.pptx usefull
Unit_III_SQL-MySQL-Commands-Basic.pptx  usefullUnit_III_SQL-MySQL-Commands-Basic.pptx  usefull
Unit_III_SQL-MySQL-Commands-Basic.pptx usefullANTOARA2211003040050
 
СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3Technopark
 
Simple Strategies for faster knowledge discovery in big data
Simple Strategies for faster knowledge discovery in big dataSimple Strategies for faster knowledge discovery in big data
Simple Strategies for faster knowledge discovery in big dataRitesh Agrawal
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Vidyasagar Mundroy
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updatedleetinhf
 
Oracle APEX Cheat Sheet
Oracle APEX Cheat SheetOracle APEX Cheat Sheet
Oracle APEX Cheat SheetDimitri Gielis
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Achmad Solichin
 
vFabric SQLFire Introduction
vFabric SQLFire IntroductionvFabric SQLFire Introduction
vFabric SQLFire IntroductionJags Ramnarayan
 
Hadoop Summit EU 2014
Hadoop Summit EU   2014Hadoop Summit EU   2014
Hadoop Summit EU 2014cwensel
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
 
GQL cheat sheet latest
GQL cheat sheet latestGQL cheat sheet latest
GQL cheat sheet latestsones GmbH
 

Similaire à Introducción rápida a SQL (20)

New tsql features
New tsql featuresNew tsql features
New tsql features
 
Unit_III_SQL-MySQL-Commands-Basic.pptx usefull
Unit_III_SQL-MySQL-Commands-Basic.pptx  usefullUnit_III_SQL-MySQL-Commands-Basic.pptx  usefull
Unit_III_SQL-MySQL-Commands-Basic.pptx usefull
 
СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3СУБД осень 2012 Лекция 3
СУБД осень 2012 Лекция 3
 
SQL-MySQL-Commands-Basic.pptx
SQL-MySQL-Commands-Basic.pptxSQL-MySQL-Commands-Basic.pptx
SQL-MySQL-Commands-Basic.pptx
 
SQL introduction
SQL introductionSQL introduction
SQL introduction
 
Simple Strategies for faster knowledge discovery in big data
Simple Strategies for faster knowledge discovery in big dataSimple Strategies for faster knowledge discovery in big data
Simple Strategies for faster knowledge discovery in big data
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Linguagem sql
Linguagem sqlLinguagem sql
Linguagem sql
 
Database
Database Database
Database
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updated
 
Oracle APEX Cheat Sheet
Oracle APEX Cheat SheetOracle APEX Cheat Sheet
Oracle APEX Cheat Sheet
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Les09
Les09Les09
Les09
 
My sql cheat sheet
My sql cheat sheetMy sql cheat sheet
My sql cheat sheet
 
vFabric SQLFire Introduction
vFabric SQLFire IntroductionvFabric SQLFire Introduction
vFabric SQLFire Introduction
 
Vertica-Database
Vertica-DatabaseVertica-Database
Vertica-Database
 
Hadoop Summit EU 2014
Hadoop Summit EU   2014Hadoop Summit EU   2014
Hadoop Summit EU 2014
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
GQL cheat sheet latest
GQL cheat sheet latestGQL cheat sheet latest
GQL cheat sheet latest
 

Plus de Carlos Hernando

Introduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonIntroduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonCarlos Hernando
 
Microservicos: Cuándo y Cómo
Microservicos: Cuándo y CómoMicroservicos: Cuándo y Cómo
Microservicos: Cuándo y CómoCarlos Hernando
 
Bases de Datos en Java - Intro a Hibernate
Bases de Datos en Java - Intro a HibernateBases de Datos en Java - Intro a Hibernate
Bases de Datos en Java - Intro a HibernateCarlos Hernando
 
Bases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCBases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCCarlos Hernando
 
Persistencia en Java - Serialización
Persistencia en Java - SerializaciónPersistencia en Java - Serialización
Persistencia en Java - SerializaciónCarlos Hernando
 

Plus de Carlos Hernando (8)

Introduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonIntroduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos Python
 
Microservicos: Cuándo y Cómo
Microservicos: Cuándo y CómoMicroservicos: Cuándo y Cómo
Microservicos: Cuándo y Cómo
 
Try AngularJS
Try AngularJSTry AngularJS
Try AngularJS
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Metodologías Ágiles
Metodologías ÁgilesMetodologías Ágiles
Metodologías Ágiles
 
Bases de Datos en Java - Intro a Hibernate
Bases de Datos en Java - Intro a HibernateBases de Datos en Java - Intro a Hibernate
Bases de Datos en Java - Intro a Hibernate
 
Bases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCBases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBC
 
Persistencia en Java - Serialización
Persistencia en Java - SerializaciónPersistencia en Java - Serialización
Persistencia en Java - Serialización
 

Dernier

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Dernier (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Introducción rápida a SQL

  • 1. Introducción rápida a SQL Usando MySQL y Workbench Carlos Hernando Carasol chernando@acm.org 5 y 9 de Mayo de 2011
  • 2. Índice de contenidos Introducción a las bases de datos Introducción a MySQL Sintaxis de SQL Uso de MySQL Worbench
  • 3. Advertencia Esto no es un curso formal en teoría Es una introducción rápida y sucia de SQL Basado en el temario del curso: MySQL for Developers
  • 4. Introducción a las bases de datos
  • 5. Conceptos Entidad Atributo, una propiedad de la Entidad Registro, una f la que representa la i Entidad con sus atributos Tabla, una sucesión de registros tabulados por sus atributos de un mismo tipo de Entidad
  • 6. Conceptos Base de datos, conjunto de Tablas Servidor, lugar dónde residen las Bases de Datos Bases de datos relacionales SQL, Structured Query Language DDL, Data Def nition Language i DML, Data Manipulation Language
  • 8. Servidor MySQL Http://www.mysql.com/ Comprado por Oracle Disponible gratuitamente Muy extendido
  • 9. Estructura Cliente / Servidor El servidor mantiene las bases de datos El cliente realiza operaciones mediante sentencias SQL. La principal carga de trabajo recae en el servidor.
  • 10. Instalación de MySQL Servidor MySQL Community Server http://www.mysql.com/downloads/mysql/ El CCFI ya ha instalado el servidor pero no está activado
  • 11. MySQL Workbench Herramienta de gestión, consulta y diseño http://wb.mysql.com/ Lo utilizaremos como apoyo
  • 12.
  • 14. Tipos de sentencias De consulta: SHOW DESC SELECT De manipulación: CREATE INSERT UPDATE ALTER
  • 15. Obtener información de una tabla SHOW TABLES DESC tabla http://dev.mysql.com/doc/refman/5.1/en/describe.html
  • 16. Query SELECT [HAVING where_condition] [ALL | DISTINCT | DISTINCTROW ] [ORDER BY {col_name | expr | position} [HIGH_PRIORITY] [ASC | DESC], ...] [STRAIGHT_JOIN] [LIMIT {[offset,] row_count | row_count [SQL_SMALL_RESULT] OFFSET offset}] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [PROCEDURE [SQL_CACHE | SQL_NO_CACHE] procedure_name(argument_list)] [SQL_CALC_FOUND_ROWS] [INTO OUTFILE 'file_name' select_expr [, select_expr ...] [CHARACTER SET charset_name] [FROM table_references export_options [WHERE where_condition] | INTO DUMPFILE 'file_name' [GROUP BY {col_name | expr | position} | INTO var_name [, var_name]] [ASC | DESC], ... [WITH ROLLUP]] [FOR UPDATE | LOCK IN SHARE MODE]] http://dev.mysql.com/doc/refman/5.1/en/select.html
  • 17. Condicionales expr OR expr comparison_operator: = | >= | > | <= | < | <> | != | expr || expr predicate: | expr XOR expr bit_expr [NOT] IN (subquery) | expr AND expr | bit_expr [NOT] IN (expr [, expr] ...) | expr && expr | bit_expr [NOT] BETWEEN bit_expr AND predicate | NOT expr | bit_expr SOUNDS LIKE bit_expr | bit_expr [NOT] LIKE simple_expr | ! expr [ESCAPE simple_expr] | boolean_primary IS | bit_expr [NOT] REGEXP bit_expr [NOT] {TRUE | FALSE | | bit_expr UNKNOWN} | boolean_primary http://dev.mysql.com/doc/refman/5.1/en/expressions.html
  • 18. Funciones AVG() CONCAT() COUNT() CURRENT_DATE() IF() TRIM() LOWER() http://dev.mysql.com/doc/refman/5.1/en/func-op-summary-ref.html
  • 19. Union Agregación de SELECT ... tablas UNION [ALL | Mismas columnas DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]
  • 20. Creación de una base de datos CREATE DATABASE curso;
  • 21. Fijar la base de datos Un servidor puede alojar múltiples bases de datos Las operaciones SQL pueden referirse a cualquiera de estas tablas Para utilizar una base de datos en concreto utilizamos USE pruebas;
  • 22. Destruir una base de datos DROP DATABASE pruebas;
  • 23. Cargar y guardar volcados Base de datos Fichero MySQLdump Fichero Base de datos Ejecutar sentencias SQL
  • 24. 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
  • 25. Propiedades de una tabla Tipo de ENGINE MyISAM InnoDB Charset Latin1 UTF8
  • 26. Tipos de datos Numéricos Cadenas Binarios Tiempo
  • 27. Numéricos Enteros TINYINT INT BIGINT Coma f otante l FLOAT Coma f ja i DECIMAL http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html
  • 28. Cadenas CHAR VARCHAR BLOB ENUM SET http://dev.mysql.com/doc/refman/5.1/en/string-types.html
  • 29. Binarios BINARY VARBINARY http://dev.mysql.com/doc/refman/5.1/en/binary-varbinary.html
  • 30. Tiempo DATETIME DATE TIME TIMESTAMP YEAR http://dev.mysql.com/doc/refman/5.1/en/date-and-time-types.html
  • 31. Tipos de datos (de nuevo) BIT[(length)] | CHAR[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | VARCHAR(length) | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name] | INT[(length)] [UNSIGNED] [ZEROFILL] | BINARY[(length)] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | VARBINARY(length) | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | TINYBLOB | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | BLOB | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | MEDIUMBLOB | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | LONGBLOB | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL] | TINYTEXT [BINARY] | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL] [CHARACTER SET charset_name] [COLLATE collation_name] | DATE | TEXT [BINARY] | TIME [CHARACTER SET charset_name] [COLLATE collation_name] | TIMESTAMP | MEDIUMTEXT [BINARY] | DATETIME [CHARACTER SET charset_name] [COLLATE collation_name] | YEAR | 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
  • 32. NULL y valores de fábrica NULL | NOT NULL DEFAULT 'valor'
  • 33. 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
  • 34. Eliminar una tabla DROP TABLE jugador;
  • 35. 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
  • 36. Foreign Keys Una vez creada la tabla: ALTER TABLE jugador ADD FOREIGN KEY index_name (index_col_name) reference_def nition i
  • 37. CASCADE ON UPDATE ON DELETE
  • 38. 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] ... ]
  • 39. DELETE DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • 40. UPDATE UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... [WHERE where_condition] [ORDER BY ...] [LIMIT row_count]
  • 41. REPLACE REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
  • 42. INSERT ON DUPLICATE KEY INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
  • 44. 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}
  • 45. LOCK LOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ... lock_type: READ [LOCAL] | [LOW_PRIORITY] WRITE UNLOCK TABLES
  • 46. Consultas a múltiples tablas JOIN Subquery
  • 47. 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
  • 48. 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
  • 49. Subqueries SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
  • 50. 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]
  • 51. Procedimientos CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body
  • 52. Triggers CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body
  • 54. Ejercicio Crear las tablas del siguiente diagrama Crear las vistas asociadas (SELECT) Insertar una Notif cación al insertar una i nueva tarea (TRIGGER) Crear un procedimiento “tarea_notif cada” i (STORED PROCEDURE) que elimine la notif cación y ponga la tarea en el estado i “progreso”