This cheatsheet covers common MySQL table operations including creating, altering, and dropping tables.
- Create Table
- Alter Table
- Drop Table
- Table Information
- Indexes
- Temporary Tables
- Truncate Table
Create Table
-- Basic table creation
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
-- Create table with primary key
CREATE TABLE table_name (
id INT NOT NULL AUTO_INCREMENT,
column1 datatype,
column2 datatype,
PRIMARY KEY (id)
);
-- Create table with foreign key
CREATE TABLE orders (
order_id INT NOT NULL,
product_id INT,
customer_id INT,
PRIMARY KEY (order_id),
FOREIGN KEY (product_id) REFERENCES products(id),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
Alter Table
-- Add a new column
ALTER TABLE table_name
ADD column_name datatype;
-- Drop a column
ALTER TABLE table_name
DROP COLUMN column_name;
-- Modify column datatype
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;
-- Rename a column
ALTER TABLE table_name
CHANGE old_column_name new_column_name datatype;
-- Add primary key
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
-- Add foreign key
ALTER TABLE table_name
ADD FOREIGN KEY (column_name) REFERENCES other_table(other_column);
-- Drop foreign key
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
Drop Table
-- Drop a table
DROP TABLE table_name;
-- Drop table if it exists
DROP TABLE IF EXISTS table_name;
Table Information
-- Show all tables in the current database
SHOW TABLES;
-- Describe table structure
DESCRIBE table_name;
-- or
SHOW COLUMNS FROM table_name;
-- Show create table statement
SHOW CREATE TABLE table_name;
-- Show table status
SHOW TABLE STATUS LIKE 'table_name';
Indexes
-- Create an index
CREATE INDEX index_name
ON table_name (column1, column2);
-- Create a unique index
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2);
-- Drop an index
DROP INDEX index_name ON table_name;
-- Show indexes for a table
SHOW INDEX FROM table_name;
Temporary Tables
-- Create a temporary table
CREATE TEMPORARY TABLE temp_table (
column1 datatype,
column2 datatype
);
-- Temporary tables are automatically dropped at the end of the session
Truncate Table
-- Remove all rows from a table
TRUNCATE TABLE table_name;