MySQL Cheat Sheet

Log into MySQL:

(anonymous login)

$ mysql -h host_name

or (prompt for password)

$ mysql -h host_name -u uername -p

or (password part of command line)

$ mysql -h host_name -u username -ppassword

Selecting a database:

mysql> USE database_name;

Listing databases:

mysql> SHOW DATABASES;

Listing tables in a db:

mysql> SHOW TABLES;

Describing the format of a table:

mysql> DESCRIBE table_name;

Creating a database:

mysql> CREATE DATABASE database_name;

Creating a table:

mysql> CREATE TABLE table_name (field1_name TYPE(SIZE), field2_name TYPE(SIZE));

Ex:

mysql> CREATE TABLE pet (name VARCHAR(20), sex CHAR(1), birth DATE);

Load tab-delimited data into a table:

mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table_name;

(Use \n for NULL)

Inserting one row at a time:

mysql> INSERT INTO table_name VALUES ('MyName', 'MyOwner', '2002-08-31');

(Use NULL for NULL)

Retrieving information (general):

mysql> SELECT from_columns FROM table WHERE conditions;

All values:

mysql> SELECT * FROM table;

Some values:

mysql> SELECT * FROM table WHERE name = "value";

Multiple critera:

mysql> SELECT * FROM TABLE WHERE col1 = "value1" AND col2 = "value2";

Fixing just one record:

mysql> UPDATE table SET value = "newvalue" WHERE record_name = "value";

Selecting specific columns:

mysql> SELECT columnname1,columnname2 FROM table;

Counting rows:

mysql> SELECT COUNT(*) FROM table;

Currently selected database:

mysql> SELECT DATABASE();

Maximum value:

mysql> SELECT MAX(col_name) AS label FROM table;

Batch mode (feeding in a script):

mysql> source batch_file;