Select specific columns
The previous section shows how to select and order all data from a table. However, often all you want to see is the data in one or more specific columns. Again, the formula is to use the Projection and FROM clauses, specify the columns and table, and perhaps order the data in ascending or descending order with an ORDER BY clause.
If
you want to find all the customer numbers in the orders table,
use a statement such as the one in the following query.
The result shows how the statement simply selects all
data in the customer_num column in the orders table
and lists the customer numbers on all the orders, including duplicates.
The output includes several duplicates because some customers have placed more than one order. Sometimes you want to see duplicate rows in a projection. At other times, you want to see only the distinct values, not how often each value appears.
To suppress duplicate rows, you can include the keyword
DISTINCT or its synonym UNIQUE at the start of the select list, once
in each level of a query, as the following query shows.
To produce a more readable list, Query limits the display to show
each customer number in the orders table only once, as the
result shows.
Suppose you are handling a customer call, and you want
to locate purchase order number DM354331. To list all the purchase
order numbers in the orders table, use a statement such as
the following query shows.
The result shows how the statement retrieves data in
the po_num column in the orders table.
However, the list is not in a useful order. You can add
an ORDER BY clause to sort the column data in ascending order and
make it easier to find that particular po_num, as shown in
the following query.
To select multiple columns from a table, list them in
the projection list in the Projection clause. The following query
shows that the order in which the columns are selected is the order
in which they are retrieved, from left to right.
As Sorting on multiple columns shows,
you can use the ORDER BY clause to sort the data in ascending or descending
order and perform nested sorts. The result shows ascending order.
When you use SELECT and ORDER BY on several columns in
a table, you might find it helpful to use integers to refer to the
position of the columns in the ORDER BY clause. When an integer is
an element in the ORDER BY list, the database server treats it as
the position in the projection list. For example, using 3 in the ORDER
BY list (ORDER BY 3) refers to the third item in the projection list.
The statements in the following query retrieve and display the same
data, as Query
result shows.
You can include the DESC keyword in the ORDER BY clause
when you assign integers to column names, as the following query shows.
In this case, data is first sorted in descending order by order_date and in ascending order by customer_num.