MySQL Tutorial
MySQL Tutorial
MySQL Tutorial
By Gez Lemon, published on 03 Sep 2003 Comments (5) PDF
Introduction
Released in January 1998, MySQL is an open source relational database management system (RDBMS). It's based around the Structured Query Language (SQL), and is
best for managing the content of the database as opposed to transactions, as MySQL does not support COMMIT or ROLLBACK. One of the biggest drawbacks of MySQL
is it's lack of support for referential integrity, no stored procedures, no triggers, and no sub-queries. MySQL is free, and may be downloaded from download section at
MySQL.
Getting Started
When you start using MySQL, you use a command prompt to enter the SQL statement. The statements can be quite lengthy, and a pain to modify. The simplest way of
using MySQL is to use files containing the SQL statements to perform. For example, if you want to create a table called, search, you could create a file called called,
createSearchTable.sql and load this file from the command prompt rather than type in a lengthy SQL statement to create the table.
The SOURCE command is used to load the file from the command prompt.
The sequence \. is a shorcut name for the SOURCE statement. The following does exactly the same thing as the above SOURCE statement.
mysql> \. createSearchTable.sql
Logging Output
The TEE statement may be used to log output from your SQL statements to a text file. The following command copies all output to the file log.txt so you can examine the
results of running your queries.
mysql> NOTEE
The CREATE statement is used to create a database in MySQL. The following statement creates a database called search.
To let MySQL know that you want to use that database, you use the USE statement. The following example uses the database, search.
Deleting a Database
Databases can be deleted using the DROP statement. The following example deletes the database, search.
Creating Tables
The CREATE statement is used to create a table in MySQL. The general syntax to create a table in MySQL is:
If NULL is specified, the field is allowed to be left empty. If NOT NULL is specified, the field must be given a value. In the absence of either a NULL or NOT NULL, NULL is
assumed.
CHAR(size fieldName CHAR(10) Stores up to 255 characters. If the content is smaller than the field size, the content will have trailing spaces appended.
VARCHAR fieldName VARCHAR Stores up to 255 characters, and a minimum of 4 characters. No trailing spaces are appended to the end of this datatype. MySQL keeps track
(size (100) of a delimiter to keep track of the end of the field.
TEXT fieldName TEXT Stores up to 65,535 characters. An Index can be created on the first 255 characters of a field with this data type.
fieldName Stores up to 16,777,215 characters. An Index can be created on the first 255 characters of a field with this data type.
MEDIUMTEXT
MEDIUMTEXT
Stores up to 4,294,967,295 characters. An Index can be created on the first 255 characters of a field with this data type.
LONGTEXT fieldName LONGTEXT
Note: The maximum size of a string in MySQL is currently 16 million bytes, so this data types is not useful at the moment.
fieldName ENUM Stores up to 65,535 enumerated types. The DEFAULT modifier may be used to specify the default value for this field.
ENUM
('Yes', 'No')
Stores a signed or unsigned integer number. Unsigned integers have a range of 0 to 4,294,967,295, and signed integers have a range of -
2,147,438,648 to 2,147,438,647. By default, the INT data type is signed. To create an unsigned integer, use the UNSIGNED attribute.
Stores a signed or unsigned byte. Unsigned bytes have a range of 0 to 255, and signed bytes have a range of -128 to 127. By default, the
TINYINT fieldName TINYINT TINYINT data type is signed.
fieldName Stores a signed or unsigned medium sized integer. Unsigned fields of this type have a range of 0 to 1,677,215, and signed fields of this type
MEDIUMINT have a range of -8,388,608 to 8,388,607. By default, the MEDIUMINT data type is signed.
MEDIUMINT
Stores a signed or unsigned big integer. Unsigned fields of this type have a range of 0 to 18,446,744,073,709,551,615, and signed fields of this
BIGINT fieldName BIGINT type have a range of -9,223,372,036,854,775,808 to 9,223,327,036,854,775,807. By default, the BIGINT data type is signed.
FLOAT fieldName FLOAT Used for single precision floating point numbers.
DOUBLE fieldName DOUBLE Used for double precision floating point numbers.
TIMESTAMP
fieldName DATETIME Stores dates and times in the format YYYY-MM-DD HH:MM:SS.
(size)
Automatically keeps track of the time the record was last ammended. The following table shows the formats depending on the size of
TIMESTAMP
Size Format
2 YY
4 YYMM
fieldName
DATETIME 6 YYMMDD
TIMESTAMP(14)
8 YYYYMMDD
10 YYYYMMDDHH
12 YYYYMMDDHHMM
14 YYYYMMDDHHMMSS
YEAR(size) fieldName YEAR(4) Stores the year as either a 2 digit number, or a 4 digit number, depending on the size provided.
Primary Keys
A primary key is a field in a table that uniquely identifies a record. The PRIMARY KEY attribute may be used when defining the field name to create a primary key, as in the
following example.
Alternatively, the PRIMARY KEY attribute may be used to specify the primary key after the defining the fields, as in the following example:
The second method is ideal should you want to create a compound primary key. A compound primary key is where more than one field is used to uniquely identify a
unique record. The field names are separated with commas. Consider a table used with a search engine for a site. The primary key could comprise the Directory name,
and the page name. The following example illustrates creating a table with a compound primary key.
createSearch.sql
CREATE TABLE search
(
Category VARCHAR(100) NOT NULL,
Page VARCHAR(20) NOT NULL,
Directory VARCHAR(255) NOT NULL,
LinkName VARCHAR(255) NOT NULL,
Keywords MEDIUMTEXT NOT NULL,
Desription VARCHAR(255) NOT NULL,
PRIMARY KEY(Page, Directory)
);
mysql> \. createSearch.sql
Default values may be provided for fields using the DEFAULT attribute. The following example uses a default value of index.html, should a Page name not be provided for
the search table.
createSearch.sql
Examining Tables
You can examine the structure of a table using the DESCRIBE statement. The following displays the structure of the search table.
The DESCRIBE statement may be shorted to DESC. The following achieves the same thing.
You may also use the SHOW FIELDS FROM statement to achieve the same thing.
You can list all tables in the database using the SHOW TABLES statement. The following example lists all tables in the current database.
Using Indexes
Creating an Index
Indexes allow you to specify an index for a table to speed up searching. Primary keys are automatically indexed, but you can add indexes to other fields to allow them to be
easily searchable. The database has to maintain the indexes, so it's not a good idea to make every field an index. The following example provides an index called
keyIndex for a field called keywords.
INDEX keyIndex(Kewords)
You can specify how many characters you wish to index in a field. The following example creates an index on the first 100 characters of the field, Keywords.
INDEX keyIndex(Keywords(100))
You can create an index on more than one table by specifying a comma separated list. The following example creates a compound index on the first 100 characters of the
Keywords field, and the Description field.
The indexes are from left to right. Therefore, in the example, indexes are only created for Descriptions where Keywords exist.
The UNIQUE specifier may be used to ensure that indexes are unique. The following example requires that the values assigned to the first 100 characters of the
Keywords field are unique.
The following example creates a table called search, with an Index on the first 100 characters of the Keywords field.
createSearch.sql
mysql> \. createSearch.sql
Altering Tables
The ALTER TABLE command allows you to alter tables, fields and indexes of a table.
Renaming a Table
The RENAME modifier allows you to rename a table. The following example renames the table search to site.
The ADD COLUMN modifier allows you to add a column to a table. The following example adds a field called modified to the search table.
The FIRST and AFTER modifiers may be used to position the field within the table. The following places the new field as the first field in the table.
The next example could be used to add the new field immediately after the field Keywords.
mysql> ALTER TABLE search ADD COLUMN modified TIMESTAMP AFTER Keywords;
The DROP COLUMN modifier may be used to drop a column from the table. The following example drops the field modified.
The DROP INDEX modifier may be used to drop an index from a table. The following example drops the index keyIndex from the search table.
Modifying columns
When you modify a column, you must specify the attributes for the column again. The following example renames the Description field to PageDescription in the search
table.
mysql> ALTER TABLE search CHANGE Description PageDescription VARCHAR(255) NOT NULL;
If you only want to change the attributes, use the same column name as in the following example:
mysql> ALTER TABLE search CHANGE Description Description VARCHAR(200) NOT NULL;
Deleting a Table
Tables are deleted from the database using the DROP statement. The following example drops the table search from the database.
Keyword Description
HAVING Used with GROUP BY to specify the criteria for the grouped records.
The simplest SELECT query is to retrieve all records from a single table. The following example lists all fields from the search table.
To select specific fields from a table, you provide a comma-separated list of field names. The following example selects the Page and Directory from the search table:
mysql> SELECT Page, Directory FROM search;
Limiting Records
The WHERE clause may be used to limit records. The following lists the comparison operators available with MySQL to limit the records returned with the WHERE clause.
Operator Description
= Equal to
When working with strings, the % character may be used as a wildcard. The following example retrieves all fields from the search table where the Keyword field contains
the text, "cookies".
The underscore character may be used as a placeholder. The following example selects all records from the search table, where the Page name beings with 'P', followed
by four characters (four underscores are used).
The BETWEEN clause may be used with numbers, dates and text. The following example retrieves all fields from Products, where the cost is between 1000 and 4000.
mysql> SELECT * FROM Products WHERE cost BETWEEN 1000 AND 4000;
The OR clause may be used to specify a range of values to check against. The following example lists all records where the Category is either ASP or PHP in the search
table.
If you have many values that you want to check against, you can use the IN clause as it makes the code a lot more readable. The following is the above statement using
the IN clause.
Similarly, you can use the NOT modifier with the IN clause to check for values that are not within the list. The following example returns all records where the Category is
not equal to ASP or PHP
Joining Tables
Sometimes the data you require may come from two or more tables. Supposing our search table contained a foreign key called AuthorID that related to a primary key of
the same name in an author table, we could retrieve records by linking the two fields. The following example lists the Surname and Forename from an author table, and
the Directory and Page from the search table written by that author.
You can add further clauses to the WHERE clause, using the AND operator. The following example extends the previous example to return only records where the Author
has the Surname, Lemon.
listLemons.sql
SELECT author.Surname, author.Forename, search.Directory, search.Page FROM search, author WHERE author.AuthorID = search.AuthorID
AND author.Surname = 'Lemon';
The file may then be used with MySQL as follows:
mysql> \. listLemons.sql
Aggregate Functions
The GROUP BY modifier may be used to perform aggregate functions, such as COUNT records. The following example lists the distinct Directories, along with a count of
how many records there are for that Directory in the search table.
mysql> SELECT Directory, COUNT(*) FROM search GROUP BY Directory;
The AS modifier may be used to provide meaningful column names for the result. In the above example, the column headings from running the query are, Directoy and
COUNT(*). The following example uses the column name Entries instead of COUNT(*).
If you want the column name to contain spaces, you must put the name in single quotes. The next example uses a column name of Number of Entries.
mysql> SELECT Directory, COUNT(*) AS 'Number of Entries' FROM search GROUP BY Directory;
SELECT AVG(cost) FROM Invoice GROUP BY Returns the average value in a group of records. The example returns the average order for each
AVG() customer.
ClientID;
SELECT COUNT(cost) FROM Invoice GROUP BY Returns the number of records in a group of records. The example returns the number of orders for each
COUNT() customer.
ClientID;
SELECT MAX(cost) FROM Invoice GROUP BY Returns the largest value in a group of records. The example returns the largest order by each customer.
MAX()
ClientID;
SELECT MIN(cost) FROM Invoice GROUP BY Returns the lowest value in a group of records. The example returns the smallest order by each customer.
MIN()
ClientID;
SELECT SUM(cost) FROM Invoice GROUP BY Returns the sum of a field. The example returns the total amount spent by each customer.
SUM()
ClientID;
mysql> SELECT AVG(cost) FROM Invoice GROUP BY ClientID HAVING AVG(cost) > 20000;
The ORDER BY clause may use the ASC or DESC modifiers to determine if the records should be in ascending or descending order. If neither are provided, the records are
shown in ascending order. The following example lists all Pages in the search table in descending order.
The following example would retrieve the next ten records from the search table.
Keyword Description
The following example inserts two records into the search table.
insert.sql
mysql> \. insert.sql
If a field in your table allows NULL values, you may omit the field from the INSERT statement.
The following characters have a special meaning to MySQL, and will need to be escaped by putting a backslash before them in order that they are interpreted correctly.
Characters Name
\ Blackslash
% Percent
_ Underscore
The following example shows how you would escape an underscore in the string, "last_modified".
'last\_modified'
You can escape single quotes by placing two single quotes together, as in the following example.
'Don''t care!'
Keyword Description
SET Specifies the field names to be updates. If the fields belong to more that one table, the table name should be specified before the field name. (eg. search.Page).
The following example updates all records in the search table to change the category from Jive, to Java.
update.sql
UPDATE search
SET Category = 'Java'
WHERE Category = 'Jive';
mysql> \. update.sql
Keyword Description
The following example deletes all records in the search table where the category is Junk.
delete.sql
mysql> \. delete.sql
Related tags
php, mysql, sql