Saturday, March 22, 2008

Get Data From MySQL

Retrieving the table data is easy, just use the SELECT statement like this

mysql> SELECT * FROM species;
+----+--------+
| id | name |
+----+--------+
| 1 | Cat |
| 2 | Bird |
| 3 | Fish |
| 4 | Turtle |
+----+--------+
4 rows in set (0.00 sec)

The * from the SELECT statement means select all columns. If you only want the names you can write

mysql> SELECT name FROM species;
+--------+
| name |
+--------+
| Cat |
| Bird |
| Fish |
| Turtle |
+--------+
4 rows in set (0.00 sec)

To select only the records that interest you, you can use WHERE statement followed by the definition. For example to select a record from species table where id equals 4 you can do this :

mysql> SELECT * FROM species WHERE id = 4;
+----+--------+
| id | name |
+----+--------+
| 4 | Turtle |
+----+--------+
1 row in set (0.59 sec)

If you want to order the returned rows by a criteria you can use ORDER BY like this :

mysql> SELECT * FROM species ORDER BY name;
+----+--------+
| id | name |
+----+--------+
| 2 | Bird |
| 1 | Cat |
| 3 | Fish |
| 4 | Turtle |
+----+--------+
4 rows in set (0.00 sec)

By default the result is sorted in ascending order. So this query will give the same result :

mysql> SELECT * FROM species ORDER BY name ASC;
+----+--------+
| id | name |
+----+--------+
| 2 | Bird |
| 1 | Cat |
| 3 | Fish |
| 4 | Turtle |
+----+--------+
4 rows in set (0.00 sec)

The ASC means ascending order. To get a descending order you just change the ASC with DESC like this :

mysql> SELECT * FROM species ORDER BY name DESC;
+----+--------+
| id | name |
+----+--------+
| 4 | Turtle |
| 3 | Fish |
| 1 | Cat |
| 2 | Bird |
+----+--------+
4 rows in set (0.00 sec)

No comments: