Skip to content

Instantly share code, notes, and snippets.

@gbarreiro
Last active September 1, 2020 06:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbarreiro/5d99a7f420f6361643cc9ed53270b76a to your computer and use it in GitHub Desktop.
Save gbarreiro/5d99a7f420f6361643cc9ed53270b76a to your computer and use it in GitHub Desktop.
MySQL cheatsheet: create a table
CREATE TABLE Teachers (name VARCHAR(30), age INT);
-- Primary key:
CREATE TABLE Teachers (id INT PRIMARY KEY, name VARCHAR(30), age INT); # primary key: main index, can't be repeated
CREATE TABLE Students (id INT, name VARCHAR(30), age INT, PRIMARY KEY (code, name, age)); # primary key is compound
CREATE TABLE Subjects (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, name VARCHAR(30)); # primary key is automatically generated, starting in 1 and following 2,3...
-- Restrictions:
CREATE TABLE Teachers (id INT PRIMARY KEY NOT NULL, name VARCHAR(30) NOT NULL, age INT NOT NULL); # NOT NULL: the column value can't be empty
CREATE TABLE Teachers (id INT PRIMARY KEY, name VARCHAR(30), age INT, CHECK (age>18 and age<70)); # CHECK: the column value must comply some conditions
CREATE TABLE Students (id INT, name VARCHAR(30), age INT, passport VARCHAR (20), UNIQUE(passport)); # UNIQUE: there can't be more than one row with the same value in that column
-- Foreign keys:
CREATE TABLE Studies (student INT NOT NULL, subject INT NOT NULL, FOREIGN KEY (student) REFERENCES Students(id), FOREIGN KEY (subject) REFERENCES Subjects(id)); # foreign keys: relationships between relations (tables)
-- Default values:
CREATE TABLE Students (id INT, name VARCHAR(30), age INT, country VARCHAR(20) DEFAULT "Spain"); # if the "country" attribute is not specified, it's stored with default value "Spain"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment