Even though the select clause is the first clause of a selectstatement, it is one of the last clauses to be evaluated by the database server. The reason for this is that before you can determine what to include in the final result set, you need to know all of the possible columns that could be included in the final result set. In order to fully understand the role of theselectclause, therefore, you will need to understand a bit about thefromclause. Here’s a query to get started:
mysql> SELECT * -> FROM department;
+---------+----------------+ | dept_id | name | +---------+----------------+ | 1 | Operations | | 2 | Loans | | 3 | Administration | +---------+----------------+ 3 rows in set (0.04 sec)
In this query, thefromclause lists a single table (department), and theselectclause indicates that all columns (designated by “*”) in thedepartmenttable should be included in the result set. This query could be described in English as follows:
Show me all the columns in thedepartment table.
In addition to specifying all of the columns via the asterisk character, you can explicitly name the columns you are interested in, such as:
mysql> SELECT dept_id, name -> FROM department;
+---------+----------------+ | dept_id | name | +---------+----------------+ | 1 | Operations | | 2 | Loans | | 3 | Administration | +---------+----------------+ 3 rows in set (0.01 sec)
The results are identical to the first query, since all of the columns in thedepartmenttable (dept_idandname) are named in theselect clause. You can choose to include only a subset of the columns in thedepartmenttable as well:
mysql> SELECT name -> FROM department;
+----------------+ | name | +----------------+ | Operations | | Loans | | Administration | +----------------+ 3 rows in set (0.00 sec)
The job of theselectclause, therefore, is the following:
Theselectclause determines which of all possible columns should be included in the query’s result set.
If you were limited to including only columns from the table or tables named in thefromclause, things would be rather dull. However, you can spice things up by including in yourselectclause such things as:
Literals, such as numbers or strings
Expressions, such astransaction.amount * -1
Built-in function calls, such asROUND(transaction.amount, 2)
The next query demonstrates the use of a table column, a literal, an expression, and a built-in function call in a single query against theemployeetable:
Expressions and built-in functions will be covered in detail later, but I wanted to give you a feel for what kinds of things can be included in theselectclause. If you only need to execute a built-in function or evaluate a simple expression, you can skip thefromclause entirely. Here’s an example: