├── 01_Reading ├── 00_comments.sql ├── 01_select.sql ├── 02_distinct.sql ├── 03_where.sql ├── 04_order_by.sql ├── 05_like.sql ├── 06_and_or_not.sql ├── 07_limit.sql ├── 08_null.sql ├── 09_min_max.sql ├── 10_count.sql ├── 11_sum.sql ├── 12_avg.sql ├── 13_in.sql ├── 14_between.sql ├── 15_alias.sql ├── 16_concat.sql ├── 17_group_by.sql ├── 18_having.sql └── 19_case.sql ├── 02_Writing ├── 01_insert.sql ├── 02_update.sql └── 03_delete.sql ├── 03_Database ├── 01_create_database.sql └── 02_drop_database.sql ├── 04_Tables ├── 01_create_table.sql ├── 02_drop_table.sql ├── 03_alter_table.sql └── 04_relationships.sql ├── 05_Join ├── 01_inner_join.sql ├── 02_left_join.sql ├── 03_right_join.sql └── 04_union.sql ├── 06_Advanced ├── 01_index.sql ├── 02_triggers.sql ├── 03_views.sql ├── 04_stored_procedures.sql ├── 05_transactions.sql └── 06_connectors.py ├── Images ├── header.jpg └── pro.jpg ├── LICENSE └── README.md /01_Reading/00_comments.sql: -------------------------------------------------------------------------------- 1 | /* 2 | COMENTAROS 3 | Lección 10.1: https://youtu.be/OuJerKzV5T0?t=7512 4 | */ 5 | 6 | -- Comentario en una lína 7 | 8 | /* 9 | Este 10 | es 11 | un 12 | comentario 13 | en 14 | varias 15 | líneas 16 | */ -------------------------------------------------------------------------------- /01_Reading/01_select.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SELECT 3 | Lección 8: https://youtu.be/OuJerKzV5T0?t=5618 4 | */ 5 | 6 | -- Obtiene todos los datos de la tabla "users" 7 | SELECT * FROM users; 8 | 9 | -- Obtiene todos los nombres de la tabla "users" 10 | SELECT name FROM users; 11 | 12 | -- Obtiene todos los identificadores y nombres de la tabla "users" 13 | SELECT user_id, name FROM users; -------------------------------------------------------------------------------- /01_Reading/02_distinct.sql: -------------------------------------------------------------------------------- 1 | /* 2 | DISTINCT 3 | Lección 9.1: https://youtu.be/OuJerKzV5T0?t=6089 4 | */ 5 | 6 | -- Obtiene todos los datos distintos entre sí de la tabla "users" 7 | SELECT DISTINCT * FROM users; 8 | 9 | -- Obtiene todos los valores distintos referentes al atributo edad de la tabla "users" 10 | SELECT DISTINCT age FROM users; -------------------------------------------------------------------------------- /01_Reading/03_where.sql: -------------------------------------------------------------------------------- 1 | /* 2 | WHERE 3 | Lección 9.2: https://youtu.be/OuJerKzV5T0?t=6384 4 | */ 5 | 6 | -- Filtra todos los datos de la tabla "users" con edad igual a 15 7 | SELECT * FROM users WHERE age = 15; 8 | 9 | -- Filtra todos los nombres de la tabla "users" con edad igual a 15 10 | SELECT name FROM users WHERE age = 15; 11 | 12 | -- Filtra todos los nombres distintos de la tabla "users" con edad igual a 15 13 | SELECT DISTINCT name FROM users WHERE age = 15; 14 | 15 | -- Filtra todas las edades distintas de la tabla "users" con edad igual a 15 16 | SELECT DISTINCT age FROM users WHERE age = 15; -------------------------------------------------------------------------------- /01_Reading/04_order_by.sql: -------------------------------------------------------------------------------- 1 | /* 2 | ORDER BY 3 | Lección 9.3: https://youtu.be/OuJerKzV5T0?t=6592 4 | */ 5 | 6 | -- Ordena todos los datos de la tabla "users" por edad (ascendente por defecto) 7 | SELECT * FROM users ORDER BY age; 8 | 9 | -- Ordena todos los datos de la tabla "users" por edad de manera ascendente 10 | SELECT * FROM users ORDER BY age ASC; 11 | 12 | -- Ordena todos los datos de la tabla "users" por edad de manera descendente 13 | SELECT * FROM users ORDER BY age DESC; 14 | 15 | -- Obtiene todos los datos de la tabla "users" con email igual a sara@gmail.com y los ordena por edad de manera descendente 16 | SELECT * FROM users WHERE email='sara@gmail.com' ORDER BY age DESC; 17 | 18 | -- Obtiene todos los nombres de la tabla "users" con email igual a sara@gmail.com y los ordena por edad de manera descendente 19 | SELECT name FROM users WHERE email='sara@gmail.com' ORDER BY age DESC; -------------------------------------------------------------------------------- /01_Reading/05_like.sql: -------------------------------------------------------------------------------- 1 | /* 2 | LIKE 3 | Lección 9.4: https://youtu.be/OuJerKzV5T0?t=6894 4 | */ 5 | 6 | -- Obtiene todos datos de la tabla "users" que contienen un email con el texto "gmail.com" en su parte final 7 | SELECT * FROM users WHERE email LIKE '%gmail.com'; 8 | 9 | -- Obtiene todos datos de la tabla "users" que contienen un email con el texto "sara" en su parte inicial 10 | SELECT * FROM users WHERE email LIKE 'sara%'; 11 | 12 | -- Obtiene todos datos de la tabla "users" que contienen un email una arroba 13 | SELECT * FROM users WHERE email LIKE '%@%'; -------------------------------------------------------------------------------- /01_Reading/06_and_or_not.sql: -------------------------------------------------------------------------------- 1 | /* 2 | NOT, AND, OR 3 | Lección 9.5: https://youtu.be/OuJerKzV5T0?t=7194 4 | */ 5 | 6 | -- Obtiene todos datos de la tabla "users" con email distinto a sara@gmail.com 7 | SELECT * FROM users WHERE NOT email = 'sara@gmail.com'; 8 | 9 | -- Obtiene todos datos de la tabla "users" con email distinto a sara@gmail.com y edad igual a 15 10 | SELECT * FROM users WHERE NOT email = 'sara@gmail.com' AND age = 15; 11 | 12 | -- Obtiene todos datos de la tabla "users" con email distinto a sara@gmail.com o edad igual a 15 13 | SELECT * FROM users WHERE NOT email = 'sara@gmail.com' OR age = 15; -------------------------------------------------------------------------------- /01_Reading/07_limit.sql: -------------------------------------------------------------------------------- 1 | /* 2 | LIMIT 3 | Lección 9.6: https://youtu.be/OuJerKzV5T0?t=7395 4 | */ 5 | 6 | -- Obtiene las 3 primeras filas de la tabla "users" 7 | SELECT * FROM users LIMIT 3; 8 | 9 | -- Obtiene las 2 primeras filas de la tabla "users" con email distinto a sara@gmail.com o edad igual a 15 10 | SELECT * FROM users WHERE NOT email = 'sara@gmail.com' OR age = 15 LIMIT 2; -------------------------------------------------------------------------------- /01_Reading/08_null.sql: -------------------------------------------------------------------------------- 1 | /* 2 | NULL 3 | Lección 10.2: https://youtu.be/OuJerKzV5T0?t=7615 4 | */ 5 | 6 | -- Obtiene todos datos de la tabla "users" de la tabla "users" con email nulo 7 | SELECT * FROM users WHERE email IS NULL; 8 | 9 | -- Obtiene todos datos de la tabla "users" de la tabla "users" con email no nulo 10 | SELECT * FROM users WHERE email IS NOT NULL; 11 | 12 | -- Obtiene todos datos de la tabla "users" de la tabla "users" con email no nulo y edad igual a 15 13 | SELECT * FROM users WHERE email IS NOT NULL AND age = 15; 14 | 15 | /* 16 | IFNULL 17 | Lección 10.14: https://youtu.be/OuJerKzV5T0?t=10023 18 | */ 19 | 20 | -- Obtiene el nombre, apellido y edad de la tabla "users", y si la edad es nula la muestra como 0 21 | SELECT name, surname, IFNULL(age, 0) AS age FROM users; -------------------------------------------------------------------------------- /01_Reading/09_min_max.sql: -------------------------------------------------------------------------------- 1 | /* 2 | MIN, MAX 3 | Lección 10.3: https://youtu.be/OuJerKzV5T0?t=7834 4 | */ 5 | 6 | -- Obtiene el valor menor del campo edad de la tabla "users" 7 | Select MIN(age) FROM users; 8 | 9 | -- Obtiene el valor mayor del campo edad de la tabla "users" 10 | Select MAX(age) FROM users; -------------------------------------------------------------------------------- /01_Reading/10_count.sql: -------------------------------------------------------------------------------- 1 | /* 2 | COUNT 3 | Lección 10.4: https://youtu.be/OuJerKzV5T0?t=8043 4 | */ 5 | 6 | -- Cuenta cuantas filas contiene la tabla "users" 7 | Select COUNT(*) FROM users; 8 | 9 | -- Cuenta cuantas filas contienen un dato no nulo en el campo edad de la tabla "users" 10 | Select COUNT(age) FROM users; -------------------------------------------------------------------------------- /01_Reading/11_sum.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SUM 3 | Lección 10.5: https://youtu.be/OuJerKzV5T0?t=8128 4 | */ 5 | 6 | -- Suma todos los valores del campo edad de la tabla "users" 7 | Select SUM(age) FROM users; -------------------------------------------------------------------------------- /01_Reading/12_avg.sql: -------------------------------------------------------------------------------- 1 | /* 2 | AVG 3 | Lección 10.6: https://youtu.be/OuJerKzV5T0?t=8293 4 | */ 5 | 6 | -- Obitne la media de edad de la tabla "users" 7 | Select AVG(age) FROM users; -------------------------------------------------------------------------------- /01_Reading/13_in.sql: -------------------------------------------------------------------------------- 1 | /* 2 | IN 3 | Lección 10.7: https://youtu.be/OuJerKzV5T0?t=8335 4 | */ 5 | 6 | -- Ordena todos los datos de la tabla "users" con nombre igual a brais y sara 7 | SELECT * FROM users WHERE name IN ('brais', 'sara') -------------------------------------------------------------------------------- /01_Reading/14_between.sql: -------------------------------------------------------------------------------- 1 | /* 2 | BETWEEN 3 | Lección 10.8: https://youtu.be/OuJerKzV5T0?t=8559 4 | */ 5 | 6 | -- Ordena todos los datos de la tabla "users" con edad comprendida entre 20 y 30 7 | SELECT * FROM users WHERE age BETWEEN 20 AND 30 -------------------------------------------------------------------------------- /01_Reading/15_alias.sql: -------------------------------------------------------------------------------- 1 | /* 2 | ALIAS 3 | Lección 10.9: https://youtu.be/OuJerKzV5T0?t=8667 4 | */ 5 | 6 | -- Establece el alias 'Fecha de inicio en programación' a la columna init_date 7 | SELECT name, init_date AS 'Fecha de inicio en programación' FROM users WHERE name = 'Brais' 8 | 9 | -- Consulta igual que la anterior. Representa la posibilidad de usar comillas dobles para cadenas 10 | SELECT name, init_date AS "Fecha de inicio en programación" FROM users WHERE name = "Brais" -------------------------------------------------------------------------------- /01_Reading/16_concat.sql: -------------------------------------------------------------------------------- 1 | /* 2 | CONCAT 3 | Lección 10.10: https://youtu.be/OuJerKzV5T0?t=8826 4 | */ 5 | 6 | -- Concatena en una sola columa los campos nombre y apellido 7 | SELECT CONCAT('Nombre: ', name, ', Apellidos: ', surname) FROM users 8 | 9 | -- Concatena en una sola columa los campos nombre y apellido y le establece el alias 'Nombre completo' 10 | SELECT CONCAT('Nombre: ', name, ', Apellidos: ', surname) AS 'Nombre completo' FROM users -------------------------------------------------------------------------------- /01_Reading/17_group_by.sql: -------------------------------------------------------------------------------- 1 | /* 2 | GROUP BY 3 | Lección 10.11: https://youtu.be/OuJerKzV5T0?t=8960 4 | */ 5 | 6 | -- Agrupa los resultados por edad diferente 7 | SELECT MAX(age) FROM users GROUP BY age 8 | 9 | -- Agrupa los resultados por edad diferente y cuenta cuantos registros existen de cada una 10 | SELECT COUNT(age), age FROM users GROUP BY age 11 | 12 | -- Agrupa los resultados por edad diferente, cuenta cuantos registros existen de cada una y los ordena 13 | SELECT COUNT(age), age FROM users GROUP BY age ORDER BY age ASC 14 | 15 | -- Agrupa los resultados por edad diferente mayor de 15, cuenta cuantos registros existen de cada una y los ordena 16 | SELECT COUNT(age), age FROM users WHERE age > 15 GROUP BY age ORDER BY age ASC -------------------------------------------------------------------------------- /01_Reading/18_having.sql: -------------------------------------------------------------------------------- 1 | /* 2 | HAVING 3 | Lección 10.12: https://youtu.be/OuJerKzV5T0?t=9265 4 | */ 5 | 6 | -- Cuenta cuantas filas contienen un dato no nulo en el campo edad de la tabla "users" mayor que 3 7 | SELECT COUNT(age) FROM users HAVING COUNT(age) > 3 -------------------------------------------------------------------------------- /01_Reading/19_case.sql: -------------------------------------------------------------------------------- 1 | /* 2 | CASE 3 | Lección 10.13: https://youtu.be/OuJerKzV5T0?t=9486 4 | */ 5 | 6 | -- Obtiene todos los datos de la tabla "users" y establece condiciones de visualización de cadenas de texto según el valor de la edad 7 | SELECT *, 8 | CASE 9 | WHEN age > 18 THEN 'Es mayor de edad' 10 | WHEN age = 18 THEN 'Acaba de cumplir la mayoría de edad' 11 | ELSE 'Es menor de edad' 12 | END AS '¿Es mayor de edad?' 13 | FROM users; 14 | 15 | -- Obtiene todos los datos de la tabla "users" y establece condiciones de visualización de valores booleanos según el valor de la edad 16 | SELECT *, 17 | CASE 18 | WHEN age > 17 THEN True 19 | ELSE False 20 | END AS '¿Es mayor de edad?' 21 | FROM users; -------------------------------------------------------------------------------- /02_Writing/01_insert.sql: -------------------------------------------------------------------------------- 1 | /* 2 | INSERT 3 | Lección 11.1: https://youtu.be/OuJerKzV5T0?t=10370 4 | */ 5 | 6 | -- Inserta un registro con identificador, nombre y apellido en la tabla "users" 7 | INSERT INTO users (user_id, name, surname) VALUES (8, 'María', 'López') 8 | 9 | -- Inserta un registro con nombre y apellido en la tabla "users" 10 | INSERT INTO users (name, surname) VALUES ('Paco', 'Pérez') 11 | 12 | -- Inserta un registro con identificador no correlativo, nombre y apellido en la tabla "users" 13 | INSERT INTO users (user_id, name, surname) VALUES (11, 'El', 'Merma') -------------------------------------------------------------------------------- /02_Writing/02_update.sql: -------------------------------------------------------------------------------- 1 | /* 2 | UPDATE 3 | Lección 11.2: https://youtu.be/OuJerKzV5T0?t=10621 4 | */ 5 | 6 | -- Estable el valor 21 para la edad del registro de la tabla "users" con identificador igual a 11 7 | UPDATE users SET age = '21' WHERE user_id = 11 8 | 9 | -- Estable el valor 20 para la edad del registro de la tabla "users" con identificador igual a 11 10 | UPDATE users SET age = '20' WHERE user_id = 11 11 | 12 | -- Estable edad y una fecha para registro de la tabla "users" con identificador igual a 11 13 | UPDATE users SET age = 20, init_date = '2020-10-12' WHERE user_id = 11 -------------------------------------------------------------------------------- /02_Writing/03_delete.sql: -------------------------------------------------------------------------------- 1 | /* 2 | DELETE 3 | Lección 11.3: https://youtu.be/OuJerKzV5T0?t=10920 4 | */ 5 | 6 | -- Elimina el registro de la tabla "users" con identificador igual a 11 7 | DELETE FROM users WHERE user_id = 11; -------------------------------------------------------------------------------- /03_Database/01_create_database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | CREATE DATABASE 3 | Lección 12.1: https://youtu.be/OuJerKzV5T0?t=11064 4 | */ 5 | 6 | -- Crea una base de datos llamada "test" 7 | CREATE DATABASE test; -------------------------------------------------------------------------------- /03_Database/02_drop_database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | DROP DATABASE 3 | Lección 12.2: https://youtu.be/OuJerKzV5T0?t=11180 4 | */ 5 | 6 | -- Elimina la base de datos llamada "test" 7 | DROP DATABASE test; -------------------------------------------------------------------------------- /04_Tables/01_create_table.sql: -------------------------------------------------------------------------------- 1 | /* 2 | CREATE TABLE 3 | Lección 13.1: https://youtu.be/OuJerKzV5T0?t=11292 4 | */ 5 | 6 | -- Crea una tabla llamada "persons" con nombre de columna (atributos) de tipo int, varchar y date 7 | CREATE TABLE persons ( 8 | id int, 9 | name varchar(100), 10 | age int, 11 | email varchar(50), 12 | created date 13 | ); 14 | 15 | /* 16 | CONSTRAINTS: Restricciones 17 | */ 18 | 19 | /* 20 | NOT NULL 21 | Lección 13.2: https://youtu.be/OuJerKzV5T0?t=11619 22 | */ 23 | 24 | -- NOT NULL: Obliga a que el campo id posea siempre un valor no nulo 25 | CREATE TABLE persons2 ( 26 | id int NOT NULL, 27 | name varchar(100) NOT NULL, 28 | age int, 29 | email varchar(50), 30 | created date 31 | ); 32 | 33 | /* 34 | UNIQUE 35 | Lección 13.3: https://youtu.be/OuJerKzV5T0?t=11787 36 | */ 37 | 38 | -- UNIQUE: Obliga a que el campo id posea valores diferentes 39 | CREATE TABLE persons3 ( 40 | id int NOT NULL, 41 | name varchar(100) NOT NULL, 42 | age int, 43 | email varchar(50), 44 | created datetime, 45 | UNIQUE(id) 46 | ); 47 | 48 | /* 49 | PRIMARY KEY 50 | Lección 13.4: https://youtu.be/OuJerKzV5T0?t=11911 51 | */ 52 | 53 | -- PRIMARY KEY: Establece el campo id como clave primaria para futuras relaciones con otras tablas 54 | CREATE TABLE persons4 ( 55 | id int NOT NULL, 56 | name varchar(100) NOT NULL, 57 | age int, 58 | email varchar(50), 59 | created datetime, 60 | UNIQUE(id), 61 | PRIMARY KEY(id) 62 | ); 63 | 64 | /* 65 | CHECK 66 | Lección 13.5: https://youtu.be/OuJerKzV5T0?t=12121 67 | */ 68 | 69 | -- CHECK: Establece que el campo age sólo podrá contener valores mayores o iguales a 18 70 | CREATE TABLE persons5 ( 71 | id int NOT NULL, 72 | name varchar(100) NOT NULL, 73 | age int, 74 | email varchar(50), 75 | created datetime, 76 | UNIQUE(id), 77 | PRIMARY KEY(id), 78 | CHECK(age>=18) 79 | ); 80 | 81 | /* 82 | DEFAULT 83 | Lección 13.6: https://youtu.be/OuJerKzV5T0?t=12243 84 | */ 85 | 86 | -- DEFAULT: Establece un valor por defecto en el campo created correspondiente a la fecha del sistema 87 | CREATE TABLE persons6 ( 88 | id int NOT NULL, 89 | name varchar(100) NOT NULL, 90 | age int, 91 | email varchar(50), 92 | created datetime DEFAULT CURRENT_TIMESTAMP(), 93 | UNIQUE(id), 94 | PRIMARY KEY(id), 95 | CHECK(age>=18) 96 | ); 97 | 98 | /* 99 | AUTO INCREMENT 100 | Lección 13.7: https://youtu.be/OuJerKzV5T0?t=12362 101 | */ 102 | 103 | -- AUTO_INCREMENT: Indica que el campo id siempre se va a incrementar en 1 con cada nuevo inserto 104 | CREATE TABLE persons7 ( 105 | id int NOT NULL AUTO_INCREMENT, 106 | name varchar(100) NOT NULL, 107 | age int, 108 | email varchar(50), 109 | created datetime DEFAULT CURRENT_TIMESTAMP(), 110 | UNIQUE(id), 111 | PRIMARY KEY(id), 112 | CHECK(age>=18) 113 | ); -------------------------------------------------------------------------------- /04_Tables/02_drop_table.sql: -------------------------------------------------------------------------------- 1 | /* 2 | DROP TABLE 3 | Lección 13.8: https://youtu.be/OuJerKzV5T0?t=12412 4 | */ 5 | 6 | -- Elimina la tabla llamada "persons8" 7 | DROP TABLE persons8; -------------------------------------------------------------------------------- /04_Tables/03_alter_table.sql: -------------------------------------------------------------------------------- 1 | /* 2 | ALTER TABLE 3 | Lección 13.9: https://youtu.be/OuJerKzV5T0?t=12461 4 | */ 5 | 6 | /* 7 | ADD 8 | Lección 13.10: https://youtu.be/OuJerKzV5T0?t=12578 9 | */ 10 | 11 | -- ADD: Añade un nuevo atributo surname a la tabla "persons8" 12 | ALTER TABLE persons8 13 | ADD surname varchar(150); 14 | 15 | /* 16 | RENAME COLUMN 17 | Lección 13.11: https://youtu.be/OuJerKzV5T0?t=12624 18 | */ 19 | 20 | -- RENAME COLUMN: Renombra el atributo surname a description en la tabla "persons8" 21 | ALTER TABLE persons8 22 | RENAME COLUMN surname TO description; 23 | 24 | /* 25 | MODIFY COLUMN 26 | Lección 13.12: https://youtu.be/OuJerKzV5T0?t=12675 27 | */ 28 | 29 | -- MODIFY COLUMN: Modifica el tipo de dato del atributo description en la tabla "persons8" 30 | ALTER TABLE persons8 31 | MODIFY COLUMN description varchar(250); 32 | 33 | /* 34 | DROP COLUMN 35 | Lección 13.13: https://youtu.be/OuJerKzV5T0?t=12712 36 | */ 37 | 38 | -- DROP COLUMN: Elimina el atributo description en la tabla "persons8" 39 | ALTER TABLE persons8 40 | DROP COLUMN description; -------------------------------------------------------------------------------- /04_Tables/04_relationships.sql: -------------------------------------------------------------------------------- 1 | /* 2 | TIPOS DE RELACIONES 3 | */ 4 | 5 | /* 6 | Relación 1:1 (uno a uno) 7 | Lección 15.1: https://youtu.be/OuJerKzV5T0?t=13490 8 | Relación que indica que un registro en la tabla A se relaciona 9 | con un sólo registro en la tabla B y viceversa. 10 | */ 11 | 12 | -- El campo user_id de la tabla "dni" es clave foránea de la clave primaria user_id de la tabla "users" 13 | -- (Un usuario sólo puede tener un DNI. Un DNI sólo puede estar asociado a un usuario) 14 | CREATE TABLE dni( 15 | dni_id int AUTO_INCREMENT PRIMARY KEY, 16 | dni_number int NOT NULL, 17 | user_id int, 18 | UNIQUE(dni_id), 19 | FOREIGN KEY(user_id) REFERENCES users(user_id) 20 | ); 21 | 22 | /* 23 | Relación 1:N (uno a muchos) 24 | Lección 15.2: https://youtu.be/OuJerKzV5T0?t=13732 25 | Relación que indica que un registro en la tabla A puede tener varios registros relacionados en la 26 | tabla B, pero un registro en la tabla B se relaciona con un sólo registro en la tabla A. 27 | */ 28 | 29 | CREATE TABLE companies( 30 | company_id int AUTO_INCREMENT PRIMARY KEY, 31 | name varchar(100) NOT NULL 32 | ); 33 | ALTER TABLE users 34 | ADD company_id int; 35 | 36 | -- El campo company_id de la tabla "users" es clave foránea de la clave primaria company_id de la tabla "companies" 37 | -- (Un empleado (usuario) sólo puede tener una empresa, pero una empresa puede tener muchos empleados (usuarios)) 38 | ALTER TABLE users 39 | ADD CONSTRAINT fk_companies 40 | FOREIGN KEY(company_id) REFERENCES companies(company_id) 41 | 42 | /* 43 | Relación N:M (muchos a muchos) 44 | Lección 15.3: https://youtu.be/OuJerKzV5T0?t=14313 45 | Relación que indica que un un registro en la tabla A puede relacionarse 46 | con varios registros en la tabla B y viceversa. 47 | Requiere una tabla intermedia o de unión para establecer la relación. 48 | */ 49 | 50 | CREATE TABLE languages( 51 | language_id int AUTO_INCREMENT PRIMARY KEY, 52 | name varchar(100) NOT NULL 53 | ); 54 | 55 | -- El campo user_id y language_id de la tabla intermedia "users_languages" es clave foránea de las 56 | -- claves primarias user_id de la tabla "users" y de language_id de la tabla "languages" 57 | -- Un usuario puede conoces muchos lenguajes. Un lenguaje puede ser conocido por muchos usuarios. 58 | CREATE TABLE users_languages( 59 | users_language_id int AUTO_INCREMENT PRIMARY KEY, 60 | user_id int, 61 | language_id int, 62 | FOREIGN KEY(user_id) REFERENCES users(user_id), 63 | FOREIGN KEY(language_id) REFERENCES languages(language_id), 64 | UNIQUE (user_id, language_id) 65 | ); 66 | 67 | /* 68 | Relación de Auto-Referencia 69 | Relación que indica que un un registro en la tabla A puede 70 | relacionarse con otro registro de la tabla A. 71 | */ 72 | 73 | /* 74 | INSERT y UPDATE para trabajar con JOIN 75 | */ 76 | 77 | /* 78 | 1:1 79 | Lección 16.1: https://youtu.be/OuJerKzV5T0?t=14994 80 | */ 81 | 82 | -- "dni" (Relación 1:1) 83 | INSERT INTO dni (dni_number, user_id) VALUES (11111111, 1); 84 | INSERT INTO dni (dni_number, user_id) VALUES (22222222, 2); 85 | INSERT INTO dni (dni_number, user_id) VALUES (33333333, 3); 86 | INSERT INTO dni (dni_number) VALUES (44444444); 87 | 88 | /* 89 | 1:N 90 | Lección 16.2: https://youtu.be/OuJerKzV5T0?t=15203 91 | */ 92 | 93 | -- "companies" y "users" (Relación 1:N) 94 | INSERT INTO companies (name) VALUES ('MoureDev'); 95 | INSERT INTO companies (name) VALUES ('Apple'); 96 | INSERT INTO companies (name) VALUES ('Google'); 97 | 98 | UPDATE users SET company_id = 1 WHERE user_id = 1; 99 | UPDATE users SET company_id = 2 WHERE user_id = 3; 100 | UPDATE users SET company_id = 3 WHERE user_id = 4; 101 | UPDATE users SET company_id = 1 WHERE user_id = 7; 102 | 103 | /* 104 | N:M 105 | Lección 16.3: https://youtu.be/OuJerKzV5T0?t=15474 106 | */ 107 | 108 | -- "languages" y "users_languages" (Relación N:M) 109 | INSERT INTO languages (name) VALUES ('Swift'); 110 | INSERT INTO languages (name) VALUES ('Kotlin'); 111 | INSERT INTO languages (name) VALUES ('JavaScript'); 112 | INSERT INTO languages (name) VALUES ('Java'); 113 | INSERT INTO languages (name) VALUES ('Python'); 114 | INSERT INTO languages (name) VALUES ('C#'); 115 | INSERT INTO languages (name) VALUES ('COBOL'); 116 | 117 | INSERT INTO users_languages (user_id, language_id) VALUES (1, 1); 118 | INSERT INTO users_languages (user_id, language_id) VALUES (1, 2); 119 | INSERT INTO users_languages (user_id, language_id) VALUES (1, 5); 120 | INSERT INTO users_languages (user_id, language_id) VALUES (2, 3); 121 | INSERT INTO users_languages (user_id, language_id) VALUES (2, 5); -------------------------------------------------------------------------------- /05_Join/01_inner_join.sql: -------------------------------------------------------------------------------- 1 | /* 2 | INNER JOIN (JOIN) 3 | Lección 17.1: https://youtu.be/OuJerKzV5T0?t=16101 4 | */ 5 | 6 | -- Realiza un JOIN de manera incorrecta, ya que no existe un campo de relación 7 | SELECT * FROM users 8 | INNER JOIN dni; 9 | 10 | -- Obtiene los datos de los usuarios que tienen un dni 11 | SELECT * FROM users 12 | INNER JOIN dni 13 | ON users.user_id = dni.user_id; 14 | 15 | -- Obtiene los datos de los usuarios que tienen un dni (JOIN es lo mismo que INNER JOIN) 16 | SELECT * FROM users 17 | JOIN dni 18 | ON users.user_id = dni.user_id; 19 | 20 | -- Obtiene el nombre y el dni de los usuarios que tienen un dni y los ordena por edad 21 | SELECT name, dni_number FROM users 22 | JOIN dni 23 | ON users.user_id = dni.user_id 24 | ORDER BY age ASC; 25 | 26 | -- Obtiene los datos de los usuarios que tienen empresa 27 | SELECT * FROM users 28 | JOIN companies 29 | ON users.company_id = companies.company_id; 30 | 31 | -- Obtiene los datos de las empresas que tienen usuarios 32 | SELECT * FROM companies 33 | JOIN users 34 | ON users.company_id = companies.company_id; 35 | 36 | -- Obtiene el nombre de las empresas junto al nombre de sus usuarios 37 | SELECT companies.name, users.name FROM companies 38 | JOIN users 39 | ON companies.company_id = users.company_id; 40 | 41 | -- Obtiene los nombres de usuarios junto a los lenguajes que conocen 42 | SELECT users.name, languages.name 43 | FROM users_languages 44 | JOIN users ON users_languages.user_id=users.user_id 45 | JOIN languages ON users_languages.language_id=languages.language_id; 46 | 47 | -- Obtiene los nombres de usuarios junto a los lenguajes que conocen (utilizando otro orden de relación entre tablas) 48 | SELECT users.name, languages.name 49 | FROM users 50 | JOIN users_languages ON users.user_id=users_languages.user_id 51 | JOIN languages ON users_languages.language_id=languages.language_id; -------------------------------------------------------------------------------- /05_Join/02_left_join.sql: -------------------------------------------------------------------------------- 1 | /* 2 | LEFT JOIN 3 | Lección 17.2: https://youtu.be/OuJerKzV5T0?t=17045 4 | */ 5 | 6 | -- Obtiene los datos de todos los usuarios junto a su dni (lo tenga o no) 7 | SELECT * FROM users 8 | LEFT JOIN dni 9 | ON users.user_id = dni.user_id; 10 | 11 | -- Obtiene el nombre de todos los usuarios junto a su dni (lo tenga o no) 12 | SELECT name, dni_number FROM users 13 | LEFT JOIN dni 14 | ON users.user_id = dni.user_id; 15 | 16 | -- Obtiene todos los dni junto al nombre de su usuario (lo tenga o no) 17 | SELECT name, dni_number FROM dni 18 | LEFT JOIN users 19 | ON users.user_id = dni.user_id; 20 | 21 | -- Obtiene el nombre de todos los usuarios junto a sus lenguajes (los tenga o no) 22 | SELECT users.name, languages.name 23 | FROM users 24 | LEFT JOIN users_languages ON users.user_id=users_languages.user_id 25 | LEFT JOIN languages ON users_languages.language_id=languages.language_id; -------------------------------------------------------------------------------- /05_Join/03_right_join.sql: -------------------------------------------------------------------------------- 1 | /* 2 | RIGHT JOIN 3 | Lección 17.3: https://youtu.be/OuJerKzV5T0?t=17399 4 | */ 5 | 6 | -- Obtiene todos los dni junto a su usuario (lo tenga o no) 7 | SELECT * FROM users 8 | RIGHT JOIN dni 9 | ON users.user_id = dni.user_id; 10 | 11 | -- Obtiene todos los dni junto al nombre de su usuario (lo tenga o no) 12 | SELECT name, dni_number FROM users 13 | RIGHT JOIN dni 14 | ON users.user_id = dni.user_id; 15 | 16 | -- Obtiene el nombre de todos los usuarios junto a su dni (lo tenga o no) 17 | SELECT name, dni_number FROM dni 18 | RIGHT JOIN users 19 | ON users.user_id = dni.user_id; 20 | 21 | -- Obtiene el nombre de todos los lenguajes junto a sus usuarios (los tenga o no) 22 | SELECT users.name, languages.name 23 | FROM users 24 | RIGHT JOIN users_languages ON users.user_id=users_languages.user_id 25 | RIGHT JOIN languages ON users_languages.language_id=languages.language_id; -------------------------------------------------------------------------------- /05_Join/04_union.sql: -------------------------------------------------------------------------------- 1 | /* 2 | UNION (FULL JOIN) 3 | Lección 17.4: https://youtu.be/OuJerKzV5T0?t=17536 4 | */ 5 | 6 | -- UNION elimina duplicados 7 | 8 | -- Obtiene todos los id de usuarios de las tablas dni y usuarios (exista o no relación) 9 | SELECT users.user_id AS u_user_id, dni.user_id AS d_user_id 10 | FROM users 11 | LEFT JOIN dni 12 | ON users.user_id = dni.user_id 13 | UNION 14 | SELECT users.user_id AS user_id, dni.user_id AS d_user_id 15 | FROM users 16 | RIGHT JOIN dni 17 | ON users.user_id = dni.user_id; 18 | 19 | -- Obtiene todos los datos de las tablas dni y usuarios (exista o no relación) 20 | SELECT * 21 | FROM users 22 | LEFT JOIN dni 23 | ON users.user_id = dni.user_id 24 | UNION 25 | SELECT * 26 | FROM users 27 | RIGHT JOIN dni 28 | ON users.user_id = dni.user_id; 29 | 30 | -- UNION ALL mantiene duplicados -------------------------------------------------------------------------------- /06_Advanced/01_index.sql: -------------------------------------------------------------------------------- 1 | /* 2 | INDEX 3 | Lección 18.1: https://youtu.be/OuJerKzV5T0?t=18219 4 | */ 5 | 6 | -- Crea un índice llamado "idx_name" en la tabla "users" asociado al campo "name" 7 | CREATE INDEX idx_name ON users(name); 8 | 9 | -- Crea un índice único llamado "idx_name" en la tabla "users" asociado al campo "name" 10 | CREATE UNIQUE INDEX idx_name ON users(name); 11 | 12 | -- Crea un índice llamado "idx_name_surname" en la tabla "users" asociado a los campos "name" y "surname" 13 | CREATE UNIQUE INDEX idx_name_surname ON users(name, surname); 14 | 15 | -- Elimina el índice llamado "idx_name" 16 | DROP INDEX idx_name ON users; -------------------------------------------------------------------------------- /06_Advanced/02_triggers.sql: -------------------------------------------------------------------------------- 1 | /* 2 | TRIGGERS 3 | Lección 18.2: https://youtu.be/OuJerKzV5T0?t=18961 4 | */ 5 | 6 | -- Crea una tabla de historial para usar en el ejemplo 7 | CREATE TABLE `hello_mysql`.`email_history` ( 8 | `email_history_id` INT NOT NULL AUTO_INCREMENT, 9 | `user_id` INT NOT NULL, 10 | `email` VARCHAR(100) NULL, 11 | PRIMARY KEY (`email_history_id`), 12 | UNIQUE INDEX `email_history_id_UNIQUE` (`email_history_id` ASC) VISIBLE); 13 | 14 | -- Crea un trigger llamado "tg_email" que guarda el email previo en la tabla "email_history" siempre 15 | -- que se actualiza el campo "email" en la tabla "users" 16 | 17 | -- DELIMITER es una directiva que sirve para cambiar el delimitador de instrucciones SQL, que por defecto es ; 18 | -- Se utiliza cuando se define un bloque de código como un procedimiento donde se requieren múltiples 19 | -- instrucciones SQL terminadas con punto y coma dentro de un mismo bloque. 20 | DELIMITER // 21 | CREATE TRIGGER tg_email 22 | AFTER UPDATE ON users 23 | FOR EACH ROW 24 | BEGIN 25 | IF OLD.email <> NEW.email THEN 26 | INSERT INTO email_history (user_id, email) 27 | VALUES (OLD.user_id, OLD.email); 28 | END IF; 29 | END// 30 | 31 | -- Actualiza el campo "email" del usuario 1 la tabla "users" para probar el trigger 32 | UPDATE users SET email = 'mouredev@gmail.com' WHERE user_id = 1 33 | 34 | -- Elimina el trigger llamado "tg_email" 35 | DROP TRIGGER tg_email; -------------------------------------------------------------------------------- /06_Advanced/03_views.sql: -------------------------------------------------------------------------------- 1 | /* 2 | VIEWS 3 | Lección 18.3: https://youtu.be/OuJerKzV5T0?t=19663 4 | */ 5 | 6 | -- Crea unaa vista llamada "v_adult_users" con los nombres y edades de usuarios de la table "users" 7 | -- que tienen una edad igual o mayor a 18 años. 8 | CREATE VIEW v_adult_users AS 9 | SELECT name, age 10 | FROM users 11 | WHERE age >= 18; 12 | 13 | SELECT * FROM v_adult_users; 14 | 15 | -- Elimina la vista llamada "v_adult_users" 16 | DROP VIEW v_adult_users; -------------------------------------------------------------------------------- /06_Advanced/04_stored_procedures.sql: -------------------------------------------------------------------------------- 1 | /* 2 | STORED PROCEDURES 3 | Lección 18.4: https://youtu.be/OuJerKzV5T0?t=20033 4 | */ 5 | 6 | -- Crea un procedimiento almacenado llamado "p_all_users" que obtiene todos los datos de "users" 7 | DELIMITER // 8 | CREATE PROCEDURE p_all_users() 9 | BEGIN 10 | SELECT * FROM users; 11 | END// 12 | 13 | -- Invoca al procedimiento almacenado llamado "p_all_users" 14 | CALL p_all_users; 15 | 16 | -- Crea un procedimiento almacenado llamado "p_age_users" parametrizado para 17 | -- obtener usuarios con edad variable 18 | DELIMITER // 19 | CREATE PROCEDURE p_age_users(IN age_param int) 20 | BEGIN 21 | SELECT * FROM users WHERE age = age_param; 22 | END// 23 | 24 | -- Invoca al procedimiento almacenado llamado "p_age_users" con un parámetro de valor 30 25 | CALL p_age_users(30); 26 | 27 | -- Elimina el procedimiento almacenado llamado "p_age_users" 28 | DROP PROCEDURE p_age_users; -------------------------------------------------------------------------------- /06_Advanced/05_transactions.sql: -------------------------------------------------------------------------------- 1 | /* 2 | TRANSACTIONS 3 | Lección 18.5: https://youtu.be/OuJerKzV5T0?t=20501 4 | */ 5 | 6 | -- Inicia una nueva transacción. Desde este punto, todas las modificaciones realizadas en la 7 | -- base de datos son temporales y solo son visibles dentro de esta transacción 8 | START TRANSACTION 9 | 10 | -- Finaliza una transacción con éxito. Cuando se ejecuta, todos los cambios realizados en la 11 | -- base de datos durante la transacción actual se hacen permanentes y visibles 12 | COMMIT 13 | 14 | -- Deshace las operaciones realizadas en una transacción, revirtiendo la base de datos 15 | -- al estado en que se encontraba antes de iniciar la transacción 16 | ROLLBACK -------------------------------------------------------------------------------- /06_Advanced/06_connectors.py: -------------------------------------------------------------------------------- 1 | # CONNECTORS 2 | # Lección 19.1: https://youtu.be/OuJerKzV5T0?t=20876 3 | # Lección 19.2: https://youtu.be/OuJerKzV5T0?t=21149 4 | 5 | # Ejemplo de conexión desde Python a una base de datos local 6 | # Se ejemplifica cómo evitar SQL INJECTION 7 | import mysql.connector 8 | 9 | 10 | def print_user(user): 11 | 12 | config = { 13 | "host": "127.0.0.1", 14 | "port": "3306", 15 | "database": "hello_mysql", 16 | "user": "root", 17 | "password": "root1234" 18 | } 19 | 20 | # config = { 21 | # "host": "bpw0hq9h09e7mqicjhtl-mysql.services.clever-cloud.com", 22 | # "port": "3306", 23 | # "database": "bpw0hq9h09e7mqicjhtl", 24 | # "user": "uqzby88erlhvkrty", 25 | # "password": "oePXiCOHdU1WRV80NPyv" 26 | # } 27 | 28 | connection = mysql.connector.connect(**config) 29 | cursor = connection.cursor() 30 | 31 | query = "SELECT * FROM users WHERE name=%s;" 32 | print(query) 33 | cursor.execute(query, (user,)) 34 | result = cursor.fetchall() 35 | 36 | for row in result: 37 | print(row) 38 | 39 | cursor.close() 40 | connection.close() 41 | 42 | 43 | print_user("Brais") 44 | # print_user("'; UPDATE users SET age = '15' WHERE user_id = 1; --") 45 | -------------------------------------------------------------------------------- /Images/header.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mouredev/hello-sql/d3cd3a0f12053438d5c3f6be9bd58e3bfdc47317/Images/header.jpg -------------------------------------------------------------------------------- /Images/pro.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mouredev/hello-sql/d3cd3a0f12053438d5c3f6be9bd58e3bfdc47317/Images/pro.jpg -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hello SQL 2 | 3 | [![SQL](https://img.shields.io/badge/MySQL-8.0+-f29221?style=for-the-badge&logo=mysql&logoColor=white&labelColor=101010)](https://mysql.com) 4 | [![SQL](https://img.shields.io/badge/PostgreSQL-16+-699eca?style=for-the-badge&logo=postgresql&logoColor=white&labelColor=101010)](https://postgresql.org) 5 | 6 | ## Curso completo para aprender los fundamentos del lenguaje SQL y bases de datos relacionales 7 | 8 | ![](./Images/header.jpg) 9 | 10 | ### 7 horas | +80 lecciones | +50 comandos | con código | desde cero | completo | gratis 11 | 12 | ### Proyecto realizado durante emisiones en directo desde [Twitch](https://twitch.tv/mouredev) 13 | > ##### Si consideras útil el curso, apóyalo haciendo "★ Star" en el repositorio. ¡Gracias! 14 | 15 | ## Curso completo en vídeo 16 | 17 | 18 | 19 | **Este es el curso completo en [vídeo](https://youtu.be/OuJerKzV5T0) de 7 horas en YouTube asociado al código de este repositorio.** 20 | 21 | ## Lecciones y código 22 | 23 | [INTRODUCCIÓN](https://youtu.be/OuJerKzV5T0) 24 | 25 | 1. [Bases de datos SQL](https://youtu.be/OuJerKzV5T0?t=234) 26 | 2. [Sistema de gestión de base de datos](https://youtu.be/OuJerKzV5T0?t=1011) 27 | 3. [Fundamentos de SQL y bases de datos](https://youtu.be/OuJerKzV5T0?t=1347) 28 | 4. [Configuración e instalación](https://youtu.be/OuJerKzV5T0?t=2753) 29 | 5. [Primeros pasos](https://youtu.be/OuJerKzV5T0?t=3282) 30 | 6. [Conexión y cliente SQL](https://youtu.be/OuJerKzV5T0?t=3555) 31 | 7. [Inicialización de datos](https://youtu.be/OuJerKzV5T0?t=4381) 32 | 8. [Consulta de datos: `SELECT`](https://youtu.be/OuJerKzV5T0?t=5618) ➔ [[Código]](./01_Reading/01_select.sql) 33 | 9. [Modificadores: Parte 1](https://youtu.be/OuJerKzV5T0?t=6074) 34 | 1. [`DISTINCT`](https://youtu.be/OuJerKzV5T0?t=6089) ➔ [[Código]](./01_Reading/02_distinct.sql) 35 | 2. [`WHERE`](https://youtu.be/OuJerKzV5T0?t=6384) ➔ [[Código]](./01_Reading/03_where.sql) 36 | 3. [`ORDER BY`](https://youtu.be/OuJerKzV5T0?t=6592) ➔ [[Código]](./01_Reading/04_order_by.sql) 37 | 4. [`LIKE`](https://youtu.be/OuJerKzV5T0?t=6894) ➔ [[Código]](./01_Reading/05_like.sql) 38 | 5. [`AND, OR, NOT`](https://youtu.be/OuJerKzV5T0?t=7194) ➔ [[Código]](./01_Reading/06_and_or_not.sql) 39 | 6. [`LIMIT`](https://youtu.be/OuJerKzV5T0?t=7395) ➔ [[Código]](./01_Reading/07_limit.sql) 40 | 10. [Modificadores: Parte 2](https://youtu.be/OuJerKzV5T0?t=7503) 41 | 1. [`COMMENTS`](https://youtu.be/OuJerKzV5T0?t=7512) ➔ [[Código]](./01_Reading/00_comments.sql) 42 | 2. [`NULL`](https://youtu.be/OuJerKzV5T0?t=7615) ➔ [[Código]](./01_Reading/08_null.sql) 43 | 3. [`MIN, MAX`](https://youtu.be/OuJerKzV5T0?t=7834) ➔ [[Código]](./01_Reading/09_min_max.sql) 44 | 4. [`COUNT`](https://youtu.be/OuJerKzV5T0?t=8043) ➔ [[Código]](./01_Reading/10_count.sql) 45 | 5. [`SUM`](https://youtu.be/OuJerKzV5T0?t=8128) ➔ [[Código]](./01_Reading/11_sum.sql) 46 | 6. [`AVG`](https://youtu.be/OuJerKzV5T0?t=8293) ➔ [[Código]](./01_Reading/12_avg.sql) 47 | 7. [`IN`](https://youtu.be/OuJerKzV5T0?t=8335) ➔ [[Código]](./01_Reading/13_in.sql) 48 | 8. [`BETWEEN`](https://youtu.be/OuJerKzV5T0?t=8559) ➔ [[Código]](./01_Reading/14_between.sql) 49 | 9. [`ALIAS`](https://youtu.be/OuJerKzV5T0?t=8667) ➔ [[Código]](./01_Reading/15_alias.sql) 50 | 10. [`CONCAT`](https://youtu.be/OuJerKzV5T0?t=8826) ➔ [[Código]](./01_Reading/16_concat.sql) 51 | 11. [`GROUP BY`](https://youtu.be/OuJerKzV5T0?t=8960) ➔ [[Código]](./01_Reading/17_group_by.sql) 52 | 12. [`HAVING`](https://youtu.be/OuJerKzV5T0?t=9265) ➔ [[Código]](./01_Reading/18_having.sql) 53 | 13. [`CASE`](https://youtu.be/OuJerKzV5T0?t=9486) ➔ [[Código]](./01_Reading/19_case.sql) 54 | 14. [`IFNULL`](https://youtu.be/OuJerKzV5T0?t=10023) ➔ [[Código]](./01_Reading/08_null.sql) 55 | 15. [Otros modificadores](https://youtu.be/OuJerKzV5T0?t=10191) 56 | 11. [Escritura de datos](https://youtu.be/OuJerKzV5T0?t=10289) 57 | 1. [`INSERT`](https://youtu.be/OuJerKzV5T0?t=10370) ➔ [[Código]](./02_Writing/01_insert.sql) 58 | 2. [`UPDATE`](https://youtu.be/OuJerKzV5T0?t=10621) ➔ [[Código]](./02_Writing/02_update.sql) 59 | 3. [`DELETE`](https://youtu.be/OuJerKzV5T0?t=10920) ➔ [[Código]](./02_Writing/03_delete.sql) 60 | 12. [Administración de la base de datos](https://youtu.be/OuJerKzV5T0?t=11021) 61 | 1. [`CREATE DATABASE`](https://youtu.be/OuJerKzV5T0?t=11064) ➔ [[Código]](./03_Database/01_create_database.sql) 62 | 2. [`DROP DATABASE`](https://youtu.be/OuJerKzV5T0?t=11180) ➔ [[Código]](./03_Database/02_drop_database.sql) 63 | 13. [Administración de tablas](https://youtu.be/OuJerKzV5T0?t=11021) 64 | 1. [`CREATE TABLE`](https://youtu.be/OuJerKzV5T0?t=11292) ➔ [[Código]](./04_Tables/01_create_table.sql) 65 | 2. [`NOT NULL`](https://youtu.be/OuJerKzV5T0?t=11619) ➔ [[Código]](./04_Tables/01_create_table.sql) 66 | 3. [`UNIQUE`](https://youtu.be/OuJerKzV5T0?t=11787) ➔ [[Código]](./04_Tables/01_create_table.sql) 67 | 4. [`PRIMARY KEY`](https://youtu.be/OuJerKzV5T0?t=11911) ➔ [[Código]](./04_Tables/01_create_table.sql) 68 | 5. [`CHECK`](https://youtu.be/OuJerKzV5T0?t=12121) ➔ [[Código]](./04_Tables/01_create_table.sql) 69 | 6. [`DEFAULT`](https://youtu.be/OuJerKzV5T0?t=12243) ➔ [[Código]](./04_Tables/01_create_table.sql) 70 | 7. [`AUTO INCREMENT`](https://youtu.be/OuJerKzV5T0?t=12362) ➔ [[Código]](./04_Tables/01_create_table.sql) 71 | 8. [`DROP TABLE`](https://youtu.be/OuJerKzV5T0?t=12412) ➔ [[Código]](./04_Tables/02_drop_table.sql) 72 | 9. [`ALTER TABLE`](https://youtu.be/OuJerKzV5T0?t=12461) ➔ [[Código]](./04_Tables/03_alter_table.sql) 73 | 10. [`ADD`](https://youtu.be/OuJerKzV5T0?t=12578) ➔ [[Código]](./04_Tables/03_alter_table.sql) 74 | 11. [`RENAME COLUMN`](https://youtu.be/OuJerKzV5T0?t=12624) ➔ [[Código]](./04_Tables/03_alter_table.sql) 75 | 12. [`MODIFY COLUMN`](https://youtu.be/OuJerKzV5T0?t=12675) ➔ [[Código]](./04_Tables/03_alter_table.sql) 76 | 13. [`DROP COLUMN`](https://youtu.be/OuJerKzV5T0?t=12712) ➔ [[Código]](./04_Tables/03_alter_table.sql) 77 | 14. [Relaciones entre tablas](https://youtu.be/OuJerKzV5T0?t=12781) 78 | 1. [RELACIÓN `1:1`](https://youtu.be/OuJerKzV5T0?t=12852) 79 | 2. [RELACIÓN `1:N`](https://youtu.be/OuJerKzV5T0?t=13117) 80 | 3. [RELACIÓN `N:M`](https://youtu.be/OuJerKzV5T0?t=13208) 81 | 4. [AUTOREFERENCIA](https://youtu.be/OuJerKzV5T0?t=13343) 82 | 15. [Creación de tablas relacionadas](https://youtu.be/OuJerKzV5T0?t=13428) 83 | 1. [TABLAS `1:1`](https://youtu.be/OuJerKzV5T0?t=13490) ➔ [[Código]](./04_Tables/04_relationships.sql) 84 | 2. [TABLAS `1:N`](https://youtu.be/OuJerKzV5T0?t=13732) ➔ [[Código]](./04_Tables/04_relationships.sql) 85 | 3. [TABLAS `N:M`](https://youtu.be/OuJerKzV5T0?t=14313) ➔ [[Código]](./04_Tables/04_relationships.sql) 86 | 16. [Almacenamiento de datos relacionados](https://youtu.be/OuJerKzV5T0?t=14635) 87 | 1. [DATOS `1:1`](https://youtu.be/OuJerKzV5T0?t=14994) ➔ [[Código]](./04_Tables/04_relationships.sql) 88 | 2. [DATOS `1:N`](https://youtu.be/OuJerKzV5T0?t=15203) ➔ [[Código]](./04_Tables/04_relationships.sql) 89 | 3. [DATOS `N:M`](https://youtu.be/OuJerKzV5T0?t=15474) ➔ [[Código]](./04_Tables/04_relationships.sql) 90 | 17. [Consulta de datos relacionados](https://youtu.be/OuJerKzV5T0?t=16013) 91 | 1. [`INNER JOIN`](https://youtu.be/OuJerKzV5T0?t=16101) ➔ [[Código]](./05_Join/01_inner_join.sql) 92 | 2. [`LEFT JOIN`](https://youtu.be/OuJerKzV5T0?t=17045) ➔ [[Código]](./05_Join/02_left_join.sql) 93 | 3. [`RIGHT JOIN`](https://youtu.be/OuJerKzV5T0?t=17399) ➔ [[Código]](./05_Join/03_right_join.sql) 94 | 4. [`UNION`](https://youtu.be/OuJerKzV5T0?t=17536) ➔ [[Código]](./05_Join/04_union.sql) 95 | 18. [Conceptos avanzados](https://youtu.be/OuJerKzV5T0?t=18196) 96 | 1. [`INDEX`](https://youtu.be/OuJerKzV5T0?t=18219) ➔ [[Código]](./06_Advanced/01_index.sql) 97 | 2. [`TRIGGER`](https://youtu.be/OuJerKzV5T0?t=18961) ➔ [[Código]](./06_Advanced/02_triggers.sql) 98 | 3. [`VIEW`](https://youtu.be/OuJerKzV5T0?t=19663) ➔ [[Código]](./06_Advanced/03_views.sql) 99 | 4. [`STORED PROCEDURE`](https://youtu.be/OuJerKzV5T0?t=20033) ➔ [[Código]](./06_Advanced/04_stored_procedures.sql) 100 | 5. [TRANSACCIONES](https://youtu.be/OuJerKzV5T0?t=20501) ➔ [[Código]](./06_Advanced/05_transactions.sql) 101 | 6. [CONCURRENCIA](https://youtu.be/OuJerKzV5T0?t=20701) 102 | 19. [Conexión desde código](https://youtu.be/OuJerKzV5T0?t=20847) 103 | 1. [CONECTORES](https://youtu.be/OuJerKzV5T0?t=20876) ➔ [[Código]](./06_Advanced/06_connectors.py) 104 | 2. [SQL INJECTION](https://youtu.be/OuJerKzV5T0?t=21149) ➔ [[Código]](./06_Advanced/06_connectors.py) 105 | 20. [Otros clientes SQL](https://youtu.be/OuJerKzV5T0?t=21641) 106 | 21. [PostgresSQL](https://youtu.be/OuJerKzV5T0?t=22070) 107 | 22. [Despliegue en la nube](https://youtu.be/OuJerKzV5T0?t=23214) 108 | 23. [Próximos pasos](https://youtu.be/OuJerKzV5T0?t=24283) 109 | 110 | [CONCLUSIONES](https://youtu.be/OuJerKzV5T0?t=24678) 111 | 112 | Durante el curso aprenderemos los fundamentos del lenguaje SQL y las bases de datos relacionales con ejemplos prácticos. 113 | Nos centraremos en MySQL para llevar a cabo las clases, ya que es uno de los más usados en enseñanza y a nivel profesional. También utilizaremos PostgreSQL, por ser una de las bases de datos más populares de la actualidad. De todas formas, no debe preocuparte el motor de bases de datos utilizado, ya que SQL es un lenguaje estándar, por lo que se utilizará prácticamente igual en todas ellas. Una vez lo conozcas no tendrá dificultad alguna llevar esos conocimientos a otros sistemas. 114 | 115 | Todo el código creado durante el curso está disponible para que puedas consultarlo junto a su explicación. 116 | 117 | > En el servidor de la comunidad de [Discord](https://discord.gg/mouredev) dispones de un canal llamado "💾bases-de-datos" para que puedas comentar lo que quieras. 118 | 119 | ## Enlaces de interés 120 | 121 | * [Documentación SQL](https://www.w3schools.com/sql/default.asp) 122 | * [MySQL](https://mysql.com) 123 | * [Descarga MySQL](https://dev.mysql.com/downloads/mysql/) 124 | * [CLI MySQL](https://dev.mysql.com/doc/refman/8.0/en/mysql.html) 125 | * [MySQL Workbench](https://dev.mysql.com/downloads/workbench) 126 | * [PostgreSQL](https://www.postgresql.org) 127 | * [Clever Cloud](https://www.clever-cloud.com) 128 | 129 | ## Únete al campus de programación de la comunidad 130 | 131 | ![https://mouredev.pro](./Images/pro.jpg) 132 | 133 | #### Te presento [mouredev pro](https://mouredev.pro), mi proyecto más importante para ayudarte a estudiar programación y desarrollo de software de manera diferente. 134 | 135 | > **¿Buscas un extra?** Aquí encontrarás mis cursos editados por lecciones individuales, para avanzar a tu ritmo y guardar el progreso. También dispondrás de ejercicios y correcciones, test para validar tus conocimientos, examen y certificado público de finalización, soporte, foro de estudiantes, reunionnes grupales, cursos exclusivos y mucho más. 136 | > 137 | > Entra en **[mouredev.pro](https://mouredev.pro)** y utiliza el cupón **"PRO"** con un 10% de descuento en tu primera suscripción. 138 | 139 | ## ![https://mouredev.com](https://raw.githubusercontent.com/mouredev/mouredev/master/mouredev_emote.png) Hola, mi nombre es Brais Moure. 140 | ### Freelance full-stack iOS & Android engineer 141 | 142 | [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCxPD7bsocoAMq8Dj18kmGyQ?style=social)](https://youtube.com/mouredevapps?sub_confirmation=1) 143 | [![Twitch Status](https://img.shields.io/twitch/status/mouredev?style=social)](https://twitch.com/mouredev) 144 | [![Discord](https://img.shields.io/discord/729672926432985098?style=social&label=Discord&logo=discord)](https://mouredev.com/discord) 145 | [![Twitter Follow](https://img.shields.io/twitter/follow/mouredev?style=social)](https://twitter.com/mouredev) 146 | ![GitHub Followers](https://img.shields.io/github/followers/mouredev?style=social) 147 | ![GitHub Followers](https://img.shields.io/github/stars/mouredev?style=social) 148 | 149 | Soy ingeniero de software desde 2010. Desde 2018 combino mi trabajo desarrollando Apps con la creación de contenido formativo sobre programación y tecnología en diferentes redes sociales como **[@mouredev](https://moure.dev)**. 150 | 151 | Si quieres unirte a nuestra comunidad de desarrollo, aprender programación, mejorar tus habilidades y ayudar a la continuidad del proyecto, puedes encontrarnos en: 152 | 153 | [![Twitch](https://img.shields.io/badge/Twitch-Programación_en_directo-9146FF?style=for-the-badge&logo=twitch&logoColor=white&labelColor=101010)](https://twitch.tv/mouredev) 154 | [![Discord](https://img.shields.io/badge/Discord-Servidor_de_la_comunidad-5865F2?style=for-the-badge&logo=discord&logoColor=white&labelColor=101010)](https://mouredev.com/discord) [![Pro](https://img.shields.io/badge/Cursos-mouredev.pro-FF5500?style=for-the-badge&logo=gnometerminal&logoColor=white&labelColor=101010)](https://moure.dev) 155 | [![Link](https://img.shields.io/badge/Links_de_interés-moure.dev-14a1f0?style=for-the-badge&logo=Linktree&logoColor=white&labelColor=101010)](https://moure.dev) [![Web](https://img.shields.io/badge/GitHub-MoureDev-087ec4?style=for-the-badge&logo=github&logoColor=white&labelColor=101010)](https://github.com/mouredev) 156 | --------------------------------------------------------------------------------