By Alan Beaulieu
Book Price: $34.95 USD
£24.95 GBP
PDF Price: $27.99
Cover | Table of Contents
http://www.mysql.com) currently claims over 6 million installations, their server is available for free, and I have found it extremely simple to download and install their server. For these reasons, I have decided that all examples for this book will be run against a MySQL (Version 4.1.11) database, and that the mysql command-line tool will be used to format query results. Even if you are already using another server and never plan to use MySQL, I urge you to install the latest MySQL server, load the sample schema and data, and experiment with the data and examples in this book.This is not a book about MySQL's SQL implementation.
select statement. Additionally, you will see many examples that use the bank schema (introduced in the next chapter), which will be used for all examples in the book. It is my hope that your growing familiarity with a single database will allow you to get to the crux of an example without your having to stop and examine the tables being used each time.http://en.wikipedia.org/wiki/Database_management_system
http://www.mcjones.org/System_R/
http://dev.mysql.com. Unless you are planning to use the server for more than just a training tool, you should download the Essentials Package, which includes only the commonly used tools, instead of the Complete Package.http://dev.mysql.com/doc/mysql/en/Installing.html.http://dev.mysql.com. Unless you are planning to use the server for more than just a training tool, you should download the Essentials Package, which includes only the commonly used tools, instead of the Complete Package.http://dev.mysql.com/doc/mysql/en/Installing.html.mysql -u root -p. You will be asked for the root password, and then the
mysql -u lrngsql -p bank
mysql> prompt will appear, via which you will be able to issue SQL statements and view the results. For example, if you want to know the current date and time, you could issue the following query:
mysql> SELECT now();
+---------------------+
| now() |
+---------------------+
| 2005-05-06 16:48:46 |
+---------------------+
1 row in set (0.01 sec)
now()
function is a built-in MySQL function that returns the current date and time. As you can see, the mysql command-line tool formats the results of your queries within a rectangle bounded by +, -, and | characters
. After the results have been exhausted (in this case, there is only a single row of results), the mysql command-line tool shows how many rows were returned and how long the SQL statement took to execute.
CHAR(20) /* fixed-length */
VARCHAR(20) /* variable-length */
tinytext, text, mediumtext, longtext), which are covered later in this section. In general, you should use the char type when all strings to be stored in the column are of the same length, such as state abbreviations, and the varchar type when strings to be stored in the column are of varying lengths. Both char and varchar are used in a similar fashion in all of the major database servers.varchar. Oracle users should use the varchar2 type when defining variable-length character columns.|
Column
|
Type
|
Allowable values
|
|---|---|---|
Name
|
Varchar(40)
| |
Gender
|
Char(1)
|
M, F
|
person and favorite_food tables in place, you can now begin to explore the four SQL data statements: insert, update, delete, and select.person or favorite_food tables, the first of the four SQL data statements to be explored will be the insert statement. There are three main components to an insert statement:not null). In some cases, those columns that are not included in the initial insert statement will be given a value later via an update statement. In other cases, a column may never receive a value for a particular row of data (such as a customer order that is cancelled before being shipped, thus rendering the ship_date column inapplicable).person table, it would be useful to discuss how values are generated for numeric primary keys. Other than picking a number out of thin air, you have a couple of options:person and favorite_food tables, however, there are lots of ways that you can run afoul when inserting or modifying data. This section shows you some of the common mistakes that you might come across and how the MySQL server will respond.person_id column and create another row in the person table with a person_id of 1:
mysql> INSERT INTO person
-> (person_id, fname, lname, gender, birth_date)
-> VALUES (1, 'Charles','Fulton', 'M', '1968-01-15');
ERROR 1062 (23000): Duplicate entry '1' for key 1
person_id column.favorite_food table includes the creation of a foreign-key constraint on the person_id column. This constraint ensures that all values of person_id entered into the favorite_food table already exist in the person table. Here's what would happen if you tried to create a row that violates this constraint:
mysql> INSERT INTO favorite_food (person_id, food)
-> VALUES (999, 'lasagna');
ERROR 1216 (23000): Cannot add or update a child row:
a foreign key constraint fails
favorite_food table is considered the child, and the person table is considered the parent, since the favorite_food table is dependent on the person table for its data. If you plan to enter data into both tables, you will need to create a row in Employee, Branch, Account, Customer, Product, Transaction, and Loan. The entire schema and example data should have been created when you followed the 13 steps at the beginning of the chapter for loading the MySQL server and generating the sample data. To see a diagram of the tables and their columns and relationships, see Appendix A.|
Table name
|
Definition
|
|---|---|
Account
|
A particular product opened for a particular customer
|
Business
|
A corporate customer (subtype of the Customer table)
|
Customer
|
A person or corporation known to the bank
|
Department
|
A group of bank employees implementing a particular banking function
|
Employee
|
A person working for the bank
|
Individual
|
A noncorporate customer (subtype of the Customer table)
|
select statements) sprinkled throughout the first two chapters. Now it's time to take a closer look at the different parts of the select statement and how they interact.select statement, it might be interesting to look at how queries are executed by the MySQL server (or, for that matter, any database server). If you are using the mysql command-line tool (which I assume you are), then you have already logged in to the MySQL server by providing your username and password (and possibly a hostname if the MySQL server is running on a different computer). Once the server has verified that your username and password are correct, a database connection is generated for you to use. This connection is held by the application that requested it (which, in this case, is the mysql tool) until either the application releases the connection (i.e., as a result of your typing quit) or the server closes the connection (i.e., when the server is shut down). Each connection to the MySQL server is assigned an identifier, which is shown to you when you first log in:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 4.1.11-nt
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
2. This information might be useful to your database administrator if something goes awry, such as a malformed query that runs for hours, so you might want to jot it down.select statement, it might be interesting to look at how queries are executed by the MySQL server (or, for that matter, any database server). If you are using the mysql command-line tool (which I assume you are), then you have already logged in to the MySQL server by providing your username and password (and possibly a hostname if the MySQL server is running on a different computer). Once the server has verified that your username and password are correct, a database connection is generated for you to use. This connection is held by the application that requested it (which, in this case, is the mysql tool) until either the application releases the connection (i.e., as a result of your typing quit) or the server closes the connection (i.e., when the server is shut down). Each connection to the MySQL server is assigned an identifier, which is shown to you when you first log in:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 4.1.11-nt
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
2. This information might be useful to your database administrator if something goes awry, such as a malformed query that runs for hours, so you might want to jot it down.select statement. While only one of them is mandatory when using MySQL (the select clause), you will usually include at least two or three of the six available clauses. Table 3-1 shows the different clauses and their purposes.|
Clause name
|
Purpose
|
|---|---|
Select
|
Determines which columns to include in the query's result set
|
From
|
Identifies the tables from which to draw data and how the tables should be joined
|
Where
|
Restricts the number of rows in the final result set
|
Group by
|
Used to group rows together by common column values
|
Having
|
Restricts the number of rows in the final result set using grouped data
|
Order by
|
Sorts the rows of the final result set by one or more columns
|
select clause is the first clause of a select statement, it is one of the last clauses to be evaluated by the database server. The reason for this is that before you can determine what to include in the final result set, you need to know all of the possible columns that could be included in the final result set. In order to fully understand the role of the select clause, therefore, you will need to understand a bit about the from clause. Here's a query to get started:
mysql> SELECT *
-> FROM department;
+---------+----------------+
| dept_id | name |
+---------+----------------+
| 1 | Operations |
| 2 | Loans |
| 3 | Administration |
+---------+----------------+
3 rows in set (0.04 sec)
from clause lists a single table (department), and the select clause indicates that all columns (designated by "*") in the department table should be included in the result set. This query could be described in English as follows:department table.
mysql> SELECT dept_id, name
-> FROM department;
+---------+----------------+
| dept_id | name |
+---------+----------------+
| 1 | Operations |
| 2 | Loans |
| 3 | Administration |
+---------+----------------+
3 rows in set (0.01 sec)
department table (dept_id and name) are named in the select clause. You can choose to include only a subset of the columns in the department table as well:
mysql> SELECT name
-> FROM department;
+----------------+
| name |
+----------------+
| Operations |
| Loans |
| Administration |
+----------------+
3 rows in set (0.00 sec)from clauses contain a single table. Although most SQL books will define the from clause as simply a list of one or more tables, I would like to broaden the definition as follows:Thefromclause defines the tables used by a query, along with the means of linking the tables together.
table, most people think of a set of related rows stored in a database. While this does describe one type of table, I would like to use the word in a more general way by removing any notion of how the data might be stored and concentrating on just the set of related rows. There are three different types of tables that meet this relaxed definition:create table statement)create view statement)from clause. By now, you should be comfortable with including a permanent table in a from clause, so I will briefly describe the other types of tables that can be referenced in a from clause.select statement; within the from clause, however, a subquery serves the role of generating a temporary table that is visible from all other query clauses and can interact with other tables named in the from clause. Here's a simple example:employee, department, or account tables (except for the demonstration of distinct earlier in the chapter). Most of the time, however, you will not wish to retrieve every row from a table but will want a way to filter out those rows that are not of interest. This is a job for the where clause.where clause is the mechanism for filtering out unwanted rows from your result set.employee table, but only for those employees who are employed as head tellers. The following query employs a where clause to retrieve only the four head tellers:
mysql> SELECT emp_id, fname, lname, start_date, title
-> FROM employee
-> WHERE title = 'Head Teller';
+--------+---------+---------+------------+-------------+
| emp_id | fname | lname | start_date | title |
+--------+---------+---------+------------+-------------+
| 6 | Helen | Fleming | 2004-03-17 | Head Teller |
| 10 | Paula | Roberts | 2002-07-27 | Head Teller |
| 13 | John | Blake | 2000-05-11 | Head Teller |
| 16 | Theresa | Markham | 2001-03-15 | Head Teller |
+--------+---------+---------+------------+-------------+
4 rows in set (0.00 sec)
where clause. This where clause contains a single filter condition, but you can include as many conditions as required; individual conditions are separated using operators such as and, or, and not (see Chapter 4 for a complete discussion of the where clause and filter conditions). Here's an extension of the previous query that includes a second condition stating that only those employees with a start date later than January 1, 2002, should be included:
mysql> SELECT emp_id, fname, lname, start_date, title
-> FROM employee
-> WHERE title = 'Head Teller'
-> AND start_date > '2002-01-01';group by clause, which is used to group data by column values. For example, rather than looking at a list of employees and the departments to which they are assigned, you might want to look at a list of departments along with the number of employees assigned to each department. When using the group by clause, you may also use the having clause, which allows you to filter group data in the same way the where clause lets you filter raw data.select clauses. Therefore, I ask that you wait until Chapter 8 for a full description of how and when to use group by and having.order by clause:Theorder byclause is the mechanism for sorting your result set using either raw column data or expressions based on column data.
account table:
mysql> SELECT open_emp_id, product_cd
-> FROM account;
+-------------+------------+
| open_emp_id | product_cd |
+-------------+------------+
| 10 | CHK |
| 10 | SAV |
| 10 | CD |
| 10 | CHK |
| 10 | SAV |
| 13 | CHK |
| 13 | MM |
| 1 | CHK |
| 1 | SAV |
| 1 | MM |
| 16 | CHK |
| 1 | CHK |
| 1 | CD |
| 10 | CD |
| 16 | CHK |
| 16 | SAV |
| 1 | CHK |
| 1 | MM |
| 1 | CD |
| 16 | CHK |
| 16 | BUS |
| 10 | BUS |
| 16 | CHK |
| 13 | SBL |
+-------------+------------+
24 rows in set (0.00 sec)
open_emp_id column; to do so, simply add this column to the order by clause:
mysql> SELECT open_emp_id, product_cd
-> FROM account
-> ORDER BY open_emp_id;
+-------------+------------+
| open_emp_id | product_cd |
+-------------+------------+
| 1 | CHK |
| 1 | SAV |
| 1 | MM |
| 1 | CHK |
| 1 | CD |
| 1 | CHK |
| 1 | MM |
| 1 | CD |
| 10 | CHK |
| 10 | SAV |
| 10 | CD |
| 10 | CHK |
| 10 | SAV |
| 10 | CD |
| 10 | BUS |
| 13 | CHK |
| 13 | MM |
| 13 | SBL |
| 16 | CHK |
| 16 | CHK |
| 16 | SAV |
| 16 | CHK |
| 16 | BUS |
| 16 | CHK |
+-------------+------------+
24 rows in set (0.00 sec)select statement and its various clauses. Please see Appendix C for solutions.'ACTIVE' and whose available balance is greater than $2,500.account table that returns the IDs of the employees who opened the accounts (use the account.open_emp_id column). Include a single row for each distinct employee.<#>) for this multi-data-set query to achieve the results shown below:
mysql> SELECT p.product_cd, a.cust_id, a.avail_balance
-> FROM product p INNER JOIN account <1>
-> ON p.product_cd = <2>
-> WHERE p.<3> = 'ACCOUNT';
+------------+---------+---------------+
| product_cd | cust_id | avail_balance |
+------------+---------+---------------+
| CD | 1 | 3000.00 |
| CD | 6 | 10000.00 |
| CD | 7 | 5000.00 |
| CD | 9 | 1500.00 |
| CHK | 1 | 1057.75 |
| CHK | 2 | 2258.02 |
| CHK | 3 | 1057.75 |
| CHK | 4 | 534.12 |
| CHK | 5 | 2237.97 |
| CHK | 6 | 122.37 |
| CHK | 8 | 3487.19 |
| CHK | 9 | 125.67 |
| CHK | 10 | 23575.12 |
| CHK | 12 | 38552.05 |
| MM | 3 | 2212.50 |
| MM | 4 | 5487.09 |
| MM | 9 | 9345.55 |
| SAV | 1 | 500.00 |
| SAV | 2 | 200.00 |
| SAV | 4 | 767.77 |
| SAV | 8 | 387.99 |
+------------+---------+---------------+
21 rows in set (0.02 sec)where clause, since you don't need to exclude any rows from consideration. Most of the time, however, you will want to narrow your focus to a subset of a table's rows. Therefore, all of the SQL data statements (except the insert statement) include an optional where clause to house all filter conditions used to restrict the number of rows acted on by the SQL statement. Additionally, the select statement includes a having clause in which filter conditions pertaining to grouped data may be included. This chapter will explore the various types of filter conditions that can be employed in the where clauses of select, update, and delete statements.where clause may contain one or more conditions, separated by the operators and and or. If there are multiple conditions separated only by the and operator, then all of the conditions must evaluate to true for the row to be included in the result set. Consider the following where clause:
WHERE title = 'Teller' AND start_date < '2003-01-01'
where clause, if they are separated by the and operator then they must all evaluate to true for the row to be included in the result set.where clause are separated by the or operator, however, then only one of the conditions must evaluate to true for the row to be included in the result set. Consider the following two conditions: