Querying a Table
Querying a Table
To retrieve data from a table, the table is queried. An SQL SELECT
statement is used to do this. The statement is divided into a select list (the part that lists the columns to be returned), a table list (the part that lists the tables from which to retrieve the data), and an optional qualification (the part that specifies any restrictions). For example, to retrieve all the rows of table weather
, type:
Here *
is a shorthand for “all columns”. [1] So the same result would be had with:
The output should be:
You can write expressions, not just simple column references, in the select list. For example, you can do:
This should give:
Notice how the AS
clause is used to relabel the output column. (The AS
clause is optional.)
A query can be “qualified” by adding a WHERE
clause that specifies which rows are wanted. The WHERE
clause contains a Boolean (truth value) expression, and only rows for which the Boolean expression is true are returned. The usual Boolean operators (AND
, OR
, and NOT
) are allowed in the qualification. For example, the following retrieves the weather of San Francisco on rainy days:
Result:
You can request that the results of a query be returned in sorted order:
In this example, the sort order isn't fully specified, and so you might get the San Francisco rows in either order. But you'd always get the results shown above if you do:
You can request that duplicate rows be removed from the result of a query:
Here again, the result row ordering might vary. You can ensure consistent results by using DISTINCT
and ORDER BY
together: [2]
[1] While SELECT *
is useful for off-the-cuff queries, it is widely considered bad style in production code, since adding a column to the table would change the results.
[2] In some database systems, including older versions of Tacnode, the implementation of DISTINCT
automatically orders the rows and so ORDER BY
is unnecessary. But this is not required by the SQL standard, and current Tacnode does not guarantee that DISTINCT
causes the rows to be ordered.