The Five Clauses of the SELECT statement
- SELECT – the columns in the result set
- FROM – names the base table(s) from which results will be retrieved
- WHERE – specifies any conditions for the results set (filter)
- ORDER BY – sets how the result set will be ordered
- LIMIT – sets the number of rows to be returned
The clauses MUST appear in the order shown above.
1 USE world;
2 SELECT name
3 FROM city
4 WHERE CountryCode = “AFG”
5 ORDER BY name
6 LIMIT 3
Let us break the statement line by line:
- The USE clause sets the database that we will be querying. You typically have more than one database on your database server. You have to specify which database you are working in.
- The semicolon “;” indicates the end of a statement. You can execute multiple statements in sequence by defining each statement with a semicolon
- The SELECT clause defines the columns and column order that you want to retrieve in your results set. If you want to retrieve all of the columns from the base table you can simply use SELECT *
- You separate each column name with a comma “,” ex., SELECT name, CountryCode
- There is no trailing comma at the end of a column list
- The FROM clause specifies the table that the results will be coming from
- You can specify multiple tables by using a JOIN clause, but we will address that topic at a future time
ORDER BY name
- The ORDER BY clause is not required but when used it defines the sort order of the results
- By default, the sort order is ascending. This is implicit However, you can use explicit syntax of ASC. If you want the sort, order to be descending you can use the keyword DESC.
- You can specify more than one column in an Order By statement separated by commas. The sort order DESC, ASC applies to each column individually. Below IS some examples
- ORDER BY population ASC, name DESC
- ORDER BY population, name (ASC is always implied if not explicitly stated)
- If you only want to return a specified number of rows from the result set, you can use the LIMIT clause. This can be helpful when you want to test a query for accuracy that could potentially bring back a very large number of rows.
- The semicolon; defines the end of the statement.
Table 1. Column Specifications
Base Table Value
Show all columns
Base Table Value
Comma-separated list of column names