MySQL Cheat Sheet

Basic Commands

CommandDescription
mysql -u username -pStart the MySQL command-line interface
CREATE DATABASE dbnameCreate a new database
DROP DATABASE dbnameDelete a database
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'Create a new user
GRANT SELECT ON *.* TO ‘usernameGrant select on all databases and tables.
GRANT ALL ON dbname.* TO ‘username‘;Grant all access to all tables in database
GRANT ALL ON dbname.* TO ‘username‘@’localhost’;Grant all access to all tables in database but only when connected from localhost. User %, or IP in place of localhost where % is wildcard like *, and by IP to restrict to a single interface.
FLUSH PRIVILEGESRefresh the privileges
DROP USER 'username'@'localhost'Delete a user
mysqldump -u username -p dbname > filename.sqlBackup a database
mysql -u username -p dbname < filename.sqlRestore a database

Creating Tables

CommandDescription
CREATE TABLE tablename (column1 datatype1, column2 datatype2, ...)Create a new table
ALTER TABLE tablename ADD COLUMN column datatypeAdd a new column to a table
ALTER TABLE tablename DROP COLUMN columnRemove a column from a table
DROP TABLE tablenameDelete a table

Data Manipulation

CommandDescription
INSERT INTO tablename (column1, column2, ...) VALUES (value1, value2, ...)Insert a new row into a table
UPDATE tablename SET column = value WHERE conditionUpdate one or more rows in a table
DELETE FROM tablename WHERE conditionDelete one or more rows from a table
SELECT column1, column2, ... FROM tablename WHERE conditionQuery data from a table

Querying Data

CommandDescription
SELECT * FROM tablenameRetrieve all rows and columns from a table
SELECT column1, column2, ... FROM tablenameRetrieve specific columns from a table
SELECT column1, column2, ... FROM tablename WHERE conditionRetrieve specific rows based on a condition
SELECT column1, COUNT(*) FROM tablename GROUP BY column1Group rows based on a column and count the number of rows in each group
SELECT column1, AVG(column2) FROM tablename GROUP BY column1Group rows based on a column and calculate the average value of another column in each group

Joins

CommandDescription
SELECT * FROM table1 JOIN table2 ON table1.column = table2.columnJoin two tables based on a common column
SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.columnLeft join two tables based on a common column
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.columnRight join two tables based on a common column
SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.columnFull outer join two tables based on a common column

Leave a Reply

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.