SELECT
The SELECT statement is used to
retrieve data from a database, and is probably the statement you will use
most.
Minimum requirements
The simplest of SELECT
statement consists of a minimum of two parts (called clauses):
SELECT field1,
field2...
FROM table1,
table2...
The SELECT clause determines
what you want to retrieve, and the FROM clause determines where you want to
retrieve it from. The following example demonstrates these clauses in use:
Example:
SELECT Name,
Address, PhoneNumber
FROM tblAddressBook
At the moment only the Name,
Address and PhoneNumber fields will be retrieved from the Address Book
table. There may be other fields such as Age, PostCode, EmailAddress,
MobileNumber that we are interested in. If we wish to retrieve all fields
for this table we can use the asterisk (*) wildcard character in place of
the list of field names. The above example becomes:
Example:
SELECT *
FROM tblAddressBook
Filtering data
Up to now we have been
retrieving all of the records from the Address Book table. Normally we would
only want a subset of these records, for example we may be interested in
just those records where the person's age is greater than 25. The WHERE
clause is used to achieve this and looks as follows:
WHERE condition1, condition2...
The example now becomes:
Example:
SELECT
*
FROM tblAddressBook
WHERE Age andgt; 25
Sorting data
Finally, the order the data is
retrieved in is important. With a list of names, it would be nice if we
could view them in alphabetical order. This is where the ORDER BY clause can
be used:
ORDER BY field1[ASC|DESC],
field2[ASC|DESC]...
The ASC|DESC part of the clause
is optional and is used for returning the sorted data in either ascending or
descending order respectively. By default the sort order is ascending. Our
completed example is as follows:
Example:
SELECT *
FROM tblAddressBook
WHERE Age andgt; 25
ORDER BY Name ASC |