Select Statements

Description

In order to retrieve data from a database using SQL, you must create a SELECT statement, which may retrieve zero, one, or many rows, depending on how you format it. The rows are returned in a collection usually referred to as a result set. The SELECT statement, although there are some variations for advanced queries, is of the form:

SELECT <column> [, <column-list> ] FROM <table> WHERE <expression> = <expression>

Example 1 - Select All

This query will return a list of all order numbers and the respective customers from the order table. The query may return zero, one, or more orders.

SELECT OrderID, CustomerID from CustomerOrder

Example 2 - Select One

This query is being used to "look up" the customer for a specific order. We expect a single row to be returned, unless the order id is not a valid number, in which case we would retrieve zero rows.

SELECT CustomerID from CustomerOrder WHERE OrderID = 12345

Example 3 - Select By Range

This query will return a list of order numbers from the order table where the total order amount is more than 100000. The query may return zero, one, or more orders.

SELECT OrderID, CustomerID from CustomerOrder WHERE TotalAmount > 100000

Example 4 - Select Across Tables

This query is being used to list out the items that make up the order in the example above. You will notice that the items have a column called OrderID. as with all relational tables, this column represents the common information that links CustomerOrder and CustomerOrderItem together. Both tables have the same OrderID value for each order. The CustomerOrderItem table has a primary key that includes both the OrderID and the ItemID, making each row unique for those two values.

SELECT CustomerOrder.OrderID, CustomerOrder.CustomerID, CustomerOrderItem.ItemID,CustomerOrderItem.Description from CustomerOrder, CustomerOrderItem WHERE CustomerOrder.OrderID = 12345 AND CustomerOrder.OrderID = CustomerOrderItem.OrderID