Difference between revisions of "Retrieving Data From a MySQL Database"
(→Retrieving a Single Column) |
|||
Line 23: | Line 23: | ||
4 rows in set (0.00 sec) | 4 rows in set (0.00 sec) | ||
</pre> | </pre> | ||
+ | |||
+ | == Using SELECT to Retrieve Mutiple Columns == | ||
+ | |||
+ | So far we have seen how easy it is to extract a single column from each row of a table. In the real world, it is more likely that information from more than one column will need to be retrieved. Fortunately the ''SELECT'' statement makes this task easy too. In fact, all that needs to be done is to specify the columns names after the SELECT statement, each separated by a comma. For example, to retrieve data from three columns in our database table: | ||
+ | |||
+ | <pre> | ||
+ | SELECT prod_code, prod_name, prod_desc FROM product; | ||
+ | </pre> | ||
+ | |||
+ | The above command will generate the following output if executed from within the [[The mysql Command-Line Tool|mysql]] tool: |
Revision as of 18:43, 9 October 2007
Just a database system would be useless without some way to write data to the database files, a database would be similarly useless if there were no way to extract the stored data. Amongst the available SQL statements, one of the most frequently used is the SELECT statement. The purpose of the SELECT statement is to retrieve data from a database table based on specified criteria. In this chapter we will cover the use of the SELECT statement in detail.
Retrieving a Single Column
The most basic of SELECT statements simply retrieves a single column of all the rows of a table. The following SQL statements select a database named extract all the product_description column entries in the product table:
USE MySampleDB; SELECT product_description FROM product;
Once executed, this command will display a list of every product description contained in the product table:
+-------------------+ | prod_desc | +-------------------+ | CD Writer | | Cordless Mouse | | SATA Disk Drive | | Ergonomic Keyboard| +-------------------+ 4 rows in set (0.00 sec)
Using SELECT to Retrieve Mutiple Columns
So far we have seen how easy it is to extract a single column from each row of a table. In the real world, it is more likely that information from more than one column will need to be retrieved. Fortunately the SELECT statement makes this task easy too. In fact, all that needs to be done is to specify the columns names after the SELECT statement, each separated by a comma. For example, to retrieve data from three columns in our database table:
SELECT prod_code, prod_name, prod_desc FROM product;
The above command will generate the following output if executed from within the mysql tool: