Skip to the content.

MySQL Cheatsheet

Table of Content

Commands

FLUSH PRIVILEGES Many guides suggest running the FLUSH PRIVILEGES command immediately after a CREATE USER or GRANT statement in order to reload the grant tables to ensure that the new privileges are put into effect:

Logical Operators

Case

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN 'The quantity is greater than 30'
    WHEN Quantity = 30 THEN 'The quantity is 30'
    ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

Functions

Constraints

Unique

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    UNIQUE (ID)
    -- OR with name
    CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
-- Add UNIQUE
ALTER TABLE Persons
ADD UNIQUE (ID);
-- OR
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

-- Drop UNIQUE
ALTER TABLE Persons
DROP INDEX UC_Person;

Primary Key

-- Drop a primary key
ALTER TABLE Persons
DROP PRIMARY KEY;

Foreign Key

CREATE TABLE Orders (
    OrderID int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
    -- OR
    CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
    REFERENCES Persons(PersonID)
);

Check

CREATE TABLE Persons (
    Age int,
    CHECK (Age>=18)
);

Default

-- Create table
City varchar(255) DEFAULT 'something'
OrderDate date DEFAULT CURRENT_DATE()
-- Alter add
ALTER TABLE Persons
ALTER City SET DEFAULT 'something';
-- Alter drop
ALTER TABLE Persons
ALTER City DROP DEFAULT;

Index

-- Duplicate values are allowed
CREATE INDEX index_name
ON table_name (column1, column2, ...);
-- Unique values
CREATE UNIQUE INDEX index_name

Auto Increment

-- Create table
Personid int NOT NULL AUTO_INCREMENT,
-- sequence start with another value
ALTER TABLE Persons AUTO_INCREMENT=100;

Data Types

Date

Handwrite Notes

-- Add column to a specific position
ALTER TABLE locations
ADD region_id INT 
AFTER state_province;
-- Add to first
ALTER TABLE locations
ADD region_id INT FIRST;