Previous Page Next Page

17.3. Getting Started with MySQL

17.3.1. Why MySQL?

MySQL is an open source,[3] full-featured relational database management system and has been ported to most platforms, including Linux, Windows, OS/X, HP-UX, AIX, etc. MySQL is portable (runs on Linux, Windows, OS/X, HP-UX, etc.), fast, reliable, scalable, and easy to use.

[3] MySQL is free use for those who are 100% GPL. See http://www.mysql.com/company/legal/licensing/opensource-license.html for details.

It claims to be installed in more than 10 million computers all over the world, including Antarctica! There are two versions, one where you buy a commercial license and one that is free, free meaning you can use MySQL in any application as long as you don't copy, modify, or distribute the MySQL software. MySQL supports a number of APIs (application programming interfaces), including Perl, PHP, TCL, Python, C/C++, Java, etc.

When working with MySQL, a number of like-name terms are used. Table 17.2 is provided to help clarify the use of these terms.

Table 17.2. The Terms in MySQL, etc.
mySQLThe actual software for the database management system
mysqldThe MySQL daemon, or server process
mysql monitorThe monitor where MySQL commands are issued (command-line interpreter)
mysqlThe name of the database MySQL uses to manage access privileges
mysqladminA MySQL utility program for administering the database


17.3.2. Installing MySQL

Here we assume you have installed a database server and it is running. Downloading and installing MySQL is usually a straightforward process. You can get MySQL from the mysql.com Web site or use integrated applications, such as XAMPP or WAMP.

XAMPP (for Windows, Linux, Mac OS, and Solaris) is a free, easy-to-install Apache distribution containing MySQL, PHP, and Perl. All you have to do is download, extract, and start it up. For details, go to http://www.apachefriends.org/en/xampp.html.

For complete installation instructions, go to this Web page.

Figure 17.13. The MySQL installation documentation.


17.3.3. Connecting to MySQL

The MySQL database system uses the client/server model described in Section 17.2.1. You are the client connecting to the database from the command line, a graphical user interface, or from a program. Before connecting to the database from a Perl program, we will first use the the MySQL command-line client.

The MySQL command-line client comes with the MySQL installation and is universally available. It is a mysql.exe program located in the bin folder of your MySQL installation.

To run this command-line application, you must start the command-line prompt. On Windows, go to the Start menu, choose the Run... option, and then type cmd in the "run" window. On Mac OS X, go to the Applications folder in your Finder and then navigate to Utilities. You will find the Terminal application there. You should navigate to the location where you installed MySQL and find the bin folder. With UNIX, type commands at the shell prompt in a terminal window.

The MySQL client executable is normally located in the bin folder.

To connect to a database using this client, you will enter information similar to the following line:

         mysql --user=root --password=my_password --host=localhost

Figure 17.14. The MySQL client.


Regardless of the type of client you choose, you may be required to specify the user name and the host machine to which you are connecting. Most configurations expect you to have a password, although if just working by yourself, it is not required. You have the option to specify the default database as well.

Once you are successfully connected, you will get the mysql> prompt instead of your standard DOS/UNIX prompt. This means you are now sending commands to the MySQL database server and not to your local computer's operating system.

Editing Keys at the MySQL Console

MySQL supports input-line editing. The up-arrow and down-arrow keys allow you to move up and down through previous input lines, and the left-arrow and right-arrow keys to move back and forth within a line. The backspace and Delete keys are used to erase characters from the line and type in new characters at the cursor position. To submit an edited line, press Enter. For UNIX users, MySQL also supports tab completion, allowing you to enter part of a keyword or identifier and complete it using the Tab key.

Setting a Password

When you download MySQL, on some installations, you may be asked to enter a password for user "root." Even if you are not forced to create a password, it is a good idea to set one to protect the security of your database. To set a password, go to the MySQL console and type the following MySQL command. Replace 'MyNewPassword' with your password.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');

After setting the password, you can stop the MySQL server and then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use. You should be able to connect using the new password.

Setting the Password at the MySQL Prompt

Example 17.1.

1 $ mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using
password: NO)
$
$ mysql -u root -p
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 91 to server version: 5.0.21-community-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

17.3.4. Graphical User Tools

The MySQL Query Browser

The MySQL Query Browser is a graphical user interface (GUI) client available from mysql.com used to connect to the MySQL database server. Once you download it and follow the simple installation wizard, you can start the application from the Start menu under Windows.

The MySQL Query Browser then displays a connection dialog box. You must specify the MySQL server where you want to connect, the credentials needed for authorization on that server, which machine that server runs on (and which port it listens to), and the default database (called the "Schema") you will be using. There are also a number of additional options you can specify if necessary.

You must choose a default database in order to issue queries. Although it is possible to choose a default database after connecting to the server, setting the default from the connection dialog can save time on subsequent connections.

The information to enter is very similar to the command-line client: user name, password, and the server host where the database server is running. You can optionally enter the database name and port number (3306 is the default for MySQL) and save the connection information as a bookmark under the Stored Connection section.

By using the familiar tree-like navigation structure on the right-hand side of the application window, you can also navigate the various databases in the MySQL Query Browser.

Figure 17.15. The MySQL Query Browser.


Figure 17.16. The MySQL Query Browser.


The phpMyAdmin Tool

The phpMyAdmin tool is written in PHP to handle the administration of MySQL over the Web. It is used to create and drop databases, manipulate tables and fields, execute SQL statements, manage keys on fields, manage privileges, and export data into various formats. See http://www.phpmyadmin.net/home_page/index.php.

Figure 17.17. The phpMyAdmin tool.


The MySQL Privilege System

With a driver's license, "authentication" is verifying that it is really you who owns the license by checking your picture and expiration date, and "authorization" is validating what type of vehicle you are authorized to drive, such as a car, a large truck, or a school bus.

Similarly, the primary purpose of the MySQL privilege system is to authenticate that the user and password are valid to connect to the specified host, as demonstrated in the previous examples in both the command line and graphical client. The second purpose of the privilege system is to specify what the user, once connected to the database, is authorized to do. For example, some users may only be authorized to select and view the data from a specific table. When MySQL is installed, the MySQL database is created with tables called grant tables that define the initial user accounts and privileges. The first account is that of a user named "root," also called the superuser. The superuser can do anything, meaning anyone logging on to the database as root is granted all privileges. Initially, the root account has no password, making it easy for anyone to log on as the superuser. The other types of accounts created are anonymous-user accounts, also without a password. For both the root and anonymous accounts, Windows gets one each and UNIX gets two. Either way, to avoid security problems, the first thing you should do, once the MySQL server starts, is to set a password on the root account and the anonymous accounts.

For administration purposes, you should have root access rights to your server. The mysqladmin utility is useful for creating passwords and performing other MySQL administrative tasks. In the next example it is used to set the password for the user "root".

Example 17.2.

1  $ mysqladmin -u root -h localhost password quigley1

2  $ mysql -uroot -hlocalhost -pquigley1
   Welcome to the MySQL monitor.  Commands end with ; or \g.
   Your MySQL connection id is 29 to server version: 5.0.21
community-nt

   Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

Explanation

  1. The mysqladmin program is used to set the password for user root on the localhost. The password is "quigley1".

  2. The user root logs into the database server. The -u switch is followed by the user or login name (no spaces between -u and the user name). This user is logging in as "root". Similarly, the -p switch is followed by the actual password; in this case, "quigley1". If a password is not provided, you will prompted to enter one.

17.3.5. Finding the Databases

The database server keeps a list of available databases, which can be displayed as a table by issuing the show command at the mysql prompt, as shown in the following example. Typically when you install MySQL, it comes with two databases: test and mysql. test is an empty database used for practicing and testing various features. You normally don't need to have any special permissions to be able work in the test database. The mysql database is a special database where the MySQL server stores various access permissions. For now, you should not worry about this database unless you need to administer privileges. See the "GRANT" command in the MySQL manual.

Example 17.3.

1 mysql -uroot -pquigley1
  Welcome to the MySQL monitor.  Commands end with ; or \g.
  Your MySQL connection id is 5 to server version: 4.1.11-nt

  Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
2  mysql> show databases;
  mysql> show databases;
  +--------------------+
  | Database           |
  +--------------------+
  | information_schema |
  | mysql              |
  | phpmyadmin         |
  | test               |
  +--------------------+
  rows in set (0.00 sec)
 mysql>

Explanation

2The show database command lists all the databases on this server. Typically, when you install MySQL, you will be given the mysql database and the test database. The test database is just for testing purposes and is empty. The mysql database contains all the MySQL server privilege information.


Creating and Dropping a Database

Creating a database is simple. Designing it is another story and depends on your requirements and the model you will use to organize your data. With the smallest database, you will have to create a table. The next section will discuss how to create and drop both databases and tables. Assuming you have been granted permission to create a database, you can do it at the mysql command line or with the mysqladmin tool as follows:

Example 17.4.

1     mysql> create database my_sample_db;
      Query OK, 1 row affected (0.00 sec)

2     mysql> use my_sample_db;
      Database changed

3     mysql> show tables;
      Empty set (0.00 sec)

4     mysql> create table test(
      -> field1 INTEGER,
      -> field2 VARCHAR(50)
      -> );
      Query OK, 0 rows affected (0.36 sec)
5     mysql> show tables;
      +------------------------+
      | Tables_in_my_sample_db |
      +------------------------+
      | test                   |
      +------------------------+
      1 row in set (0.00 sec)

6     mysql> drop table test;
      Query OK, 0 rows affected (0.11 sec)

7     mysql> drop database my_sample_db;
      Query OK, 0 rows affected (0.01 sec)

					  

Explanation

  1. This command creates a database called my_sample_db.

  2. Just because the database has been created doesn't mean you are in it. To enter the new database, the use command is executed.

  3. The show command lists the tables in the database. This database is empty.

  4. A table called test is created for the my_sample_db database. When a table is created, two columns, field1 and field2, are defined. Each field is assigned the type of data that will be stored there; field1 will store whole numbers, and field2 will store a string of up to 50 characters.

  5. The show command lists all the tables in the database.

  6. The drop table command destroys a table and its contents.

  7. The drop database command destroys a database and its contents.

17.3.6. Getting Started with Basic Commands

Example 17.5.

(At the MySQL Client Prompt)
1 mysql> select database();
+------------+
| database() |
+------------+
| northwind  |
+------------+
1 row in set (0.00 sec)
2 mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2007-05-12 16:09:57 |
+---------------------+
1 row in set (0.00 sec)

The examples in this next section illustrate how to issue SQL commands from the MySQL client. These examples do not attempt to cover all the possible SQL statements supported by MySQL but are here to illustrate the basic syntax for creating and dropping databases and tables and how to insert, delete, edit, alter, and select data from the database tables. For a complete discription of all that you can do with MySQL, visit http://dev.mysql.com/doc/.

Figure 17.18. MySQL Documentation page.


Creating a Database with MySQL

Now we are ready to create a database. This database is called sample_db. The CREATE DATABASE command creates the database, and the SHOW DATABASES statement demonstrates that it is now listed with the other databases. (You can also use the mysqladmin command to create and drop databases.)

Example 17.6.

1  mysql> CREATE DATABASE sample_db;
Query OK, 1 row affected (0.03 sec)

2 mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| northwind          |
| phpmyadmin         |
| sample_db          |
| test               |
+--------------------+
6 rows in set (0.00 sec)

Explanation

  1. The CREATE DATABASE statement allows you to create a database. Creating a database does not put you in that database. The USE statement will let you start working in the database, as shown in the next example.

  2. The SHOW DATABASES statement lists all the MySQL databases currently available. The sample_db database was just created.

Selecting a Database with MySQL

After creating the database, we need to open it so we can use it. This is done with the USE statement. We now have a database to work in.

Example 17.7.

mysql> USE sample_db;
Database changed

Creating a Table in the Database

Once the database is created, it is time to create some tables. In a real situation, the relational database will be designed with rules that put logic in the structure of the tables, a process called "normalization" and a topic beyond the scope of this book. In our sample database, we will create one table and put some data in it, just to show you how it is done. The data types define the structure of each field in the table. The CREATE TABLE statement defines each field, its name, and its data type.

Data Types

First, we will have to decide what kind of data will be stored in the table: text, numbers, dates, photos, money, etc., and what to name the fields (columns) under which the data is stored. MySQL has specific data types to describe all the types of data that can be stored in the database. Most of the MySQL data types are listed in Table 17.3.

Table 17.3. MySQL Data Types
Data TypeDescription
Numbers 
TINYINTVery small numbers; suitable for ages. Can store numbers between 0 and 255 if UNSIGNED clause is applied; else the range is between –128 and 127.
SMALLINTSuitable for numbers between 0 and 65535 (UNSIGNED) or –32768 and 32767.
MEDIUM INT0 to 16777215 with UNSIGNED clause or -8388608 and 8388607.
INTUNSIGNED integers fall between 0 and 4294967295 or –2147683648 and 2147683647.
BIGINTHuge numbers (–9223372036854775808 to 9223372036854775807).
FLOATFloating point numbers (single precision).
DOUBLEFloating point numbers (double precision).
DECIMALFloating point numbers represented as strings.
Text 
CHAR(x)Where x can range from 1 to 255. Holds a fixed-length string (can contain letters, numbers, and special characters). The fixed size is specified in parentheses.
VARCHAR(x)x ranges from 1 to 255. Holds a variable-length string (can contain letters, numbers, and special characters). The maximum size is specified in parentheses.
TINYTEXTSmall text, case insensitive.
TEXTSlightly longer text, case insensitive.
MEDIUMTEXTMedium-size text, case insensitive.
LONGTEXTReally long text, case insensitive.
TINYBLOBBlob means a Binary Large OBject. You should use blobs for case-sensitive searches.
Binary 
BLOBSlightly larger blob, case sensitive.
MEDIUMBLOBMedium-sized blobs, case sensitive.
LONGBLOBReally huge blobs, case sensitive.
ENUMEnumeration data type has fixed values, and the column can take only one value from the given set. The values are placed in parentheses following ENUM declaration. An example is a marital-status column—m_status ENUM("Y", "N").
Dates 
DATE: YYYY-MM-DDFour-digit year followed by two-digit month and date; e.g., 20071030
TIME: hh:mm:ssHours:Minutes:Seconds
DATETIMEYYYY-MM-DD hh:mm:ss (Date and time separated by a space character)
TIMESTAMPYYYYMMDDhhmmss
YEARYYYY (four-digit year); e.g., 2007


Example 17.8.

1  mysql> CREATE TABLE teams(
    -> name varchar(100) not null,
    -> wins int unsigned,
    -> losses int unsigned);
Query OK, 0 rows affected (0.09 sec)

2 mysql> SHOW TABLES;
+---------------------+
| Tables_in_sample_db |
+---------------------+
| teams               |
+---------------------+
1 row in set (0.00 sec);

3 mysql> DESCRIBE teams;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| name   | varchar(100)     | NO   |     |         |       |
| wins   | int(10) unsigned | YES  |     | NULL    |       |
| losses | int(10) unsigned | YES  |     | NULL    |       |
+--------+------------------+------+-----+---------+-------+
| teams               |
+---------------------+
1 row in set (0.00 sec)

					  

Explanation

  1. The CREATE TABLE statement creates a table in the database. This table is named teams. It consists of three fields: name, wins, losses. The name field will consist of a varying string of up to 100 characters; the wins and losses fields will hold unsigned integers.

  2. The SHOW command lists the table in a database.

  3. The DESCRIBE command describes the structure of the table; i.e., the names of the fields and the type of data that can be stored in each field. Note that the name field cannot be "Null", and the default value for the wins and losses is NULL if a value isn't supplied; e.g., if a team hasn't played any games, the wins and losses will be assigned NULL.

Adding Another Table with a Primary Key

In the next example, we will create another table and add a primary key. A primary key is used to uniquely identify the records in the database. A user's login name, UID, account number, or license plate are examples of unique IDs. A primary key is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY.

Example 17.9.

1  mysql> CREATE TABLE coaches(
    -> id INT NOT NULL AUTO_INCREMENT,
    -> name VARCHAR(75),
    -> team VARCHAR(100),
    -> title VARCHAR(50),
    -> start_date date,
    -> PRIMARY KEY(id));
   Query OK, 0 rows affected (0.38 sec)

2  mysql> DESCRIBE coaches;
   +------------+--------------+------+-----+---------+---------------
   | Field      | Type         | Null | Key | Default | Extra
   +------------+--------------+------+-----+---------+---------------
   | id         | int(11)      | NO   | PRI | NULL    |auto_increment
   | name       | varchar(75)  | YES  |     | NULL    |
   | team       | varchar(100) | YES  |     | NULL    |
   | title      | varchar(50)  | YES  |     | NULL    |
   | start_date | date         | YES  |     | NULL    |
   +------------+--------------+------+-----+---------+---------------
   5 rows in set (0.00 sec)
3  mysql> SHOW TABLES;
  +---------------------+
  | Tables_in_sample_db |
  +---------------------+
  | coaches             |
  | teams               |
  +---------------------+
  2 rows in set (0.00 sec)

					  

Explanation

  1. The coach table is created with the id field being assigned a primary key. This is the field that will used to uniquely identify a specific coach.

  2. The structure of the new table shows that the id field has a primary key that will be automatically incremented by one by MySQL each time a new coach is added.

  3. Now our database has two tables, one called teams and one called coaches.

Inserting Data into Tables

The SQL INSERT statement adds new records to a table. When you insert data, make sure you provide a value for each field name in the order the data is stored; otherwise, MySQL will send an error message. In the following example, data can be inserted with the SET clause where fields are assigned values, or the values can be specified with the VALUES list or by simply listing the values for each field in order. See the MySQL documentation for a complete list of ways to add new records to a table.

Example 17.10.

1  mysql> INSERT INTO teams
    -> set name='Fremont Tigers',
    -> wins=24,
    -> losses=26;
   Query OK, 1 row affected (0.00 sec)

2  mysql> INSERT INTO teams
    -> set name='Chico Hardhats',
    -> wins=19,
    -> losses=25;
   Query OK, 1 row affected (0.00 sec)

3  mysql> INSERT INTO teams values
    -> ('Bath Warships',32,3);
   Query OK, 1 row affected (0.00 sec)
4  mysql> INSERT INTO teams values
    -> ('Bangor Rams', 22, 24);
   Query OK, 1 row affected (0.00 sec)

5  mysql> SELECT name FROM teams;
   +----------------+
   | name           |
   +----------------+
   | Fremont Tigers |
   | Chico Hardhats |
   | Bath Warships  |
   | Bangor Rams    |
   +----------------+
   4 rows in set (0.00 sec)

6  mysql> INSERT INTO coaches values
   -> (" ",'John Doe','Chico Hardhats','Head Coach', 20021210);
   Query OK, 1 row affected, 1 warning (0.05 sec)

7  mysql>  INSERT INTO coaches values
      -> (" ", 'Jack Mattsone','Chico Hardhats','Offensive Coach' ,
'20041005');
    Query OK, 1 row affected, 1 warning (0.00 sec)

8  mysql> INSERT INTO coaches(name,team, title,start_date)
       -> values( 'Bud Wilkins', 'Fremont Tigers', 'Head Coach',
'19990906');
    Query OK, 1 row affected (0.03 sec)

9  mysql>  INSERT INTO coaches(name, team, title,start_date)
       ->values( 'Joe Hayes', 'Fremont Tigers', 'Defensive Coach',
    '19980616');
    Query OK, 1 row affected (0.02 sec

					  

Explanation

1The fields and values are assigned using the SET clause within the INSERT statement. For any field not named in the SET, MySQL assigns its default value.
2Again the fields and values are inserted using the SET clause.
3In this example, the INSERT statement contains a VALUE list where a value for each field is assigned in the order it was specified when the table was created. To see the order, if you are not sure, use the DESCRIBE statement as shown in the previous example.
4The VALUES list is repeated in this example for a new record. Note that the date is inserted in the format yyyy-mm-dd
5The SELECT statement displays the names of all the teams that have been inserted into the table.
6,7,8,9More records are inserted with the VALUES list.


Selecting Data from Tables—The SELECT Command

One of the most commonly used SQL commands is SELECT, mandatory when performing a query. The SELECT command is used to retrieve data from a table based on some criteria. It specfies a comma-separated list of fields to be retrieved, and the FROM clause specifies the table(s) to be accessed. The results are stored in a result table known as the result set, just a little table itself. The * symbol can be used to represent all of the fields.

Selecting by Columns

In the following examples, data is retrieved for specific columns, each column (field) separated by a comma.

Example 17.11.

1  mysql> SELECT name FROM teams;
+----------------+
| name           |
+----------------+
| Fremont Tigers |
| Chico Hardhats |
| Bath Warships  |
| Bangor Rams    |
+----------------+
4 rows in set (0.00 sec)

2  mysql> SELECT name, wins FROM teams;
  +----------------+------+
  | name           | wins |
  +----------------+------+
  | Bangor Rams    |   22 |
  | Bath Warships  |   32 |
  | Fremont Tigers |   24 |
  | Chico Hardhats |   19 |
  +----------------+------+
  4 rows in set (0.00 sec)

3  mysql> SELECT id, name, title FROM coaches;
  +----+---------------+-----------------+
  | id | name          | title           |
  +----+---------------+-----------------+
  | 1  | John Doe      | Head Coach      |
  | 2  | Jack Mattsone | Offensive Coach |
  | 3  | Bud Wilkins   | Head Coach      |
  | 4  | Joe Hayes     | Defensive Coach |
  +----+---------------+-----------------+
  4 rows in set (0.00 sec)

					  

Explanation

  1. The SELECT statement retrieves all values in the name field from the table called teams.

  2. The SELECT statement retrieves all values in the name field and the wins field from the table called teams. The list of field names are separated with a comma.

  3. The SELECT statement retrieves all values in the id field, the name field, and the title field from the coaches table.

Select All Columns

The * is a wildcard that is used to represent all of the columns in a table.

Example 17.12.

1  mysql> SELECT * FROM teams;
+----------------+------+--------+
| name           | wins | losses |
+----------------+------+--------+
| Fremont Tigers |   24 |     26 |
| Chico Hardhats |   19 |     25 |
| Bath Warships  |   32 |      3 |
| Bangor Rams    |   22 |     24 |
+----------------+------+--------+

2  mysql> SELECT * FROM coaches;
+----+---------------+----------------+-----------------+-----------+
| id | name          | team           | title           | start_date|
+----+---------------+----------------+-----------------+-----------+
|  1 | John Doe      | Chico Hardhats | Head Coach      | 2002-12-10|
|  2 | Jack Mattsone | Chico Hardhats | Offensive Coach | 2004-10-05|
|  3 | Bud Wilkins   | Fremont Tigers | Head Coach      | 1999-09-06|
|  4 | Joe Hayes     | Fremont Tigers | Defensive Coach | 1998-06-16|
+----+---------------+----------------+-----------------+-----------+
4 rows in set (0.00 sec)

Explanation

  1. The SELECT statement retrieves all fields and values from the table called teams.

  2. The SELECT statement retrieves all fields and values from the table called coaches.

The WHERE Clause

The WHERE clause is optional and specifies which data values or rows will be selected based on some condition, called selection criterion. SQL provides a set of operators to qualify the condition being set.

Table 17.4. SQL Operators
OperatorDescriptionExample
=Equal towhere country = 'Sweden'
<>, !=Not equal to[a]where country <> 'Sweden'
>Greater thanwhere salary > 50000
<Less thanwhere salary < 50000
>=Greater than or equal 
<=Less than or equal 
IS [NOT] NULLIs NULL (no value) or Not NULLwhere birth = NULL
BETWEENBetween an inclusive rangewhere last_name BETWEEN 'Doe' AND 'Hayes'
LIKESearch for value like a patternwhere last_name LIKE 'D%'
NOT LIKESearch for a value not like a patternwhere country NOT LIKE 'Sw%'
!, NOTlogical NOT for negationwhere age ! 10;
||, ORlogical ORwhere order_number > 10 || part_number = 80
&&, ANDlogical ANDwhere age > 12 && age < 21
XORExclusive ORwhere status XOR


[a] In some versions of SQL, the <> operator may be written as !=.

Example 17.13.

1  mysql> SELECT name, wins FROM teams WHERE wins > 25;
  +-------------------+------+
  | name              | wins |
  +-------------------+------+
  | Bath Destroyers   |   34 |
  | Portland Penguins |   28 |
  +-------------------+------+

2  mysql> SELECT name FROM teams WHERE losses < wins;
  +---------------+
  | name          |
  +---------------+
  | Bath Warships |
  +---------------+
  1 row in set (0.03 sec)
3  mysql> SELECT name, title FROM coaches WHERE team = 'Chico
Hardhats';
  +---------------+-----------------+
  | name          | title           |
  +---------------+-----------------+
  | John Doe      | Head Coach      |
  | Jack Mattsone | Offensive Coach |
  +---------------+-----------------+
  2 rows in set (0.00 sec)

4 mysql> SELECT name FROM coaches WHERE name LIKE 'J%';
  +---------------+
  | name          |
  +---------------+
  | John Doe      |
  | Jack Mattsone |
  | Joe Hayes     |
  +---------------+
  3 rows in set (0.00 sec)

5  mysql> SELECT name FROM teams WHERE wins > 10 && losses < 10;
  +---------------+
  | name          |
  +---------------+
  | Bath Warships |
  +---------------+
  1 row in set (0.00 sec)

6  mysql> SELECT name FROM coaches WHERE id BETWEEN 1 AND 3;
  +---------------+
  | name          |
  +---------------+
  | John Doe      |
  | Jack Mattsone |
  | Bud Wilkins   |
  +---------------+
  3 rows in set (0.00 sec)

					  

Explanation

  1. The SELECT statement retrieves the name of teams from the table called teams where the number of wins was greater than 25.

  2. The SELECT statement retrieves the name of teams from the table called teams where the number of losses was less than the number of wins.

  3. The SELECT statement retrieves the names of coaches and their titles from the table called coaches if their team is equal to the string 'Chico Hardhats'. The string must be quoted in either single or double quotes, and the match must be exact.

  4. The SELECT statement retrieves the names of coaches from the table called coaches where the coachs name contains a string starting with a 'J'. The % sign is a wildcard representing any characters following the 'J'.

  5. The SELECT statement retrieves the name of the team where the number of wins is greater than 10 and the number of losses less than 10. The && is called the logical AND. Both statements must be true or nothing will be selected.

  6. The SELECT statement retrieves the names of coaches from the table called coaches where the coachs ID is between 1 and 3. The BETWEEN clause creates a range criteria from which to select.

Sorting Tables

You can display the output of a query in a particular order by using the ORDER BY clause. Rows can be sorted either in ascending (the default) or descending (DESC) order where the values being sorted are either strings or numbers. You can limit the output of any query with the LIMIT clause.

Example 17.14.

1  mysql> SELECT * FROM teams ORDER BY name;
  +----------------+------+--------+
  | name           | wins | losses |
  +----------------+------+--------+
  | Bangor Rams    |   22 |     24 |
  | Bath Warships  |   32 |      3 |
  | Chico Hardhats |   19 |     25 |
  | Fremont Tigers |   24 |     26 |
  +----------------+------+--------+
  4 rows in set (0.00 sec)

2  mysql> SELECT * FROM teams ORDER BY name DESC;
  +----------------+------+--------+
  | name           | wins | losses |
  +----------------+------+--------+
  | Fremont Tigers |   24 |     26 |
  | Chico Hardhats |   19 |     25 |
  | Bath Warships  |   32 |      3 |
  | Bangor Rams    |   22 |     24 |
  +----------------+------+--------+
  4 rows in set (0.00 sec)

3  mysql> SELECT name, wins FROM teams ORDER BY WINS LIMIT 2;
  +----------------+------+
  | name           | wins |
  +----------------+------+
  | Chico Hardhats |   19 |
  | Bangor Rams    |   22 |
  +----------------+------+
  2 rows in set (0.00 sec)

					  

Explanation

  1. The SELECT statement retrieves all fields from the table called teams and sorts the result set by names in ascending order.

  2. The SELECT statement retrieves all fields from the table called teams and sorts the result set by names in descending order.

  3. The SELECT statement retrieves the names and wins of teams and sorts the number of wins in ascending order, limiting the result set to the top two winners.

Joining Tables

When a database is designed properly, the tables relate to one another based on some criteria; for example, in our database, every team has a name and every coach has a name and a team name. A join allows two or more tables to be combined and return a result set based on the relationships they share. There are different types of join statements (inner joins, cross joins, left, joins, etc.), but they all follow the basic syntax of a SELECT statement with the addition of a JOIN clause.

Example 17.15.

1  mysql> SELECT teams.name, coaches.name, teams.wins
 FROM teams, coaches WHERE
 teams.name = coaches.team && coaches.id = 4;
+----------------+-----------+------+
| name           | name      | wins |
+----------------+-----------+------+
| Fremont Tigers | Joe Hayes |   24 |
+----------------+-----------+------+
1 row in set (0.00 sec)

2  mysql> SELECT teams.name, coaches.name, teams.wins FROM teams,
    -> coaches  WHERE teams.name = coaches.team &&
-> coaches.title = "Head Coach";
+----------------+-------------+------+
| name           | name        | wins |
+----------------+-------------+------+
| Chico Hardhats | John Doe    |   21 |
| Fremont Tigers | Bud Wilkins |   24 |
+----------------+-------------+------+
2 rows in set (0.00 sec)


3  mysql> SELECT t.name, c.name, t.wins FROM teams t, coaches c
-> WHERE t.name = c.team && c.title LIKE "Head%";
+----------------+-------------+------+
| name           | name        | wins |
+----------------+-------------+------+
| Chico Hardhats | John Doe    |   21 |
| Fremont Tigers | Bud Wilkins |   24 |
+----------------+-------------+------+
2 rows in set (0.00 sec)

					  

Explanation

  1. The SELECT statement will retrieve the team's name, the coach's name, and the number of wins for the team where the team and coach name are the same and the coach's ID is 4. The fields are prepended with the name of the table and a dot to identify the field and table. The join (inner join) means that all unmatched records are discarded. Only the rows that matched the criteria in the WHERE clause are displayed in the result set.

  2. The SELECT statement will retrieve the team's name, the coach's name, and the number of wins for the team where the team and coach name are the same and the coach's title is "Head Coach." Like the last example, the join (inner join) means only the rows that matched the criteria in the WHERE clause are displayed in the result set.

  3. The SELECT statement will retrieve the team name, the coach name, and the team wins from both the teams and coaches tables where the team name and the coach name are the same and the coach's title starts with "Head." The letters 't' and 'c' are called aliases for the respective tables, teams and coaches. Aliases save a lot of typing.

Deleting Rows

The DELETE command allows you to remove rows from a table. The only real difference between DELETE and SELECT is that the DELETE removes records based on some criteria, whereas the SELECT retrieves those records.

Example 17.16.

1  mysql> SELECT name FROM teams;
+----------------+
| name           |
+----------------+
| Fremont Tigers |
| Chico Hardhats |
| Bath Warships  |
| Bangor Rams    |
+----------------+
4 rows in set (0.00 sec)

2  mysql> DELETE FROM teams WHERE name = "Bath Warships";
Query OK, 1 row affected (0.20 sec)

3  mysql> SELECT name FROM teams;
+----------------+
| name           |
+----------------+
| Fremont Tigers
| Chico Hardhats |
| Bangor Rams    |
+----------------+
4 rows in set (0.00 sec)

Explanation

  1. The SELECT statement retrieves all values in the name field from the table called teams.

  2. The DELETE statement removes all rows in the name field if the name of the team is "Bath Warships."

  3. This SELECT statement retrieves all values in the name fields, showing us that the "Bath Warships" team was deleted in the previous DELETE statement.

Updating Data in a Table

The UPDATE command is used to edit a table; i.e., to modify or change the values in a table. This statement uses the SET clause to change the existing value to something else, as shown in Example 17.17.

Example 17.17.

1 mysql> SELECT * FROM teams;
+----------------+------+--------+
| name           | wins | losses |
+----------------+------+--------+
| Fremont Tigers |   24 |     26 |
| Chico Hardhats |   19 |     25 |
| Bath Warships  |   32 |      3 |
| Bangor Rams    |   22 |     24 |
+----------------+------+--------+
4 rows in set (0.00 sec)


1  mysql> UPDATE teams SET wins=wins + 2 WHERE name="Chico Hardhats";
   Query OK, 1 row affected (0.02 sec)
   Rows matched: 1  Changed: 1  Warnings: 0

2  mysql> UPDATE teams SET name="Bath Destroyers"
    ->  where name="Bath Warships";
      Query OK, 1 row affected (0.13 sec)
      Rows matched: 1  Changed: 1  Warnings: 0

3   mysql> SELECT * FROM teams;
+------------------+------+--------+
| name              | wins | losses |
+-------------------+------+--------+
| Fremont Tigers    |   24 |     26 |
| Chico Hardhats    |   21 |     25 |
| Bath Destroyers   |   32 |      3 |
| Bangor Rams       |   22 |     24 |
+-------------------+------+--------+
4 rows in set (0.00 sec)

					  

Explanation

  1. The SELECT statement retrieves all rows from the table called teams. We will compare this result set with the one on line 3 after the the table is updated.

  2. The UPDATE statement edits the name field. It causes the "Bath Warships" team to be renamed "Bath Destroyers".

  3. This SELECT statement retrieves all values in the name field, showing us that the "Bath Warships" team's name was changed by the UPDATE statement.

Altering a Table

The ALTER TABLE command allows you to alter the structure of an existing table by adding and dropping columns. The ALTER statement has many possible clauses, such as CHANGE, MODIFY, RENAME, DROP, etc. Don't confuse ALTER with UPDATE. Altering a table changes the structure of how the table was described after it was created. You can use it to add primary keys, indexes, change the definition of a column or where it is positioned in the table, etc. Some of these alterations are demonstrated in the following examples.

Add a Column
Example 17.18.

1  mysql> ALTER TABLE teams ADD captain varchar(100);
Query OK, 11 rows affected (0.64 sec)
Records: 11 Duplicates: 0 Warnings:

2  mysql> select * from teams;
+------------------------+------+--------+---------+
| name                   | wins | losses | captain |
+------------------------+------+--------+---------+
| Fremont Tigers         |   24 |     26 | NULL    |
| Bath Destroyers        |   34 |      3 | NULL    |
| Chico Hardhats         |   21 |     25 | NULL    |
| Bangor Rams            |   23 |      5 | NULL    |
4 rows in set (0.01 sec)

Explanation

  1. The ALTER statement adds a new field called captain to the teams table. The values in the new field will consist of up to 100 characters.

Drop a Column
Example 17.19.

mysql> ALTER TABLE teams DROP captain;
Query OK, 11 rows affected (0.34 sec)
Records: 11  Duplicates: 0  Warnings: 0

Add a Primary Key

In Example 17.20, the teams table is altered by making the name field a primary key. This means that all new teams must have unique names.

Example 17.20.

1  mysql> ALTER TABLE teams MODIFY name VARCHAR(100) NOT NULL,
    -->  ADD PRIMARY KEY(name);
    Query OK, 10 rows affected (0.06 sec)
    Records: 10  Duplicates: 0  Warnings: 0

2  mysql> DESCRIBE teams;
  +--------+------------------+------+-----+---------+-------+
  | Field  | Type             | Null | Key | Default | Extra |
  +--------+------------------+------+-----+---------+-------+
  | name   | varchar(100)     | NO   | PRI | NULL    |       |
  | wins   | int(10) unsigned | YES  |     | NULL    |       |
  | losses | int(10) unsigned | YES  |     | NULL    |       |
  +--------+------------------+------+-----+---------+-------+
  3 rows in set (0.05 sec)

Dropping a Table

To drop a table is relatively simple. Just use the DROP command and the name of the table.

Example 17.21.

mysql> DROP TABLE teams;
Query OK, 5 rows affected (0.11 sec)

Dropping a Database

To drop a database, use the DROP DATABASE command.

Example 17.22.

mysql> DROP DATABASE sample_db;
Query OK, 1 row affected (0.45 sec)

Previous Page Next Page