Here’s a comprehensive cheat sheet for MySQL:
- Connect to a MySQL server:
mysql -h hostname -u username -p password
- Create a database:
CREATE DATABASE database_name;
- Use a database:
USE database_name;
- Create a table:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
...
);
- Insert data into a table:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
- Select data from a table:
SELECT * FROM table_name;
- Select specific columns from a table:
SELECT column1, column2 FROM table_name;
- Select data with a condition:
SELECT * FROM table_name WHERE column_name = value;
- Update data in a table:
UPDATE table_name SET column_name = new_value WHERE column_name = old_value;
- Delete data from a table:
DELETE FROM table_name WHERE column_name = value;
- Create an index:
CREATE INDEX index_name ON table_name (column_name);
- Create a view:
CREATE VIEW view_name AS SELECT column1, column2 FROM table_name WHERE condition;
- Drop a table:
DROP TABLE table_name;
- Drop a database:
DROP DATABASE database_name;
- Show all databases:
SHOW DATABASES;
- Show all tables in a database:
SHOW TABLES;
- Show the structure of a table:
DESCRIBE table_name;
- Export data to a file:
SELECT * INTO OUTFILE '/path/to/file.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' FROM table_name;
- Import data from a file:
LOAD DATA INFILE '/path/to/file.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
- Set a password for a user:
SET PASSWORD FOR 'user'@'hostname' = PASSWORD('newpassword');
- Grant privileges to a user:
GRANT ALL PRIVILEGES ON database_name.* TO 'user'@'hostname';
- Revoke privileges from a user:
REVOKE ALL PRIVILEGES ON database_name.* FROM 'user'@'hostname';
This cheat sheet includes some of the most commonly used commands in MySQL. By using these commands, you can create, manage, and manipulate databases and tables, as well as import and export data.