Skip to content

Instantly share code, notes, and snippets.

@eduardogpg
Last active December 19, 2025 00:23
Show Gist options
  • Select an option

  • Save eduardogpg/0a166294242ee6f50dda2b5381f1a173 to your computer and use it in GitHub Desktop.

Select an option

Save eduardogpg/0a166294242ee6f50dda2b5381f1a173 to your computer and use it in GitHub Desktop.
llaves - SQL - 18 dec
-- Users
DROP TABLE users;
-- ID strings -- x ()
-- ADMIN - 1
-- SOFT delete
CREATE TABLE users(
id INT AUTO_INCREMENT PRIMARY KEY, -- Indexados -- COUNT(id) -- COUNT(username)
username VARCHAR(50) NOT NULL,
first_name VARCHAR(100),
last_name VARCHAR(100)
);
INSERT INTO users (username, first_name, last_name) VALUES ('cody1', 'Cody', 'Cody'); -- 1
INSERT INTO users (username, first_name, last_name) VALUES ('cody2', 'Cody', 'Cody');
INSERT INTO users (username, first_name, last_name) VALUES ('cody3', 'Cody', 'Cody');
INSERT INTO users (username, first_name, last_name) VALUES ('cody4', 'Cody', 'Cody');
INSERT INTO users (username, first_name, last_name) VALUES ('cody5', 'Cody', 'Cody'); -- 5
-- 1: M
-- BELONGS to
DROP TABLE tasks;
CREATE TABLE tasks(
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
title VARCHAR(50),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE --En pertenencia
);
INSERT INTO tasks(user_id, title) VALUES (6, 'Terminar el curso');
INSERT INTO tasks(user_id, title) VALUES (6, 'Practicar');
INSERT INTO tasks(user_id, title) VALUES (6, 'Apagar la instancia de AMAZON!!!! $');
-- TRUNCATE users;
-- Courses
DROP TABLE courses;
CREATE TABLE courses(
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL
);
INSERT INTO courses(title) VALUES ('Base de datos'); -- 1
INSERT INTO courses(title) VALUES ('Python');
INSERT INTO courses(title) VALUES ('Ruby');
INSERT INTO courses(title) VALUES ('Rust'); -- 4
-- Enrollments
-- M:M
-- Un usuario puede poseer múltiples cursos
-- Un curso puede ser tomado por múltiples usuarios
DROP TABLE enrollments;
-- M:M
CREATE TABLE enrollments(
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT, -- FK
course_id INT, -- FK
-- attempts: INT
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
-- ON DELETE SET NULL
FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);
INSERT INTO enrollments (user_id, course_id) VALUES(2, 1);
-- @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1
-- SELECT
-- JOINs
-- INNER JOIN
-- LEFT JOIN
-- RIGHT JOIN
-- CROSS JOIN
-- SELECT
-- *
-- FROM users FULL JOIN tasks
SELECT
*
FROM users INNER JOIN tasks ON users.id = tasks.user_id;
WHERE users.username = 'cody6';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment