Java Reference
In-Depth Information
Chapter 7: Retrieving Data withSQL Queries
In This Chapter
One of the most important functions of any database application is finding the records in the database
tables and returning them in the desired form. The process of finding and returning formatted records
is known as querying the database. This chapter will explore the use of the SQL SELECT command to
query the database created and populated in Chapters 5 and 6 .
The SELECT Statement
The SELECT statement is the heart of a SQL query. In addition to its use in returning data in a query, it
can be used in combination with other SQL commands to select data for a variety of other operations,
such as modifying specific records using the UPDATE command.
The most common use of SELECT , however, is as the basis of data-retrieval commands, or queries, to
the database. A simple query specifies the names of the columns to be returned and the name of the
table they can be found in. A basic SELECT command looks like this:
SELECT columnName1, columnName2,.. FROM tableName;
The SQL command for selecting the First Name and Last Name of each entry in the Contact_Info table
would be as follows:
SELECT First_Name, Last_Name FROM Contact_Info;
In addition to this specific form, where the names of all the fields you want returned are specified in the
query, SQL also supports the following wild-card form:
SELECT * FROM tableName;
The wild card, * , tells the database-management system to return the values for all columns.
Using the WHERE Clause
The real power of the SELECT command comes from the WHERE clause, which allows you to query the
database for specific data. You will have noticed that each of the commands shown above returns
values for all rows. A practical query needs to be more restrictive, returning the requested fields from
only those records that match specific criteria. For example, the WHERE clause enables you to retrieve
all records with a Last_Name Corleone from the Contact_Info table shown in Table 7-1 .
Table 7-1: The CONTACT_INFO Table
FIRST_NAME
MI
LAST_NAME
STREET
CITY
STATE
ZIP
Michael
A
Corleone
123 Pine
New York
NY
10006
Fredo
X
Corleone
17 Main
New York
NY
10007
Sonny
A
Corleone
123 Walnut
Newark
NJ
12346
 
Search WWH ::




Custom Search