Getting Data from a Database

only for RuBoard

The SELECT statement is the most commonly used statement when you're using SQL. This is what enables you to retrieve data from a relational database. Listing 4.2 illustrates the basic structure of the SELECT statement.

Listing 4.2 The Basic Structure of a SELECT Statement
 SELECT select_list [ INTO new_table ] FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC  DESC ] ] 

In its simplest form, a SELECT statement begins with the word SELECT . SELECT is followed by one or more fields from the database table, each field separated by a comma. Then there's the FROM clause, which specifies the source of the data being queried. It ends with a table name , your source. After the WHERE clause you'll notice a couple of other expressions: GROUP BY , HAVING , and ORDER BY . These are covered later in the chapter and deal with sorting and filtering your result set (the rows returned from the query).

The following is a simple real-world example using a SELECT statement against the Northwind database:

 1: SELECT ProductName 2: FROM Products 

Figure 4.1 illustrates the results of the query.

Figure 4.1. A Web page displaying the results of the query.
graphics/04fig01.gif

When the SQL Statement in the proceeding example is executed, all rows in the ProductName field found in the Products table will be returned in the result set. In this query, the data will be returned exactly as it appears in the database, meaning that it's basically a snapshot of that column in the database.

If retrieving all the records from a table is what you need to do, you can bypass the need to comma delimitate all the field names by using an asterisk ( * ) after the SELECT statement and before the FROM clause, as shown in the following code:

 1: SELECT * 2: FROM Products 

Note

Be careful, though, because running this query will return all the data in the table. This could be a hefty load on your server, depending on how big your database is.


It's said to be good form to use the table name before any fields in the table when you're doing queries as the following code demonstrates . You want to do this in case you're returning data from more than one table and for ease of readability:

 1: Select Products.* 2: FROM Products 

The SELECT statement can be simple, as in this example, or it can be very complicated, spanning many lines. You can use the SELECT statement to return one million rows out of a database, or narrow it down to one record out of a million by giving the statement a set of criteria on which to search.

only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net