Repository navigation
Week 3
This week we will expand upon the basic skills we have learned over the past two weeks. There is little new material here, rather more complex examples on how to use the basic skills we have already learned.
- More Complex Queries using Multiple Conditions and Subqueries
- Updating and Deleting Data
- SQL Keys
- Joins using more than 2 tables
We need a new table to work on some more complex queries, so let's create one and learn a few new MySQL data types along the way.
CREATE TABLE foods(
id INT(11) AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
country_of_origin VARCHAR(255),
primary_meal ENUM('breakfast', 'lunch', 'dinner'),
short_description VARCHAR(255),
average_price DECIMAL(8,2) DEFAULT 0.00,
calories INTEGER(11) DEFAULT 0,
discovery_date DATE,
PRIMARY KEY(id)
);
We have 3 new data types in this table. The primary_meal column is an ENUM, the average_price column is a DECIMAL, and the discovery_date column is a DATE.
Why are we using DATE instead of TIMESTAMP ? They are both similar, except that TIMESTAMP includes the DATE information (YYYY-MM-DD) as well as the time information (HH:MM:SS). We are using DATE because it allow for historic dates. From the MySQL documentation:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
The lesson here is that we each database has it's own data-type details that we need to learn. Assume nothing! And always read the documentation: http://dev.mysql.com/doc/refman/5.1/en/datetime.html
ENUM is a MySQL specific data-type. It allows for a limited range of values:
primary_meal ENUM('breakfast', 'lunch', 'dinner')
However, in typical MySQL fashion, if you do not choose one of these values (and we are not in strict mode), MySQL will not throw an error, but rather just insert a blank value.
INSERT INTO foods (name, country_of_origin, primary_meal, short_description, average_price, calories, discovery_date) VALUES
('rice', 'China', 'anytime', 'also great with anything', 0.99, 100, '1000-01-01');
Also, note that just because we are using ENUM does not mean that we cannot have NULL values:
INSERT INTO foods (name, primary_meal, short_description, discovery_date) VALUES ('water', NULL, 'we need it to survive', NULL);
Decimals are useful for representing non-integer numbers... like values for money. From the MySQL documentation:
The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.1 are as follows:
M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)
D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.
When we are dealing with money, a very common format would be DECIMAL(x,2). The precision can be as high or low as we want, but the scale is usually 2 since that is how we represent cents.
average_price DECIMAL(8,2) DEFAULT 0.00,
So far the conditions in our WHERE clauses have been fairly simple. Using () we can group together simple combinations of conditions to make more complex conditions. Here is an example:
SELECT * FROM foods
WHERE (country_of_origin = 'Italy' AND (calories < 1000 OR primary_meal = 'dinner'))
OR
(country_of_origin = 'China' AND (calories < 1000 OR primary_meal = 'dinner'));
By using the AND and OR operators and grouping conditions with (), we have create a focused query. We are looking for foods from Italy or China that are less than 1000 calories that are usually served at dinner. Go ahead an run the query.
Now let's remove the parenthesis and observe the outcome:
SELECT * FROM foods
WHERE (country_of_origin = 'Italy' AND calories < 1000 OR primary_meal = 'dinner')
OR
(country_of_origin = 'China' AND calories < 1000 OR primary_meal = 'dinner');
Not only is this query harder to understand, we also get a different result set. This second query is looking for foods from Italy with less than 1000 calories... or foods that are primarily served at dinner.... or foods from China with less than 1000 calories... or foods primarily served at dinner. Without the parenthesis in this last query the precedence of the OR and AND operators is unclear.
The lesson here is to always use parenthesis even if they are not required. It makes your queries more legible to the human eye.
The LIKE operator can be very useful for matching text. The format is as follows: WHERE column name LIKE "%value%"
The "%" character is a wildcard. Here are a few examples:
The short description ends with the word "food":
SELECT * FROM foods WHERE short_description LIKE "%food";
The short description starts with the word "great":
SELECT * FROM foods WHERE short_description LIKE "great%";
The short description has the word "with" somewhere:
SELECT * FROM foods WHERE short_description LIKE "%with%";
We can think of a SQL Key like as an index. In fact, they are often referred to as indexes. A good example of an index would be typical college textbook. Usually at the end of the book, there is an alphabetical list of topics covered in the book. Next to each topic is the page number where the topic can be found. This enables the reader to quickly locate the page they are seeking. On the other hand, imagine a phone book that was not in alphabetical order. Locating a phone number would take a long time.
Now let's imagine a SQL table with millions of rows. Once we start querying with conditions, having Keys can greatly speed up performance. To give you a real SQL example would require building a table with thousands or millions of rows, and I do not want to hand you a gigantic SQL file with thousands/millions of insert statements. So for now, consider this an abstract introduction to Keys. Enough talk, let's create a table with a few Keys. Two columns in our posts table that we might query against with great regularity would be the id and author_initials columns.
CREATE TABLE posts_week_2_keys (
id INT(11) AUTO_INCREMENT,
author_initials CHAR(2) DEFAULT '**',
title VARCHAR(255),
body TEXT,
created_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY(id),
KEY(author_initials)
);
Now go ahead and inspect this table using describe. Note that the id column is the primary key and the author_initials column has a key as well. The PRIMARY KEY was created a bit differently on this table, as opposed to the previous example. Traditionally in SQL, the keys are defined after the table column, so creating the PRIMARY KEY this way is a bit closer to standard SQL. The end result is the same.
PRIMARY KEYS by default cannot be NULL. This means that PRIMARY KEY should be a value that is always present. Having the id AUTO INCREMENT and making it your PRIMARY KEY is a very standard approach for web development.
You might ask yourself, why not just put a key on every column ? Here is the downside to Keys. You must rebuild the Index/Key every time you insert a new row. Let's go back to our textbook example. Imagine that every time the author adds a new section to the book, he must update the index in the back.
So if we have a table that is frequently having rows inserted, we must weigh the cost/benefit of placing Indexes/Keys on certain columns. In general, we only want to place Keys/Indexes on columns that we will query against in our WHERE clause. If we placed a bunch of non-useful Keys/Indexes on all of our columns, it would greatly slow down our INSERT statements. For some DB tables, that could be a big problem, and could slow down your application.
The Unique Key enforces a uniqueness constraint on one or more columns. We can see how useful right away this can be since it can help us outside of performance issue. Here is a very common real-world scenario. You have a users table and you require each user to enter an email address. To prevent duplicate accounts, we can enforce a uniqueness constraint on the email column since each email address should be unique. Our authors table is a perfect example. Let's create a new one with a UNIQUE KEY on the email column.
CREATE TABLE authors_unique_key (
id INT(11) AUTO_INCREMENT,
email VARCHAR(255),
first_name VARCHAR(255),
last_name VARCHAR(255),
active TINYINT(1) DEFAULT 1,
created_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY(id),
UNIQUE KEY(email)
);
Now consider the following 2 insert statements.
INSERT INTO authors_unique_key (email, first_name, last_name) VALUES ('rob@winterfell.com', 'Rob', 'Stark');
INSERT INTO authors_unique_key (email, first_name, last_name) VALUES ('rob@winterfell.com', 'Robert', 'Stark');
The first one will succeed, but the second insert statement fails. It is violating the UNIQUE KEY on the email column.
The UNIQUE KEY can also be placed across more than one column. Consider the following table:
CREATE TABLE authors_unique_key_2(
id INT(11) AUTO_INCREMENT,
email VARCHAR(255),
first_name VARCHAR(255),
last_name VARCHAR(255),
active TINYINT(1) DEFAULT 1,
created_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY(id),
UNIQUE KEY(first_name, last_name)
);
This UNIQUE KEY is telling us that the combination of first_name and last_name must be unique. Consider the following 3 queries:
INSERT INTO authors_unique_key_2 (email, first_name, last_name) VALUES ('rob@winterfell.com', 'Rob', 'Stark');
INSERT INTO authors_unique_key_2 (email, first_name, last_name) VALUES ('arya@winterfell.com', 'Arya', 'Stark');
INSERT INTO authors_unique_key_2 (email, first_name, last_name) VALUES ('rob@yahoo.com', 'Rob', 'Stark');
The first 2 queries succeed, but the third fails. The third query does not have a unique first_name and last_name combination.
In the web world when we are dealing with many different resources, joining tables becomes a very powerful tool. Often these resources are stored in separate DB tables, so we must join them to avoid making multiple queries for each related resource. We needs some tables to work with so please create your "posts_week_3", "authors_week_3", and our new "comments" tables and insert the data included in the source code.
This is a typical relationship for our blog application's resources. We could classify these relationships by saying the following truths:
- An author has many posts
- A post belongs to an author
- A post has many comments
- A comment belongs to a post
These relationship descriptors ("has many" and "belongs to") are not official by any means. Programmers have used other ways of describing the same relationships. We have built our tables in such a way so that we can support these relationship. Let's describe each of these tables and talk about the column relationships, before we get into how to join these tables:
mysql> desc posts_week_3;
+------------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+-------------------+----------------+
| id* | int(11) | NO | PRI | NULL | auto_increment |
| author_id**| int(11) | NO | | NULL | |
| title | varchar(255) | YES | | NULL | |
| body | text | YES | | NULL | |
| active | tinyint(1) | YES | | 1 | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
+------------+--------------+------+-----+-------------------+----------------+
6 rows in set (0.05 sec)
mysql> desc authors_week_3;
+------------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+-------------------+----------------+
| id* | int(11) | NO | PRI | NULL | auto_increment |
| email | varchar(255) | YES | | NULL | |
| first_name | varchar(255) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
| active | tinyint(1) | YES | | 1 | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
+------------+--------------+------+-----+-------------------+----------------+
6 rows in set (0.04 sec)
mysql> desc comments;
+--------------+------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------+------+-----+-------------------+----------------+
| id* | int(11) | NO | PRI | NULL | auto_increment |
| post_id** | int(11) | NO | | NULL | |
| comment_text | text | YES | | NULL | |
| active | tinyint(1) | YES | | 1 | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
+--------------+------------+------+-----+-------------------+----------------+
5 rows in set (0.05 sec)
In each table I have place a single asterisk * next to the PRIMARY KEY. We have already talked a bit about Primary Keys. They are unique identifiers for each row. Each row in a table has a unique id.
I have also placed double asterisk ** next to column names that server as Foreign Keys. These are important columns because they (usually) tie to another table's Primary Key. Since an author has many posts, the posts.author_id column serves as the Foreign Key for the authors table. We can join an authors row to a posts row by looking for the authors.id that matches it's Foreign Key, posts.author_id.
The same is true for the relationship between a posts and it's comments. Since a post has many comments, we can match any given post to it's comments by joining the posts.id to it's matching Foreign Key, comments.post_id .
Confusing ? Good. If not, then start looking for a job right now! Joins can be very confusing at first. I know very few people who understand Relational Databases on their first try. Some diagrams might help:
So here is our scary joins query...
SELECT posts_week_3.title, posts_week_3.body, authors_week_3.first_name, authors_week_3.last_name, comments.comment_text
FROM posts_week_3 INNER JOIN authors_week_3 ON (posts_week_3.author_id = authors_week_3.id)
INNER JOIN comments ON (posts_week_3.id = comments.post_id)
Notice we are always joining Primary Key to Foreign Key. This is the most common case. Let's break this query down and discuss it.... in class.
Parenthesis can also be used to house sub queries. When matching a single value, the sub query must return a single value of the correct data-type.
SELECT * FROM posts_week_3 WHERE author_id = (SELECT id FROM authors_week_3 WHERE first_name = 'Tyrion' AND last_name = 'Lanister');
The subquery here returns a single value of 3. It's always a good idea to run the sub query first, to make sure it works and returns the proper value(s), before running the entire outer query.
Another example:
SELECT * FROM posts_week_3 WHERE author_id IN (SELECT id FROM authors_week_3 WHERE last_name = 'Lanister');
Our 2nd sub query example returns multiple ids which is what we want - we are using the IN operator.
Sometimes we need to change an existing value in one or more of our columns. Here is the basic format of an UPDATE query: UPDATE table name SET column name = value WHERE condition We do not need a WHERE condition, but unless you want to update every value in a column, then we better use it. Using the WERE condition is the much more common case for update statements.
This update query will change the value of every
UPDATE posts_week_3 SET active = 0;
Here is a more common update query. It will update all of author #3's posts as active.
UPDATE posts_week_3 SET active = 1 WHERE author_id = 3;
Here is a query that updates multiple columns. The different column updates are separate by a comma.
UPDATE posts_week_3 SET active = 1, created_at = '2012-04-01' WHERE author_id != 3;
Updates are one of the more dangerous queries because it's easy to update an entire table if you forget your WHERE clause. Because of this, I know some programmers who will write the WHERE clause first, and the complete the beginning of the update query to ensure they do not wreak havoc on their data.
We can delete rows from our DB tables, but we must be very careful! The DELETE statement is practically identical to the SELECT statement in its format. Here is a typical format of a delete statement:
DELETE FROM <table name> WHERE <where clause>
Here is a more typical DELETE statement, deleting all posts by anonymous authors:
DELETE FROM posts_week_3 WHERE author_id = 1;
Without a WHERE clause, a DELETE statement will delete all of the rows in your DB table! Observe, but (for now) do not execute the following SQL statement:
DELETE FROM posts_week_3;
It's very easy to accidentally wipe a table clean from all of it's data. Therefore, when I am executing DELETE statements, I will make sure not to include the statement terminator (; or \G) at the end of my statement until I am sure it is correct. This way, even if I accidentally hit the return key, I will not wipe out my data. That being said, most programmers I know have made this mistake at least once, so it's a good idea to back up your data frequently or run your sensitive SQL queries inside of transactions. We will cover this towards the end of the course.