Sunteți pe pagina 1din 17

Access 2010

Select Queries



Select Queries

Table of Contents
Introduction .................................................................................................................................................. 1
Retrieving Data from Tables ......................................................................................................................... 1
Query Design View .................................................................................................................................... 1
Query Results View ................................................................................................................................... 3
Add Criteria to a Query ............................................................................................................................. 5
Query Criteria ........................................................................................................................................ 5
Comparison Operators .......................................................................................................................... 6
Conditional Operators ........................................................................................................................... 6
Add a Calculated Field to a Query ............................................................................................................. 8
Operators .............................................................................................................................................. 8
Expressions ............................................................................................................................................ 8
Performing a Calculation on a Group of Records ................................................................................... 10
Creating Flexible Queries ............................................................................................................................ 12
Setting Top and Bottom Values .............................................................................................................. 12
Showing Records Containing Unique Values .......................................................................................... 12
Creating Parameter Queries ................................................................................................................... 14
The Like Operator and Wildcards ....................................................................................................... 14
The BetweenAnd Operator ............................................................................................................... 15
The Ampersand (&) ............................................................................................................................. 15
The Prompt Message .......................................................................................................................... 15

Select Queries
Revised - 25-Mar-13 Page 1
Select Queries
Introduction
When designing a database, first the data model is created and tables and relationships are defined in
Access. Next, test data is entered, the design is further refined and field properties are used to ensure
consistency when entering and updating data. Then, filters can be created and applied in each tables
datasheet view to display subsets of the information stored in that table. In this topic, we are now
ready to use select queries to retrieve data from one or more tables in order to answer questions about
the data.
Although there are many different types of queries that can be created and used in Access, this topic will
be covering select queries. We will begin by creating select queries to retrieve data from multiple
tables. We will then move on to summarizing data in queries. Finally, we will create new calculated,
query fields based upon data stored in the tables.
Retrieving Data from Tables
Filtering allows you to display all of the fields for selected data from a single table and to save the filter
with the table. However, you may need to display only certain fields for selected data from multiple
tables. Select queries allow you to retrieve relevant information from different tables at the same time.
You can also save query designs as named, reusable Access objects.
Query Design View
Tables can be very large; containing many fields and records. Select queries enable you to choose only
the fields that are relevant and retrieve only the records necessary for the task you are trying to
accomplish. In the Query Design view window, table field lists are displayed in the upper pane and the
selected fields and desired attributes are displayed in the query-by-example grid in the lower pane.

Select Queries
Revised - 25-Mar-13 Page 2
The Query Design window is opened by clicking the Query Design button found on the Create tab in the
Other group.

Once opened the Query Design window displays the Show Table dialog box. To add tables to the upper
pane of the query design window, select the desired table(s) and click Add. Tables can be added one-by-
one or all at once by holding the Ctrl key when selecting them. Once tables have been added, the Show
Table dialog box must be closed by clicking the Close button. The Query Tools Design contextual ribbon
tab displays indicating that a Select query is the default Query Type and that Table Names are displayed
by default in the query grid. Note: Once closed, the Show Table dialog box can be redisplayed by
clicking the Show Table button in the Query Setup group.

If relationships between the selected tables were previously defined in the relationships window a join
line connecting the tables will automatically display. If referential integrity was enforced when the
relationship was created, the join line will show the relationship type, i.e. One-to-Many or One-to One.
If no relationships between the tables were previously defined, a join line will not display automatically
and the tables will need to be joined by dragging a join line between the related fields.

Select Queries
Revised - 25-Mar-13 Page 3
Query Results View
Query results can be viewed by
clicking the View or Run button
located in the Results group on
the left side of the Query Tools
Design contextual tab.

Query results display in
datasheet view and the Query
Tools Design contextual tab
closes. To redisplay the query
design view, click the View
button on the left side of the
Home tab.
The query design can be saved
by clicking the Save button on
the Quick Access toolbar and
assigning a name to the query.

Note: Queries can be saved in
either the design view or the
results view but it is the design
of the query that is saved, not
the results it produces at that
time.

Once saved, the query is then available by
selecting it from the Queries group in the
Object Navigation bar.


Select Queries
Revised - 25-Mar-13 Page 4
Procedure Reference: Creating a Basic Select Query
1. In the desired table, on the Create tab, in the Queries group, click the Query Design button to
open the Query Design window and the Show Table dialog box.
2. In the show Table dialog box, select the table(s) and/or query(s) to be used for the query.
3. For each desired table, select it and click Add to add it to the Query Design view.
4. Once all tables have been added, close the Show Table dialog Box.
5. If necessary, click the Select button on the Design contextual tab to create a Select query.
6. In the query design window, add the required fields to the query design grid. Fields can be
added to the grid by:
Double-clicking the field name in the table.
Dragging and dropping the field name from the table to the query grid.
Clicking the drop-down arrow in the table row of the query grid and selecting the
desired table name from the list. Then, by clicking the drop-down arrow in the field
row of the query grid and selecting the field name from the list.
7. Save the query.
Click the Save button on the Quick Access toolbar.
8. Assign a meaningful name for the query and then click OK.
9. View the query results.
Click the View or Run button from the Results group, on left side of the Query Tools
Design tab.
Or, in the Object Navigation Pane, double-click the query to run it.

Select Queries
Revised - 25-Mar-13 Page 5
Add Criteria to a Query
In addition to selecting certain fields to be displayed, queries can also be used to select a subset of data
in a single table or across multiple tables that satisfy specific criteria and can be sorted in different ways.
Query Criteria
Query Criteria are the search conditions used in a query to retrieve or manipulate specific information.
Multiple criteria as well as sort selections can be included in a query. The query criteria are used to
compare the information in the fields to specific values and retrieve the records that meet the
condition(s). The order of the information retrieved can be changed using the Sort features in the query
grid. Sort selections are: ascending, descending and not sorted. Sort precedence is from left to right
within the query grid. Display of one or more fields in the results can be controlled by using the Show
checkbox for the field(s). Selected fields are displayed by default (checked). Display can be suppressed
by removing the check from the Show checkbox.

Note: It is recommended that the results be reviewed, using the View button, each time criteria is
added or changed in the query design. This will determine if the desired results are being displayed at
each step in the data retrieval process. If the results at any step are not what were expected, then the
previous criteria entered or changed is likely the reason and can be adjusted accordingly. This can save
valuable time in determining what went wrong, where and when in the event that a querys results
are not what were expected.

Select Queries
Revised - 25-Mar-13 Page 6
Comparison Operators
Comparison Operators are symbols used to compare two values. Comparison operators, when set in
criteria, establish results after comparing two or more values. The output of a comparison is either true
or false.


Operator Value Example
= Equals =NJ
< Less Than <12/31/2011
<= Less Than or Equal To <=10
> Greater Than >5
>= Greater Than or Equal To >=1/1/2011
<> Not Equal To <>NY
BetweenAnd Within a Range Between 100 And 500
Is Null Null Values Is Null

Conditional Operators
Conditional Operators are operators that test for the truth of a condition. Conditional operators, as with
comparison operators, return a value of either true or false. Parentheses can be used to change the
order of evaluation, and the operators within parentheses are evaluated first. Conditional operators are
also commonly referred to as logical operators.


Operator Description Example
AND True if both conditions are true. >5 AND <100
OR True if either condition is true. <5 OR >500
NOT True if the single instance is not true NOT Between 100 And 200

Criterion
Comparison
Operator Value
Criterion
Conditional
Operator
Select Queries
Revised - 25-Mar-13 Page 7
Additional Information regarding Query Criteria
The Access query grid provides multiple rows in which you can specify the records that need to be
retrieved in the result set. For example, if you wanted to select all of the records where a Price field is
greater than $100, you would type >100 in the criteria row below the Price field in the query grid. Using
ANDs and Ors allows you to expand or narrow the search. If you wanted to select all of the records
where the Price field is greater than $100 AND where the location of the sale is the State of California,
you would add the word California to the criteria row below the State field. When both criteria are
placed on the same line, an AND condition is automatically created. An AND condition narrows the
search because the records that are selected must meet all of the criteria in order to be retrieved.
Putting criteria on a different line creates an OR condition, which expands the search. Using the
previous example, if the word California below the State field was moved down one row to the OR
row of the query grid, the query would retrieve all records where the Price field is greater than $100
(from any state) as well as all records where the State field is equal to California (regardless of the price).
AND and OR conditions may also be typed directly into the same cell in the query grid. For example, you
could type California OR Michigan in a State fields criteria row to return all records from either
state. Typing California AND Michigan in the State fields criteria row would not return any records
because the value in the State field, for a single record, cannot be equal to both California and Michigan
at the same time.
Field display, as well as sort precedence, in the results view can be controlled by adding criteria to a field
in the query grid and not showing it in the results view or by adding a field to the query grid a second
time, for sorting purposes, but not showing it in the results view.
Procedure Reference: Add Criteria to a Query
1. Create a new Select Query or open the desired Select Query in Design view.
2. In the query grid include the field or fields for which you wish to set criteria.
3. Set the criteria.
To create an AND or OR condition on a single field, include the appropriate word in the
Criteria row for that field.
To create an AND condition on more than one field, enter the additional criteria in the
Criteria row for the additional field(s).
To create an OR condition on more than one field, enter the additional criteria in the OR
row for the additional field(s).

Select Queries
Revised - 25-Mar-13 Page 8
Add a Calculated Field to a Query
A Calculated Field is a new field, created in a query, which derives its values from calculations performed
on the contents of other fields. Unlike the fields found in tables, a calculated fields data is not entered
by users. It is generated by an arithmetic or text expression and its value is based upon the values used
in the expression. When designing databases, calculated values are never stored in tables because there
is no easy way to ensure that the calculated values are current. Calculated values are computed
dynamically, based upon the most current data, each time a query containing a calculation is viewed or
run.
Operators
An Operator is a sign or symbol that specifies the type of calculation to perform within an expression.
Arithmetic Operators are used to perform mathematical calculations. They add (+), subtract (-), multiply
(*) or divide (/) values. Exponents are calculated using the carat symbol (^) and parentheses can be
used to control the order of the calculations. In addition, Text Operators for concatenating text (& and
+) can be used to combine two fields, i.e. FullName: [FirstName]& &[LastName].
Expressions
Expressions are combinations of functions, field names, numbers, text and operators that perform
calculations to produce results. Arithmetic expressions can contain table data, referred to by field
names, as well as operators, functions and numbers. In expressions, field names must be enclosed
within square brackets, i.e. [fieldname]. Text is used to assign a meaningful name to the newly created
calculated field.


The Expression Builder
The Expression Builder is a tool that can help the user select
database objects and then, using the applications built-in
operations and functions, build formulas and calculations that
are used within queries, forms and reports. To display the
Expression Builder dialog box, right-click on the cell in the grid
and choose Build from the short-cut menu.
Arithmetic Operator
Arithmetic Expression
Newly Created Field Name
Existing Field Name
Select Queries
Revised - 25-Mar-13 Page 9
The Zoom Dialog Box
The Zoom dialog box enables the user to type and view the
entire expression. It can be used when an expression is too
long to be displayed completely within the cell of the query
grid. To display the Zoom dialog box, right-click on the cell in
the grid and choose Zoom from the short-cut menu.
The Property Sheet Pane
The Property Sheet pane is where properties can be set for Access objects. Properties that affect
structure, appearance and behavior can be specified in an objects property sheet.
The Field List Properties sheet contains items that affect the tables in the
query and can be opened by right-clicking on the table name and
selecting Properties from the short-cut menu.

The Field Properties sheet contains items that affect the fields in the
query grid and can be opened by right-clicking on the desired field, in
the query grid, and selecting Properties from the short-cut menu.

The Property Sheet pane can also be opened by selecting the appropriate object and clicking the
Property Sheet button
on the right side of the
Query Tools Design
contextual tab.

Procedure Reference: Add a Calculated Field to a Query
1. Open the desired query and switch to Design view or create a new query in Design view.
2. Ensure that the necessary tables and relationships appear in the Design view upper pane.
3. In the query design grid, click in the first available blank column and enter the name to be
assigned to the calculated field, followed by a colon, i.e., NewField:
4. Following the colon enter the arithmetic expression for the calculation.
Type the expression directly into the query grid.
Or, type the expression into the query grid using the Zoom window.
Or, create the expression using the Expression Builder.
5. Set the desired properties for the field such as: description, format, decimal places, etc.
6. Save the query.
7. View (or Run) the query to confirm that the expression is calculating properly and is displayed as
desired.
Select Queries
Revised - 25-Mar-13 Page 10
Performing a Calculation on a Group of Records
Weve seen how queries can be used to perform calculations on single records. Next we will examine
how to group records and then perform calculations on the group.
Group By Functions
A Group By Function performs a calculation on a group of values. These functions can be used with any
number of values and will result in a single value for the group. Aggregate functions are used when
grouping records in databases. In Access, Group By functions are selected from the Totals row in the
query design grid. The Totals row can be displayed by clicking the Totals button, in the Show/Hide
group, on the Design contextual tab.
When first displayed, every column in the query grid contains the
text Group By in the Total row. Aggregate functions are
selected from the Group By drop-down lists. The most commonly
used aggregate functions are: Sum, Avg (Average), Count, Max
(the maximum value) and Min (the minimum value).
Note: To ensure that aggregate functions
calculate the proper values, remove fields
from the query grid which would prevent
the records from grouping properly.
Fields with unique values (AssetTag in the
above illustration) will prevent records
from grouping at all. Fields with values
that are mostly unique (FirstName and
LastName in the above illustration) may
also not be desirable for grouping.
Columns can be deleted from the query grid by selecting them and clicking the Delete Columns button
found in the Query Setup group on the Design contextual tab.
Select Queries
Revised - 25-Mar-13 Page 11

Procedure Reference: Performing Calculations on a Group of Records
1. Open the desired query and switch to Design view or create a new query in Design view.
2. Click the Totals button in the Show/Hide group, on the Design contextual tab.
3. Add the fields to the design grid on which you wish to group the records.
4. Add the fields to the design grid that you wish to calculate using aggregate function(s).
5. For each field, from the Group By drop-down list, select Group By or the desired aggregate
function.
6. If desired, enter selection criteria in the Criteria row(s). Note: If selection criteria must be
entered for a field which is not to be grouped, include that field in the design grid and from the
Group By drop-down list, select Where.
7. If desired, select sort order(s) from the Sort row.
8. Save the query, assigning a name if necessary.
9. View or run the query to display the results.
Note: When grouping records and using aggregate functions, newly created calculated fields cannot be
used in other calculations within the same query. To resolve the error message either re-create the
additional calculated field(s) without the newly created field or create a new query based upon the
previous query to perform the grouping and aggregate functions.


Select Queries
Revised - 25-Mar-13 Page 12
Creating Flexible Queries
Weve seen that creating and using queries allows for quick access to all kinds of information in a
database. Surprisingly, select queries can be even more flexible in their functionality. You can use
them to display specific subsets of data by showing Top, Bottom or Unique values. Also, using
Parameter prompts, you can be prompted to enter different criteria each time the query is run, rather
than entering specific criteria in the query grid.
Setting Top and Bottom Values
Displaying the top or bottom values in a query results list involves two steps. First the query results
must be sorted, either ascending (for top values) or descending (for bottom values), on the desired field.
Then, the number or percent of the top or bottom values must be set using the Return option in the
Query Setup group of the Query Tools Design contextual tab or the Top Values property on the Query
Properties sheet. Note: Entry is not restricted to the items listed. Numeric or percentage values may
be typed into the Return combo box or the Top Values property.
Showing Records Containing Unique Values
The Query Properties sheet contains other items, in addition to the Top
Values property, that affect the entire query. The Unique Values property
can be used to restrict the records returned to those that have unique field
values in the query design grid. Similarly, the Unique Records property can
be used to restrict the records returned to those that have unique values in
all fields in the underlying tables or queries.
The Query Properties sheet can be opened by right-clicking a blank area of
the upper pane of the query design window and selecting Properties from
the short-cut menu or by clicking the Property Sheet button in the
Show/Hide group of the Design contextual tab.
Select Queries
Revised - 25-Mar-13 Page 13
Procedure Reference: Setting Top or Bottom Values
1. Open the query in design view.
2. For the desired field in the Design grid, in the Sort cell, select either Ascending or Descending.
3. View or run the query to observe the results.
4. Return to Query Design view.
5. Set the numeric or percentage value for the subset of records desired.
On the Design contextual tab, in the Query Setup Group, provide a value for the Return
property box by selecting or typing a number or percent value.
Or, in the Query Properties pane provide a value for the Top Values property field by
selecting or typing a number or percent value.
6. View or run the query to observe the results.
Procedure Reference: Showing Records Containing Unique Values
1. Open the query in design view.
2. Display the Query Properties Sheet pane.
Right-click in a blank area in the top of the query design and select Properties.
Or, Click the Property Sheet button in the Show/Hide group on the Query Tools Design
contextual tab.
3. Set the Unique Values property to Yes or set the Unique Records property to Yes.
4. View or run the query and observe the results.

Select Queries
Revised - 25-Mar-13 Page 14
Creating Parameter Queries
A Parameter Query is a flexible query that prompts the user for additional criteria. Instead of the actual
criteria, a message or command is placed in the criteria row beneath the applicable field. The message
must be enclosed in square brackets ([ ]). When the query is run, this text appears as a prompt, awaiting
input from the user. A parameter query can prompt for more than one criterion, with a separate dialog
box displayed for each.







The Like Operator and Wildcards
A wildcard is a special character used to include or exclude a single character or a group of characters in
a search. A wildcard is a symbol that enables you to substitute a different character in order to provide
criteria for pattern matching. Wildcards can be used in the criteria of a query as well as in a parameter
prompt. You can use the Like operator with one or more wildcards to display query results that match
specific values in a field that follows the pattern set by the wildcards. You can also use wildcards in
response to parameter prompts.
Common Wildcards
Character Description Example
* Matches any number of characters but can only
appear at the beginning or the end of the
string.
Like S* would match Stone, Smith
and Sullivan. Like *s would match
Lakes and Snakes.
? Matches any single alphabetical character and
can appear in the middle of a string.
Like B?nd would match Band, Bind
and Bend, among others.
[ ] Matches any single character provided within
the brackets.
Like B[ai]nd would match Band and
Bind, but not Bend or Bond.
[! ] Matches any character not provided within the
brackets.
Like B[!a]nd would match Bend,
Bind and Bond, but not Band.
[ - ] Matches any single character from within the
range provided in the brackets
Like B[a-d]nd would match Band,
Bbnd, Bcnd, and Bdnd only.
# Matches any single numeric character and can
appear in the middle of a number.
Like 9#7 would match 901, 917,
927, etc.


Brackets
Text appears as a prompt
Dialog Box
Select Queries
Revised - 25-Mar-13 Page 15
The BetweenAnd Operator
Another valid operator in a parameter query is the BetweenAnd operator. To check for a range of
values in a single cell, use the BetweenAnd operator with the bracketed prompts. For example, typing
Between [Please enter the start date:] And [Please enter the end date:] into the criteria row of a date
field would locate records that have date values that are between the start and end dates provided by
the user in response to the prompts.
The Ampersand (&)
The ampersand is a concatenation operator that is used to join two character strings end to end. It is
usually accomplished by putting the ampersand character between the strings. It can be used along with
the asterisk (*) wildcard to link more data to criteria specified by the user as part of a parameter query.
The Prompt Message
When you specify a prompt message in a parameter query, it should be brief but meaningful. Access
can display up to 50 characters in the prompt message. Periods, exclamation marks and square
brackets are not allowed within the outer square brackets. Also, the message cannot be the same as the
field name but can include the field name.
Note: Shift+F9 can be used to re-run a query.








Procedure Reference: Create and Run a Parameter Query
1. Open a query in design view or create a new query.
2. Click in the Criteria cell for the appropriate field and type the prompt message within square
brackets ([ ]).
3. If necessary, enter Like, the concatenation operator & and the desired wildcards within the
criteria.
4. View or run the query.
5. In the Enter Parameter Value dialog box, type appropriate data in response to the prompt.
6. Click OK.
7. Query results will display the records which match the data entered.
Wildcard
Concatenation Operator
Like Operator

S-ar putea să vă placă și