User Guide
Chapter 3: Querying a Database 21
• Performs SQL commands that are enclosed within the block.
• Returns query variable values to the page.
CFQUERY tag syntax
<CFQUERY NAME="EmpList" DATASOURCE="CompanyInfo">
You’ll type SQL here
</CFQUERY>
In this example, the query code tells ColdFusion to:
• Use the
CompanyInfo data source to connect to the company.mdb database.
• Store the retrieved data in the query variable EmpList.
In general, you should follow these guidelines:
• The CFQUERY tag is a block tag, that is, it has an opening <CFQUERY> and
ending </CFQUERY> tag.
• Use the NAME attribute to name the query variable so that you can reference it
later on the page.
• Use the DATASOURCE attribute to name an existing data source that should be
used to connect to a specific database.
• Always surround attribute values with double quotes (").
• Place SQL statements inside the CFQUERY block to tell the database what to
process during the query.
• When referencing text literals in SQL, use single quotes (’). For example, Select
* from mytable WHERE FirstName=’Russ’
selects every record from mytable
in which the first name is Russ.
Note The data source must exist in order to perform a successful query.
Writing SQL
In between the begin and end CFQUERY tags, write the SQL that you want the
database to execute.
For example, to retrieve data from a database:
• Write a SELECT statement that lists the fields or columns that you want to
select for the query.
• Follow the SELECT statement with a FROM clause that specifies the database
tables that contain the columns.
Tip If you are using ColdFusion Studio, you can use the Query Builder to
build SQL statements by graphically selecting the tables, and records
within those tables you want to retrieve. See Using ColdFusion Studio for
details.