Wednesday, January 9, 2013

SELECT Statement


The SQL SELECT statement allows you to retrieve records from one or more tables in your SQL database.
The syntax for the SQL SELECT statement is:
SELECT columns
FROM tables
WHERE predicates;

SQL SELECT Statement - Select all fields from one table example

Let's take a look at how to use the SQL SELECT statement to select all fields from a table.
SELECT *
FROM suppliers
WHERE city = 'Newark';
In this SQL SELECT statement, we've used * to signify that we wish to view all fields from the suppliers table where the supplier resides in Newark.

SQL SELECT Statement - Selecting individual fields from one table example

You can also use the SQL SELECT statement to select individual fields from the table, as opposed to all fields from the table.
For example:
SELECT name, city, state
FROM suppliers
WHERE supplier_id > 1000;
This SQL SELECT statement would return only the name, city, and state fields from the suppliers table where the supplier_id value is greater than 1000.

SQL SELECT Statement - Select fields from multiple tables example

You can also use the SQL SELECT statement to retrieve fields from multiple tables.
SELECT orders.order_id, suppliers.name
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;
This SQL SELECT statement joins two tables together to gives us a result set that displays the order_id and supplier name fields where the supplier_id value existed in both the suppliers and orders table.