Archive for the ‘MySql’ Category


SQL Basics

Monday, April 14th, 2008

Basics of SQL covers table creation to manipulating records. The table creation command requires three important pieces of information—the table name, the field name, and the field definitions. Field definitions are important because a well-designed table will help speed along your database. MySQL has three different categories of data types: numeric, date and time, and string.

The INSERT command, used to add records to a table, names the table and columns you want to populate, and then defines the values. When placing values in the INSERT statement, strings must be enclosed with single or double quotes. The SELECT SQL command is used to retrieve records from specific tables. The * character enables you to easily select all fields for all records in a table, but you can also specify particular column names. If the result set is too long, the LIMIT clause provides a simple method for extracting slices of results if you indicate a starting position and the number of records to return. To order the results, use the ORDER BY clause to select the columns to sort. Sorts can be performed on integers, dates, and strings, in either ascending or descending order. The default order is ascending. Without specifying an order, results are displayed in the order they appear in the table.

You can pick and choose which records you want to return using WHERE clauses to test for the validity of conditions. Comparison or logical operators are used in WHERE clauses, and sometimes both types are used for compound statements. Selecting records from multiple tables within one statement is as advanced as it gets, as these types of statements—called JOIN—require forethought and planning to produce correct results. Common types of JOIN are INNER JOIN, LEFT JOIN, and RIGHT JOIN, although MySQL supports many different kinds of JOIN.

The UPDATE and REPLACE commands are used to modify existing data in your MySQL tables. UPDATE is good for changing values in specific columns or to change values in multiple records based on specific conditions. REPLACE is a variation of INSERT that deletes, and then reinserts a record with a matching primary key. Be very careful when using UPDATE to change values in a column because failure to add a condition will result in the given column being updated throughout all records in the table.

The DELETE command is a simple one—it simply removes whole records from tables. This also makes it very dangerous, so be sure you give DELETE privileges only to users who can handle the responsibility. You can specify conditions when using DELETE so that records are removed only if a particular expression in a WHERE clause is true. Also, you can delete smaller portions of the records in your table using a LIMIT clause. If you have an exceptionally large table, deleting portions is less resource-intensive than deleting each record in a huge table.


Using the DELETE Command

Monday, April 14th, 2008

The basic DELETE syntax is

DELETE FROM table_name

[WHERE some_condition_is_true]

[LIMIT rows]

Notice there is no column specification in the delete command—when you use DELETE, the entire record is removed.

Assuming the structure and data in a table called fruit:

mysql> select * from fruit;

+—-+————+——–+

| id | fruit_name | status |

+—-+————+——–+

|  1 | apple      | ripe   |

|  2 | pear       | rotten |

|  3 | banana     | ripe   |

|  4 | grape      | rotten |

+—-+————+——–+

4 rows in set (0.00 sec)

This statement will remove all records in the table:

mysql> delete from fruit;
Query OK, 0 rows affected (0.00 sec)

You can always verify the deletion by attempting to SELECT data from the table:

mysql> select * from fruit;
Empty set (0.00 sec)

All your fruit is gone.

Conditional DELETE

A conditional DELETE statement, just like a conditional SELECT or UPDATE statement, means you are using WHERE clauses to match specific records. You have the full range of comparison and logical operators available to you, so you can pick and choose which records you want to delete.

A prime example would be to remove all records for rotten fruit from the fruit table:

mysql> delete from fruit where status = ‘rotten’;
Query OK, 2 rows affected (0.00 sec)

Two records were deleted, and only ripe fruit remains:

mysql> select * from fruit;

+—-+————+——–+

| id | fruit_name | status |

+—-+————+——–+

|  1 | apple      | ripe   |

|  3 | banana     | ripe   |

+—-+————+——–+

2 rows in set (0.00 sec)

For users of MySQL 4.0 (or later), you can also use ORDER BY clauses in your DELETE statements. Take a look at the basic DELETE syntax with the ORDER BY clause added to its structure:

DELETE FROM table_name

[WHERE some_condition_is_true]

[ORDER BY some_column [ASC | DESC]]

[LIMIT rows]

At first glance, you might wonder, “Why does it matter in what order I delete records?” The ORDER BY clause isn’t for the deletion order, it’s for the sorting order of records.

In this example, a table called access_log shows access time and username:

mysql> select * from access_log;

+—-+———————+———-+

| id | date_accessed       | username |

+—-+———————+———-+

|  1 | 2001-11-06 06:09:13 | johndoe  |

|  2 | 2001-11-06 06:09:22 | janedoe  |

|  3 | 2001-11-06 06:09:39 | jsmith   |

|  4 | 2001-11-06 06:09:44 | mikew    |

+—-+———————+———-+

4 rows in set (0.00 sec)

To remove the oldest record, first use ORDER BY to sort the results appropriately, then use LIMIT to remove just one record:

mysql> delete from access_log order by date_accessed desc limit 1;

Query OK, 1 row affected (0.01 sec)

Select the record from access_log and verify that only three records exist:

mysql> select * from access_log;

+—-+———————+———-+

| id | date_accessed       | username |

+—-+———————+———-+

|  2 | 2001-11-06 06:09:22 | janedoe  |

|  3 | 2001-11-06 06:09:39 | jsmith   |

|  4 | 2001-11-06 06:09:44 | mikew    |

+—-+———————+———-+

3 rows in set (0.00 sec)


Using the REPLACE Command

Monday, April 14th, 2008

Another method for modifying records is to use the REPLACE command, which is remarkably similar to the INSERT command.

REPLACE INTO table_name (column list) VALUES (column values);

The REPLACE statement works like this: if the record you are inserting into the table contains a primary key value that matches a record already in the table, the record in the table will be deleted and the new record inserted in its place.

 

The REPLACE command is a MySQL-specific extension to ANSI SQL. This command mimics the action of a DELETE and re-INSERT of a particular record. In other words, you get two commands for the price of one.

Using the grocery_inventory table, the following command will replace the entry for Apples:

mysql> replace into grocery_inventory values

    -> (1, ‘Granny Smith Apples’, ‘Sweet!’, ‘0.50′, 1000);

Query OK, 2 rows affected (0.00 sec)

In the query result, notice that the result states, “2 rows affected“. In this case, because id is a primary key that had a matching value in the grocery_inventory table, the original row was deleted and the new row inserted—2 rows affected.

Select the records to verify that the entry is correct, which it is

mysql> select * from grocery_inventory;

+—-+———————–+———————–+———–+———–+

| id | item_name             | item_desc             | item_price | curr_qty |

+—-+———————–+———————–+————+———-+

|  1 | Granny Smith Apples   | Sweet!                |        0.5 |     1000 |

|  2 | Bunches of Grapes     | Seedless grapes.      |       2.99 |      500 |

|  3 | Bottled Water (6-pack)| 500ml spring water.   |       2.29 |      250 |

|  4 | Bananas               | Bunches, green.       |       1.99 |      150 |

|  5 | Pears                 | Anjou, nice and sweet.|        0.5 |      500 |

|  6 | Avocado               | Large Haas variety.   |       0.99 |      750 |

+—-+———————–+———————–+————+———-+

6 rows in set (0.00 sec)

If you use a REPLACE statement, and the value of the primary key in the new record does not match a value for a primary key already in the table, the record would simply be inserted and only one row would be affected.


Using the UPDATE Command to Modify Records

Monday, April 14th, 2008

UPDATE is the SQL command used to modify the contents of one or more columns in an existing record. The most basic UPDATE syntax looks like this:

UPDATE table_name

SET column1='new value',

column2='new value2'

[WHERE some_condition_is_true]

The guidelines for updating a record are similar to those used when inserting a record—the data you’re entering must be appropriate to the data type of the field, and you must enclose your strings in single or double quotes, escaping where necessary.

For example, assume you have a table called fruit containing an ID, a fruit name, and the status of the fruit (ripe or rotten):

mysql> SELECT * FROM fruit;

+—-+————+——–+

| id | fruit_name | status |

+—-+————+——–+

|  1 | apple      | ripe   |

|  2 | pear       | rotten |

|  3 | banana     | ripe   |

|  4 | grape      | rotten |

+—-+————+——–+

4 rows in set (0.00 sec)

To update the status of the fruit to “ripe“, use

mysql> update fruit set status = ‘ripe’;

Query OK, 2 rows affected (0.00 sec)

Rows matched: 4 Changed: 2 Warnings: 0

Take a look at the result of the query. It was successful, as you can tell from the Query OK message. Also note that only 2 rows were affected—if you try to set the value of a column to the value it already is, the update won’t occur for that column.

The second line of the response shows that 4 rows were matched, and only 2 were changed. If you’re wondering “matched what?” the answer is simple—because you did not specify a particular condition for matching, the match would be “all rows“.

You must be very careful and use a condition when updating a table, unless you really intend to change all the columns for all records to the same value. For the sake of argument, assume that “grape” is spelled incorrectly in the table, and you want to use UPDATE to correct this mistake. This query would have horrible results:

mysql> update fruit set fruit_name = ‘grape’;

Query OK, 4 rows affected (0.00 sec)

Rows matched: 4 Changed: 4 Warnings: 0

When you read the result, you should be filled with dread: 4 of 4 records were changed, meaning your fruit table now looks like this:

mysql> SELECT * FROM fruit;

+—-+————+——–+

| id | fruit_name | status |

+—-+————+——–+

|  1 | grape      | ripe   |

|  2 | grape      | ripe   |

|  3 | grape      | ripe   |

|  4 | grape      | ripe   |

+—-+————+——–+

4 rows in set (0.00 sec)

All your fruit records are now grapes. Through attempting to correct the spelling of one field, all fields were changed because no condition was specified! When doling out UPDATE privileges to your users, think about the responsibility you’re giving to someone—one wrong move and your entire table could be grapes.

Conditional UPDATEs

Making a conditional UPDATE means that you are using WHERE clauses to match specific records. Using a WHERE clause in an UPDATE statement is just like using a WHERE clause in a SELECT statement. All the same comparison and logical operators can be used, such as “equal to“, “greater than“, “OR“, “AND“—the whole nine yards.

Assume your fruit table has not been completely filled with grapes, but instead contains four records, one with a spelling mistake (”grappe” instead of “grape“). The UPDATE statement to fix the spelling mistake would be

mysql> update fruit set fruit_name = ‘grape’ where fruit_name = ‘grappe’;

Query OK, 1 row affected (0.00 sec)

Rows matched: 1 Changed: 1 Warnings: 0

In this case, only one row was matched and one row was changed. Your fruit table should be intact, and all fruit names should be spelled properly:

mysql> select * from fruit;

+—-+————+——–+

| id | fruit_name | status |

+—-+————+——–+

|  1 | apple      | ripe   |

|  2 | pear       | ripe   |

|  3 | banana     | ripe   |

|  4 | grape      | ripe   |

+—-+————+——–+

4 rows in set (0.00 sec)

Using Existing Column Values with UPDATE

Another feature of UPDATE is the capability to use the current value in the record as the base value.

mysql> select * from grocery_inventory;

+—-+———————–+————————+——+—–+———-+

| id | item_name             | item_desc              | item_price | curr_qty |

+—-+———————–+————————+————+———-+

|  1 | Apples                | Beautiful, ripe apples.|       0.25 |     1000 |

|  2 | Bunches of Grapes     | Seedless grapes.       |       2.99 |      500 |

|  3 | Bottled Water (6-pack)| 500ml spring water.    |       2.29 |      250 |

|  4 | Bananas               | Bunches, green.        |       1.99 |      150 |

|  5 | Pears                 | Anjou, nice and sweet. |        0.5 |      500 |

|  6 | Avocado               | Large Haas variety.    |       0.99 |      750 |

+—-+———————–+————————+————+———-+

6 rows in set (0.00 sec)

When someone purchases an apple, the inventory table should be updated accordingly. However, you won’t know exactly what number to enter in the curr_qty column, just that you sold one. In this case, use the current value of the column and subtract one:

mysql> update grocery_inventory set curr_qty = curr_qty - 1 where id = 1;

Query OK, 1 row affected (0.00 sec)

Rows matched: 1 Changed: 1 Warnings: 0

This should give you a new value of 999 in the curr_qty column, and indeed it does:

mysql> select * from grocery_inventory;

+—-+———————–+————————+————+———-+

| id | item_name             | item_desc              | item_price | curr_qty |

+—-+———————–+————————+————+———-+

|  1 | Apples                | Beautiful, ripe apples.|       0.25 |      999 |

|  2 | Bunches of Grapes     | Seedless grapes.       |       2.99 |      500 |

|  3 | Bottled Water (6-pack)| 500ml spring water.    |       2.29 |      250 |

|  4 | Bananas               | Bunches, green.        |       1.99 |      150 |

|  5 | Pears                 | Anjou, nice and sweet. |        0.5 |      500 |

|  6 | Avocado               | Large Haas variety.    |       0.99 |      750 |

+—-+———————–+————————+————+———-+

6 rows in set (0.00 sec)


Selecting from Multiple Tables, Join

Saturday, April 12th, 2008

Selecting from Multiple Tables

You’re not limited to selecting only one table at a time. That would certainly make application programming a long and tedious task! When you select from more than one table in one SELECT statement, you are said to be joining the tables together.

Suppose you have two tables, fruit and color. You can select all rows from each of the two tables, using two separate SELECT statements:

mysql> select * from fruit;
 +—-+———–+
 | id | fruitname |
 +—-+———–+
 |  1 | apple     |
 |  2 | orange    |
 |  3 | grape     |
 |  4 | banana    |
 +—-+———–+
 4 rows in set (0.00 sec)
mysql> select * from color;
 +—-+———–+
 | id | colorname |
 +—-+———–+
 |  1 | red       |
 |  2 | orange    |
 |  3 | purple    |
 |  4 | yellow    |
 +—-+———–+
 4 rows in set (0.00 sec)

When you want to select from both tables at once, there are a few differences in the syntax of the SELECT statement. First, you must ensure that all the tables you’re using in your query appear in the FROM clause of the SELECT statement. Using the fruit and color example, if you simply want to select all columns and rows from both tables, you might think you would use the following SELECT statement:

mysql> select * from fruit, color;
 +—-+———–+—-+———–+
 | id | fruitname | id | colorname |
 +—-+———–+—-+———–+
 |  1 | apple     |  1 | red       |
 |  2 | orange    |  1 | red       |
 |  3 | grape     |  1 | red       |
 |  4 | banana    |  1 | red       |
 |  1 | apple     |  2 | orange    |
 |  2 | orange    |  2 | orange    |
 |  3 | grape     |  2 | orange    |
 |  4 | banana    |  2 | orange    |
 |  1 | apple     |  3 | purple    |
 |  2 | orange    |  3 | purple    |
 |  3 | grape     |  3 | purple    |
 |  4 | banana    |  3 | purple    |
 |  1 | apple     |  4 | yellow    |
 |  2 | orange    |  4 | yellow    |
 |  3 | grape     |  4 | yellow    |
 |  4 | banana    |  4 | yellow    |
 +—-+———–+—-+———–+
 16 rows in set (0.00 sec)

Sixteen rows of repeated information is probably not what you were going for! What this query did is literally join a row in the color table to each row in the fruit table. Because there are four records in the fruit table and four entries in the color table, that’s 16 records returned to you.

When you select from multiple tables, you must build proper WHERE clauses to ensure you really get what you want. In the case of the fruit and color tables, what you really want is to see the fruitname and colorname records from these two tables where the IDs of each match up. This brings us to the next nuance of the query—how to indicate exactly which field you want when the fields are named the same in both tables!

Simply, you append the table name to the field name, like this:

tablename.fieldname

So, the query for selecting fruitname and colorname from both tables where the IDs match would be

mysql> select fruitname, colorname from fruit, color where fruit.id = color.id;
 +———–+———–+
 | fruitname | colorname |
 +———–+———–+
 | apple     | red       |
 | orange    | orange    |
 | grape     | purple    |
 | banana    | yellow    |
 +———–+———–+
 4 rows in set (0.00 sec)

However, if you attempt to select a column that appears in both tables with the same name, you will get an ambiguity error:

mysql> select id, fruitname, colorname from fruit, color
-> where fruit.id = color.id;
 ERROR 1052: Column: ‘id’ in field list is ambiguous

If you mean to select the id from the fruit table, you would use

mysql> select fruit.id, fruitname, colorname from fruit,
     -> color where fruit.id = color.id;
 +——+———–+———–+
 | id   | fruitname | colorname |
 +——+———–+———–+
 |    1 | apple     | red       |
 |    2 | orange    | orange    |
 |    3 | grape     | purple    |
 |    4 | banana    | yellow    |
 +——+———–+———–+
 4 rows in set (0.00 sec)

Using JOIN

Several types of JOINs can be used in MySQL, all of which refer to the order in which the tables are put together and the results are displayed. The type of JOIN used with the fruit and color tables is called an INNER JOIN, although it wasn’t written explicitly as such. To rewrite the SQL statement using the proper INNER JOIN syntax, you would use

mysql> select fruitname, colorname from fruit inner join color
-> on fruit.id = color.id;
 +———–+———–+
 | fruitname | colorname |
 +———–+———–+
 | apple     | red       |
 | orange    | orange    |
 | grape     | purple    |
 | banana    | yellow    |
 +———–+———–+
 4 rows in set (0.00 sec)

The ON clause replaced the WHERE clause, in this instance telling
MySQL to join together the rows in the tables where the IDs match
each other.
When joining tables using ON clauses, you can use any conditions
that you would use in a WHERE clause, including all the various
logical and arithmetic operators.

Another common type of JOIN is the LEFT JOIN. When joining two
tables with LEFT JOIN, all rows from the first table will be
returned, no matter if there are matches in the second table or not.
Suppose you have two tables in an address book, one called master_name,
containing basic records, and one called email, containing email records.
Any records in the email table would be tied to a particular id of a
record in the master_name table. For example

mysql> select name_id, firstname, lastname from master_name;
 +———+———–+———-+
 | name_id | firstname | lastname |
 +———+———–+———-+
 |       1 | John      | Smith    |
 |       2 | Jane      | Smith    |
 |       3 | Jimbo     | Jones    |
 |       4 | Andy      | Smith    |
 |       7 | Chris     | Jones    |
 |      45 | Anna      | Bell     |
 |      44 | Jimmy     | Carr     |
 |      43 | Albert    | Smith    |
 |      42 | John      | Doe      |
 +———+———–+———-+
 9 rows in set (0.00 sec)
 mysql> select name_id, email from email;
 +———+——————+
 | name_id | email            |
 +———+——————+
 |      42 | jdoe@yahoo.com   |
 |      45 | annabell@aol.com |
 +———+——————+
 2 rows in set (0.00 sec)

Using LEFT JOIN on these two tables, you can see that
if a value from the email table doesn’t exist, NULL will
appear in place of an email address:

mysql> select firstname, lastname, email fom master_name
 left join email
 -> on master_name.name_id = email.name_id;
 +———–+———-+——————+
 | firstname | lastname | email            |
 +———–+———-+——————+
 | John      | Smith    | NULL             |
 | Jane      | Smith    | NULL             |
 | Jimbo     | Jones    | NULL             |
 | Andy      | Smith    | NULL             |
 | Chris     | Jones    | NULL             |
 | Anna      | Bell     | annabell@aol.com |
 | Jimmy     | Carr     | NULL             |
 | Albert    | Smith    | NULL             |
 | John      | Doe      | jdoe@yahoo.com   |
 +———–+———-+——————+
 9 rows in set (0.01 sec)

A RIGHT JOIN works like LEFT JOIN, but with the table order
reversed.
In other words, when using a RIGHT JOIN, all rows from the
second table will be returned,
no matter whether there are matches in the first table or not.
However, in the case of the master_name and email tables, there
are only two rows in the email table,
whereas there are nine rows in the master_name table. This means that
only two of the nine rows will be returned:

mysql> select firstname, lastname, email from master_name right join
email
-> on master_name.name_id = email.name_id;
 +———–+———-+——————+
 | firstname | lastname | email            |
 +———–+———-+——————+
 | John      | Doe      | jdoe@yahoo.com   |
 | Anna      | Bell     | annabell@aol.com |
 +——+—–+—————————-+
 2 rows in set (0.00 sec)

Several different types of JOINs are available in MySQL, and
you’ve learned about the most common types.
You can also learn more about JOINs such as CROSS JOIN,
STRAIGHT JOIN and NATURAL JOIN


Using WHERE in SQL , operators and comparision criterias with where clause

Saturday, April 12th, 2008

You may have to retrieve specific rows apart from retrieving particular columns from your tables. This is when the WHERE clause comes in to play. From the basic SELECT syntax, you see that WHERE is used to specify a particular condition:

SELECT expressions_and_columns FROM table_name [WHERE some_condition_is_true]

An example would be to retrieve all the records for items with a quantity of 500:

mysql> select * from grocery_inventory where curr_qty = 500;
+—-+——————-+————————+————+———-+
 | id | item_name         | item_desc              | item_price | curr_qty |
 +—-+——————-+————————+————+———-+
 |  2 | Bunches of Grapes | Seedless grapes.       |       2.99 |      500 |
 |  5 | Pears             | Anjou, nice and sweet. |        0.5 |      500 |
 +—-+——————-+————————+————+———-+
 2 rows in set (0.00 sec)

As shown previously, if you use an integer as the WHERE clause comes in to play. From part of your WHERE clause, quotation marks are not required. Quotation marks are required around strings, and the same rules apply with regard to escaping characters, as you learned in the section on INSERT.

Using Operators in WHERE Clauses

You’ve used the equal sign (=) in your WHERE clauses to determine the truth of a condition—is one thing equal to another. You can use many types of operators, with comparison operators and logical operators being the most popular types.

Comparison operators, shown in the table below, should look familiar to you if you think about the first day of algebra class.

Operator

Meaning

=

Equal to

!=

Not equal to

<=

Less than or equal to

<

Less than

>=

Greater than or equal to

>

Greater than

There’s also a handy operator called BETWEEN, which is useful with integer or data comparisons because it searches for results between a minimum and maximum value. For example

mysql> select * from grocery_inventory where item_price
-> between 1.50 and 3.00;
+—-+————————+———————+————+———-+
 | id | item_name              | item_desc           | item_price | curr_qty |
 +—-+————————+———————+————+———-+
 |  2 | Bunches of Grapes      | Seedless grapes.    |       2.99 |      500 |
 |  3 | Bottled Water (6-pack) | 500ml spring water. |       2.29 |      250 |
 |  4 | Bananas                | Bunches, green.     |       1.99 |      150 |
 +—-+————————+———————+————+———-+
 3 rows in set (0.00 sec)

Other operators include logical operators, which enable you to use multiple comparisons within your WHERE clause. The basic logical operators are AND and OR. When using AND, all comparisons in the clause must be true to the WHERE clause comes in to play. From retrieve results, whereas using OR allows a minimum of one comparison to be true.

String Comparison Using LIKE

You were introduced to matching strings within a WHERE clause by using = or !=, but there’s another useful operator for the WHERE clause comes in to play. From string comparisons: LIKE. This operator uses two characters as wildcards in pattern matching.

  • %— Matches multiple characters

  • _— Matches exactly one character

If you want to find records in the grocery_inventory table where the first name of the item starts with the letter “A“, use

mysql> select * from grocery_inventory where item_name like ‘A%’;
+—-+———–+————————-+————+———-+
 | id | item_name | item_desc               | item_price | curr_qty |
 +—-+———–+————————-+————+———-+
 |  1 | Apples    | Beautiful, ripe apples. |       0.25 |     1000 |
 |  6 | Avocado   | Large Haas variety.     |       0.99 |      750 |
 +—-+———–+————————-+————+———-+
 

Unless performing a LIKE comparison on a binary string, the comparison is not case sensitive.


Using the SELECT Command ,Order by clause and limiting the result

Saturday, April 12th, 2008

SELECT is the SQL command used to retrieve records. This command syntax can be totally simplistic or very complicated. As you become more comfortable with database programming, you will learn to enhance your SELECT statements, ultimately making your database do as much work as possible and not overworking your programming language of choice.

The most basic SELECT syntax looks like this:

SELECT expressions_and_columns FROM table_name
[WHERE some_condition_is_true]
[ORDER BY some_column [ASC | DESC]]
[LIMIT offset, rows]

Start with the first line:

SELECT expressions_and_columns FROM table_name

One handy expression is the * symbol, which stands for “everything.” So, to select “everything” (all rows, all columns) from the grocery_inventory table, your SQL statement would be

SELECT * FROM grocery_inventory;

Depending on how much data you inserted into the grocery_inventory table during the previous hour, your results will vary, but it might look something like this:

mysql> select * from grocery_inventory;
+—+———————–+————————+———–+———+
| id| item_name             | item_desc              | item_price| curr_qty|
+—+———————–+————————+———–+———+
|  1| Apples                | Beautiful, ripe apples.|       0.25|     1000|
|  2| Bunches of Grapes     | Seedless grapes.       |       2.99|      500|
|  3| Bottled Water (6-pack)| 500ml spring water.    |       2.29|      250|
+—+———————–+————————+———–+———+
3 rows in set (0.00 sec)

As you can see, MySQL creates a lovely table with the names of the columns along the first row as part of the result set. If you only want to select specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the id, item_name, and curr_qty fields from the grocery_inventory table.

mysql> select id, item_name, curr_qty from grocery_inventory;
+—-+————————+———-+
| id | item_name              | curr_qty |
+—-+————————+———-+
|  1 | Apples                 |     1000 |
|  2 | Bunches of Grapes      |      500 |
|  3 | Bottled Water (6-pack) |      250 |
+—-+————————+———-+
3 rows in set (0.00 sec)

Ordering SELECT Results

By default, results of SELECT queries are ordered as they were inserted into the table, and shouldn’t be relied upon as a meaningful ordering system. If you want to order results a specific way, such as by date, ID, name, and so on, specify your requirements using the ORDER BY clause. In the following statement, results are ordered by item_name:

mysql> select id, item_name, curr_qty from grocery_inventory
-> order by item_name;
+—-+————————+———-+
| id | item_name              | curr_qty |
+—-+————————+———-+
|  1 | Apples                 |     1000 |
|  3 | Bottled Water (6-pack) |      250 |
|  2 | Bunches of Grapes      |      500 |
+—-+————————+———-+
3 rows in set (0.04 sec)
 

When selecting results from a table without specifying a sort order, the results may or may not be ordered by their key value. This occurs because MySQL reuses the space taken up by previously deleted rows. In other words, if you add records with ID values of 1 through 5, delete the record with ID number 4, then add another record (ID number 6), the records might appear in the table in this order: 1, 2, 3, 6, 5.

The default sorting of ORDER BY results is ascending (ASC); strings sort from A to Z, integers start at 0, dates sort from oldest to newest. You can also specify a descending sort, using DESC:

mysql> select id, item_name, curr_qty from grocery_inventory
-> order by item_name desc;
+—-+————————+———-+
| id | item_name              | curr_qty |
+—-+————————+———-+
|  2 | Bunches of Grapes      |      500 |
|  3 | Bottled Water (6-pack) |      250 |
|  1 | Apples                 |     1000 |
+—-+————————+———-+
3 rows in set (0.00 sec)

You’re not limited to sorting by just one field—you can specify as many fields as you want, separated by a comma. The sorting priority is the order in which you list the fields.

Limiting Your Results

You can use the LIMIT clause to return only a certain number of records in your SELECT query result. There are two requirements when using the LIMIT clause: offset and number of rows. The offset is the starting position, and the number of rows should be self-explanatory.

 

For the most part, counting while programming always starts at 0, not 1. For example: 0, 1, 2, 3 instead of 1, 2, 3, 4.

Suppose you had more than 2 or 3 records in the grocery_inventory table, and you wanted to select the id, name, and quantity of the first 3, ordered by curr_qty. In other words, you want to select the 3 items with the least inventory, the following single-parameter limit will start at the 0 position and go to the third record:

mysql> select id, item_name, curr_qty from grocery_inventory
-> order by curr_qty limit 3;
+—-+————————+———-+
| id | item_name              | curr_qty |
+—-+————————+———-+
|  4 | Bananas                |      150 |
|  3 | Bottled Water (6-pack) |      250 |
|  2 | Bunches of Grapes      |      500 |
+—-+————————+———-+
3 rows in set (0.00 sec)

The LIMIT clause can be quite useful in an actual application. For example, you can use the LIMIT clause within a series of SELECT statements to essentially page through results in steps:

  1. SELECT * FROM grocery_inventory ORDER BY curr_qty LIMIT 0, 3;

  2. SELECT * FROM grocery_inventory ORDER BY curr_qty LIMIT 3, 3;

  3. SELECT * FROM grocery_inventory ORDER BY curr_qty LIMIT 6, 3;

If you specify an offset and number of rows in your query and no results are found, you won’t see an error—just an empty result set. For example, if the grocery_inventory table contains only 6 records, a query with a LIMIT offset of 6 will produce no results:

mysql> select id, item_name, curr_qty from grocery_inventory
-> order by curr_qty limit 6, 3;
Empty set (0.00 sec)

In Web-based applications, when lists of data are displayed with links such as “previous 10″ and “next 10,” it’s a safe bet that a LIMIT clause is at work.


Table Creation Syntax and Insert syntax

Saturday, April 12th, 2008

The table creation command requires

  • Name of the table

  • Names of fields

  • Definitions for each field

The generic table creation syntax is

CREATE TABLE table_name (column_name column_type);

For example, if you have a table that holds the inventory of a grocery store, you would probably name it something like grocery_inventory. Similarly, the field names you select should be as concise as possible and relevant to the function they serve and data they hold. For example, you might call a field holding the name of an item item_name.

This example creates a generic grocery_inventory table with fields for ID, name, description, price, and quantity:

mysql> CREATE TABLE grocery_inventory (
-> id int not null primary key auto_increment,
-> item_name varchar (50) not null,
-> item_desc text,
-> item_price float not null,
-> curr_qty int not null
-> );
 

The id field is defined as a primary key.  By using auto_increment as an attribute of the field, you are telling MySQL to go ahead and add the next available number to the id field for you.

Using the INSERT Command

After you have created some tables, you’ll use the SQL command INSERT for adding new records to these tables. The basic syntax of INSERT is

INSERT INTO table_name (column list) VALUES (column values);

Within the parenthetical list of values, you must enclose strings within quotation marks. The SQL standard is single quotes, but MySQL enables the usage of either single or double quotes. Remember to escape the type of quotation mark used, if it’s within the string itself.

 

Integers do not require quotation marks around them.

Here is an example of a string where escaping is necessary:

O'Connor said "Boo"

If you enclose your strings in double quotes, the INSERT statement would look like this:

INSERT INTO table_name (column_name) VALUES ("O'Connor said \"Boo\"");

If you enclose your strings in single quotes instead, the INSERT statement would look like this:

INSERT INTO table_name (column_name) VALUES ('O\'Connor said "Boo"');

A Closer Look at INSERT

Besides the table name, there are two main parts of the INSERT statement—the column list and the value list. Only the value list is actually required, but if you omit the column list, you must specifically name each column in your values list in order.

Using the grocery_inventory table as an example, you have five fields: id, item_name, item_desc, item_price, and curr_qty. To insert a complete record, you could use either of these statements:

  1. A statement with all columns named:

    insert into grocery_inventory (id, item_name, item_desc, item_price, curr_qty)
     values ('1', 'Apples', 'Beautiful, ripe apples.', '0.25', 1000);

  2. A statement that uses all columns but does not explicitly name them:

    insert into grocery_inventory values
    ('2', 'Bunches of Grapes', 'Seedless grapes.', '2.99', 500);

Give both of them a try and see what happens. You should get results like this:

mysql> insert into grocery_inventory
-> (id, item_name, item_desc, item_price, curr_qty)
 -> values
-> (1, ‘Apples’, ‘Medium-sized Granny Smith apples.’, 0.25, 1000);
mysql> insert into grocery_inventory values
(2, ‘Bunches of Grapes’,
 -> ‘Seedless grapes.’, 2.99, 500);

Now for some more interesting methods of using INSERT. Because id is an auto-incrementing integer, you don’t have to put it in your values list. However, if there’s a value you specifically don’t want to list (such as id), you then must list the remaining columns in use. For example, the following statement does not list the columns and also does not give a value for id, and it will produce an error:

mysql> insert into grocery_inventory values
-> (’Bottled Water (6-pack)’, ‘500ml spring water.’, 2.29, 250);
ERROR 1136: Column count doesn’t match value count at row 1

Because you didn’t list any columns, MySQL expects all of them to be in the value list, causing an error on the previous statement. If the goal was to let MySQL do the work for you by auto-incrementing the id field, you could use either of these statements:

  1. A statement with all columns named except id:

    insert into grocery_inventory (item_name, item_desc, item_price, curr_qty)
    values ('Bottled Water (6-pack)', '500ml spring water.', '2.29', 250);

  2. A statement that uses all columns, but does not explicitly name them and indicates a NULL entry for id (so one is filled in for you):

    insert into grocery_inventory values
    ('NULL', 'Bottled Water (6-pack)', '500ml spring water.', 2.29, 250);

Go ahead and pick one to use so that your grocery_inventory table has three records in total. It makes no different to MySQL, but as with everything that is a preference, be consistent in your application development. Consistent structures will be easier for you to debug later because you’ll know what to expect.


Date and Time Data Types in MySql

Saturday, April 12th, 2008

MySQL has several data types available for storing dates and times, and these data types are flexible in their input. In other words, you can enter dates that are not really days, such as February 30—February has only 28 or 29 days, never 30. Also, you can store dates with missing information. If you know that someone was born sometime in November of 1980, you can use 1980-11-00, where “00″ would have been for the day, if you knew it.

The flexibility of MySQL’s date and time types also means that the responsibility for date checking falls on the application developer. MySQL checks only two elements for validity: that the month is between 0 and 12 and the day is between 0 and 31. MySQL does not automatically verify that the 30th day of the second month (February 30th) is a valid date.

The MySQL date and time data types are

  • DATE— A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.

  • DATETIME— A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.

  • TIMESTAMP— A timestamp between midnight, January 1, 1970 and sometime in 2037. You can define multiple lengths to the TIMESTAMP field, which directly correlates to what is stored in it. The default length for TIMESTAMP is 14, which stores YYYYMMDDHHMMSS. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000. Other definitions of TIMESTAMP are 12 (YYMMDDHHMMSS), 8 (YYYYMMDD), and 6 (YYMMDD).

  • TIME— Stores the time in HH:MM:SS format.

  • YEAR(M)— Stores a year in 2 digit or 4 digit format. If the length is specified as 2 (for example, YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default length is 4.

You will likely use DATETIME or DATE more often than any other date- or time-related data type.


Numeric Dataypes in Mysql

Monday, March 31st, 2008

TINYINT(M)

8-bit integer (1 byte, - 128 to +127)

SMALLINT(M)

16-bit integer (2 bytes, - 32,769 to +32,767)

MEDIUMINT

24-bit integer (3 bytes, - 8,388,608 to +8,388,607)

BIGINT(M)

64-bit integer (8 bytes, ±9.22 × 1018)

INT, INTEGER(M)

32-bit integer (4 bytes, - 2,147,483,648 to +2,147,483,647)

 

With the INT data type, both positive and negative numbers are generally allowed. With the attribute UNSIGNED, the range can be restricted to the positive integers. But note that then subtraction returns UNSIGNED integers, which can lead to deceptive and confusing results.

With TINYINT, numbers between -128 and +127 are allowed. With the attribute UNSIGNED, the range is 0 to 255. If one attempts to store a value above or below the given range, MySQL simply replaces the input with the largest or, respectively, smallest permissible value.

Optionally, in the definition of an integer field, the desired column width (number of digits) can be specified, such as, for example, INT(4). This parameter is called M (for maximum display size) in the literature. It assists MySQL as well as various user interfaces in presenting query results in a readable format.

Remark 

Note that with the INT data types, the M restricts neither the allowable range of numbers nor the possible number of digits. In spite of setting INT(4), for example, you can still store numbers greater than 9999. However, in certain rare cases (such as in complex queries for the evaluation of which MySQL constructs a temporary table), the numerical values in the temporary tables can be truncated, with incorrect results as a consequence.

AUTO_INCREMENT Integers

With the optional attribute AUTO_INCREMENT you can achieve for integers that MySQL automatically inserts a number that is 1 larger than the currently largest value in the column when a new record is created for the field in question. AUTO_INCREMENT is generally used in the definition of fields that are to serve as the primary key for a table.

The following rules hold for AUTO_INCREMENT:

  • This attribute is permitted only when one of the attributes NOT NULL, PRIMARY KEY,or UNIQUE is used as well.

  • It is not permitted for a table to possess more than one AUTO_INCREMENT column.

  • The automatic generation of an ID value functions only when in inserting a new data record with INSERT, a specific value or NULL is not specified. However, it is possible to generate a new data record with a specific ID value, provided that the value in question is not already in use.

  • If you want to find out the AUTO_INCREMENT value that a newly inserted data record has received, after executing the INSERT command (but within the same connection or transaction), execute the command SELECT LAST_INSERT_ID( ).

  • If the AUTO_INCREMENT counter reaches its maximal value, based on the selected integer format, it will not be increased further. No more insert operations are possible. With tables that experience many insert and delete commands, it can happen that the 32-bit INT range will become used up, even though there are many fewer than two billion records in the table. In such a case, use a BIGINT column

 

  • FLOAT(M,D)— A floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.

  • DOUBLE(M,D)— A double precision floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.

  • DECIMAL(M,D)— An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL.

  • Of all the MySQL numeric data types, you will likely use INT most often. You can run into problems if you define your fields to be smaller than you actually need; for example, if you define an id field as an unsigned TINYINT, you won’t be able to successfully insert that 256th record if ID is a primary key (and thus required).