Chapter 3: Selecting
Chapter 3: Selecting
Note: The default FROM clause is actually FROM SYS.DUMMY. For exam-
ple, the statement SELECT * works, and returns a single row with a single
column called dummy_col, with a zero value, which is exactly what the built-in
read-only SYS.DUMMY table contains. That is why a SELECT with no FROM
clause always returns a single row, as it does in the example above.
The following example uses some of the arithmetic operators to perform com-
putations in the select list:
SELECT product.id,
product.unit_price * product.quantity AS stock_value,
product.unit_price
* ( SELECT SUM ( quantity )
FROM sales_order_items
WHERE sales_order_items.prod_id
= product.id ) AS sales_value,
( stock_value / sales_value ) * 100.00 AS percent
FROM product
ORDER BY sales_value DESC;
Heres how it works: For every row in the product table, the unit_price is multi-
plied by the quantity to determine stock_value, the total value of stock on hand.
Also, for each row in the product table, a subquery retrieves all the sales_order_
items rows where prod_id matches product.id and computes the sum of all
sales_order_items.quantity. This sum is multiplied by product.unit_price to
compute the sales_value, total sales value for that product. Finally, a percentage
calculation is performed on the results of the previous two calculations by refer-
ring to the alias names stock_value and sales_value. Here is what the result
looks like, sorted in descending order by sales_value, when run against the
ASADEMO database:
id stock_value sales_value percent
=== =========== =========== ========
600 936.00 73440.00 1.274510
700 1200.00 68040.00 1.763668
601 768.00 65376.00 1.174743
301 756.00 33432.00 2.261307
302 1050.00 30072.00 3.491620
400 1008.00 29502.00 3.416718
401 120.00 27010.00 .444280
300 252.00 21276.00 1.184433
500 252.00 18564.00 1.357466
501 196.00 17556.00 1.116427