Mysql Pocket Reference
Created By: Wiggins - Last Updated by: Wiggins - Last Updated on: 2002.05.23
This is not intended as an all encompassing SQL reference, this is intended as the basics, what you need to get started and to do nothing advanced.


Commands at shell prompt:

mysqlshow -h <host> <database> Displays list of databases on localhost or <host> when argument exists, when no arguments passed, or list of tables in <database> when argument exists
mysql -h <host> <database> Connects to MySQL server on localhost or <host> when argument exists, if 2nd argument exists then connects to <database>. May take a file as input with < syntax, for example ~> mysql database < list_of_mysql_commands.mysql.
mysqladmin Controls various server functions, such as database creation and deletion, pass --help for possible switches
mysqldump -h <host> <database> <table> Dumps all data including create table information and rows in <database> on server localhost or <host> when argument exists. If 2nd argument exists then dumps only data in <table>.

Query Language Syntax at MySQL client prompt:

connect <database>; Connects client instance to <database>
SHOW (DATABASES|TABLES); Displays a list of the databases on the currently connected server, or a list of tables in the currently connected database
DESCRIBE <table>; Displays information about <table> in the currently connected database, including field names, field types, other field specifics, and a count of the total number of rows
CREATE TABLE <new table name> (
	fieldname fieldtype (options),
	fieldname2 fieldtype2 (options2),
	...
);

example:
CREATE TABLE example_table (
  id int(10) DEFAULT '0' NOT NULL auto_increment,
  status tinyint(3),
  username varchar(20),
  email varchar(255),
  description text,
  datecreated datetime,
  lastupdated datetime,
  PRIMARY KEY (id)
);
			
Create table creates a new table in the currently connected database. new table name may only include alphanumeric characters and no white space ([A-Za-z0-9_]). For field specifics see field descriptors later in this file.
DROP TABLE <table>; Deletes all content and definition of the table <table> from the currently connected database.
ALTER TABLE <table> ADD <field> <fieldtype> <fieldoptions> (AFTER <field>);

ALTER TABLE <table> DROP <field>;

ALTER TABLE <table> CHANGE <oldfieldname> <newfieldname> <fieldtype> <fieldoptions>;

examples:
ALTER TABLE example_table ADD password varchar(8) AFTER username;

ALTER TABLE example_table DROP datecreated;

ALTER TABLE example_table CHANGE description personal_profile varchar(255);

Changes the configuration of <table> in one of three ways. ADD creates a new field in the form specified either at the field list end or after the field specified. DROP removes a field from the table and any data stored therein. CHANGE edits the specified field changing its definition to the newly entered one preserving data where possible. Data is preserved if the type does not change significantly (text <-> varchar, tinyint <->mediumint, etc.) or data is truncated where necessary (datetime -> date drops the time, etc.) or data is deleted where assumptions can't be made (depends on case and data)


INSERT INTO <table> (<fieldlist>) VALUES (<values>);

examples:
INSERT INTO example_table (id,status,username,datecreated) VALUES (NULL,1,'testuser',NOW());

INSERT INTO example_table VALUES (NULL,1,'testuser','testuser@mysql.com','This is a description.',NOW(),NULL);

Enters a new row into <table>. In the case of a <fieldlist> the values for the given fields and in the given order are entered. When no field list is specified all fields must have a supplied value (even if that value is NULL) and values will be inserted in the order they appear in the table's field list given by mysqlshow.

Special Cases: If a field is defined as auto_increment then "NULL" should be passed.
Formatting: Dates and times can be in a number of formats but the recommended format is: yyyy-mm-dd hh:mm:ss



DELETE FROM <table> ( WHERE <field> <operator> <value>);

examples:
DELETE FROM example_table; - Deletes all rows from example_table

DELETE FROM example_table WHERE id=1; - Deletes only the row with id 1

DELETE FROM example_table WHERE username LIKE 'u%'; - Deletes all rows where the username starts with "u"

Deletes rows from <table> where a row matches the entered query. If no query is specified all rows will be deleted. Queries can include the same sets of field/operator/value as selects and updates. See building a query under select later in this file.


UPDATE <table> SET <field1>=<value1>,<field2>=<value2>, ... ( WHERE <field> <operator> <value>)

examples:
UPDATE example_table SET username='newusername',lastupdated=NOW() WHERE id=1; - Changes the username for the user with id 1 to "newusername" and changes the 'lastupdated' field to the current date and time

Updates all rows in <table> setting each field equal to its corresponding value in the "SET list" whereever a row matches the query string. If no query string is provided then all rows are updated. Queries can include the same sets of field/operator/value as selects and deletes. See building a query under select later in this file.


SELECT <field1>(,<field2> AS <newfieldname>) FROM <table1>(,<table2>) ( WHERE <field> <operator> <value> ) ( ORDER BY <fieldlist> [DESC]) (LIMIT <startrow>,<numrows>)

examples:
SELECT * FROM example_table; - selects all data in each row

SELECT id,status,username FROM example_table; - selects 3 fields from every row

SELECT id,status,username FROM example_table WHERE username='user'; - selects 3 fields from every row that corresponds to the username "user"

SELECT id,status,username FROM example_table WHERE username='user' ORDER BY datecreated,lastupdated; - same as above ordered by when the user's were created, and when the datecreated is the same orders by when their record was last updated

SELECT COUNT(*) FROM example_table; - returns the number of rows in the table

SELECT id,status,username FROM example_table WHERE (username='user' AND password='pass'); - selects fields from every row where the username is "user" and the password is "pass" (both must be true)

SELECT id,status,username FROM example_table WHERE username LIKE 'u%'; - selects fields from every row where the username starts with "u" and is followed by 0 or more characters

SELECT id,status,username FROM example_table WHERE username LIKE 'u%' LIMIT 0,5; - same as above except will only return 5 rows starting at the 0th (first row found) row

SELECT id,status,username FROM example_table WHERE username LIKE '%u' ORDER BY username,lastupdated DESC LIMIT 1,6; - similar to above but the username's are first ordered alphabetically and the 1st-6th (second through seventh) rows are returned

Multi-table

SELECT table1.id AS userid, table2.email AS useremail, table2.lastupdated AS last_login FROM table1,table2 WHERE ((table1.id > 10 AND table2.email LIKE '%@%') AND (table1.id = table2.id)) ORDER BY email DESC LIMIT 0,20; - can you guess?

Retrieves specified fields in the given number of rows (default is all matching) starting at the given row (default is 0) from <table> where records match,returned in the specified order (defaults to database structure, not necessarily input order).

The field list may contain a number of specialized variants including, *, COUNT(*). The "AS" keyword allows a field name to be aliased to another, for example: SELECT verylongfieldname AS vlfn makes the values in "verylongfieldname" appear as values in a field named "vlfn" instead.

Fields may be selected from multiple tables in the same query, but may require a field to be related in each table. When selecting from multiple tables non-unique fields will conflict if the table name is not included, for example if you are selecting from table1 and table2 and both have an "id" field then the field(s) you are selecting and the field(s) you are querying will need to be stated completely, such as table1.id and table2.id .




Field Types (most widely used)
All fields allow for a "NOT NULL" option, and a DEFAULT value

TINYINT unsigned,auto_increment Signed: -128 to 127
Unsigned: 0 to 255
SMALLINT unsigned,auto_increment Signed: -32,768 to 32,767
Unsigned 0 to 65,535
MEDIUMINT unsigned,auto_increment Signed: -8,388,608 to 8,388,607
Unsigned 0 to 16,777,215
INT unsigned,auto_increment Signed: -2,147,683,648 to 2,147,683,647
Unsigned: 0 to 429,496,967,295
VARCHAR(#) 4-255 Stores up to 255 characters (fields adjust to max. value size) (use BLOB for case sensitivity)
TEXT Stores (almost) unlimited amount of data but reduces efficiency of querying, etc. (use BLOB for case sensitivity)
DATE (yyyy-mm-dd) 1000-01-01 to 9999-12-31
TIME (hhh-mm-ss) -838:59:59 to 838:59:59
DATETIME (yyyy-mm-dd hh-mm-ss) 1000-01-01 00:00:00 to 9999-12-31 23:59:59
YEAR (yyyy) 1901 to 2155
TIMESTAMP(#) # determines display 2,4,6,8,10,12,14 pass nothing for this field, it is automatically updated to the current system time
1970-01-01 to 2037

Operators (most widely used)
All expressions can be grouped with parentheses
Example: ( (user='username') AND (pass='password') )

Logical Operators
AND or && evaluates to 1 if both sides are true
OR or || evaluates to 1 if either side is true
NOT or ! evaluates to 1 if following side is false
Comparison Operators
= a = b true if operands are equal
!=, <> a != b, a <> b true if operands are not equal
< , <= a < b, a <= b true if less than, or if less than or equal to
> , >= a > b, a >= b true if greater than, or if greater than or equal to
LIKE a LIKE b Pattern Match: true if a matches b
NOT LIKE a NOT LIKE b Pattern Match: true if a does not match b
IS NULL a IS NULL true if a is NULL
IS NOT NULL a IS NOT NULL true if a is not NULL

Notes:
  • When specifying a field value that is not an integer or NULL the value must be included in <single quotes>, Example: username='brianm'
  • When using a field value that is included in single quotes, all single quotes therein must be "escaped", the escape sequence is one of: \' or '' Example: field value = can't, would look like contraction='can\'t' -or- contraction='can''t'
  • When creating a table with an auto_increment field, the field must be of an integer type (any size) and must be established as a PRIMARY KEY (see example under CREATE)