IN THIS CHAPTER
In the preceding chapter, you created queries using selected fields from one or more tables. You also sorted the data and set criteria to limit the results of a query. This chapter focuses on using operators and expressions to calculate information, compare values, and display data in a different format—using queries to build examples.
This chapter uses queries to demonstrate the use of operators and functions, but the principles in this chapter's exercises apply anywhere operators and expressions appear in Access.
Operators let you compare values, put text strings together, format data, and perform a wide variety of tasks. You use operators to instruct Access to perform a specific action against one or more operands. The combination of operators and operands is known as an expression.
You'll use operators every time you create an equation in Access. For example, operators specify data validation rules in table properties, create calculated fields in forms and reports, and specify criteria in queries.
Operators can be grouped into the following types:
Mathematical operators are also known as arithmetic operators, because they're used for performing numeric calculations. By definition, you use mathematical operators to work with numbers as operands. When you work with mathematical operators, numbers can be any numeric data type. The number can be a constant value, the value of a variable, or a field's contents. You use these numbers individually or combine them to create complex expressions.
There are seven basic mathematical operators:
+ |
Addition |
– |
Subtraction |
* | Multiplication |
/ |
Division |
|
Integer division |
^ |
Exponentiation |
Mod |
Modulo |
If you want to create a calculated field in a query for adding the value of tax to the price, use an expression similar to the following:
[TaxAmt]+[Price]
The subtraction operator (–
) performs simple subtraction, such as calculating a final invoice amount by subtracting a discount from the price:
[Price] - ([Price] * [DiscountPercent])
A simple example of when to use the multiplication operator (*
) is to calculate the total price of several items. You could design a query to display the number of items purchased and the price for each item. Then you could add a calculated field containing the value of the number of items purchased times the price per item. In this case, the expression would be:
[Quantity] * [Price]
Use the division operator (/
) to divide two numbers. Suppose, for example, that a pool of 212 people win a $1,000,000 lottery. The expression to determine each individual's payoff of $4,716.98 is:
1000000 / 212
The integer division operator () takes any two numbers (number1 and number2), rounds them up or down to integers, divides the first by the second (number1 / number2), and then drops the decimal portion, leaving only the integer value. Here are some examples of how integer division differs from normal division:
Normal Division | Integer Conversion Division |
100 / 6 = 16.667 | 100 6 = 16 |
100.9 / 6.6 = 19.288 | 100.9 6.6 = 14 |
102 / 7 = 14.571 | 102 7 = 14 |
The exponentiation operator (^
) raises a number to the power of an exponent. Raising a number simply means multiplying a number by itself. For example, multiplying the value 4 x 4 x 4
(that is, 43) is the same as entering the formula 4^3
.
The exponent does not have to be a whole number; it can even be negative. For example, 2^2.1
returns 4.28709385014517
, and 4^–2
is 0.0629
.
The modulo operator (Mo
d
) takes any two numbers (number1 and number2), rounds them up or down to integers, divides the first by the second (number1 / number2), and then returns the remainder. Here are some examples of how modulo division compares to normal division:
Normal Division | Modulo Division | Explanation |
10 / 5 = 2 | 10 Mod 5 = 0 | 10 is evenly divided by 5 |
10 / 4 = 2.5 | 10 Mod 4 = 2 | 10 / 4 = 2 with a remainder of 2 |
22.24 / 4 = 9.56 | 22.24 Mod 4 = 2 | 22 / 4 = 5 with a remainder of 2 |
22.52 / 4 = 9.63 | 22.52 Mod 4 = 3 | 23 / 4 = 5 with a remainder of 3 |
The tricky thing about modulo division is that the returned value is the remainder after integer division is performed on the operands. The Mod
operator is often used to determine whether a number is even or odd by performing modulo division with 2 as the divisor:
5 Mod 2 = 1
4 Mod 2 = 0
If Mod
returns 1
, the dividend is odd. Mod
returns 0
when the dividend is even.
Comparison operators compare two values or expressions in an equation. There are six basic comparison operators:
= |
Equal |
<> |
Not equal |
< |
Less than |
<= |
Less than or equal to |
> |
Greater than |
>= |
Greater than or equal to |
The expressions built from comparison operators always return True
, False
, or Null
. Null
is returned when the expression can't be evaluated.
As you read the following descriptions, please keep in mind that Access is case insensitive in most situations. When comparing strings, for example, “CAR,” “Car,” and “car” are the same to Access.
If either side of an equation is a null value, the result is always Null
.
The equal operator (=
) returns True
if the two expressions are the same. For example,
[Category] = "Car" |
Returns True if Category is Car ; returns False for any other category. |
[SaleDate] = Date() |
Returns True if the date in SaleDate is today; returns False for any other date. |
The not-equal operator (<>
) is the opposite of the equal operator. For example,
[Category] <> "Car" |
Returns True if Category is anything but Car and False only when Category is Car . |
The less-than operator (<
) returns a logical True
if the left side of the equation is less than the right side, as in this example:
[Price] < 1000 |
Returns True if the Price field contains a value of less than 1,000; returns False whenever Price is greater than or equal to 1,000. |
Interestingly, the less-than operator is easily applied to string values (the same is true for most comparison operators). For example, the following expression is False
:
"Man" > "Woman"
Without getting philosophical about the expression, what actually happens is that Access does a character-by-character comparison of the strings. Because M appears before W in the alphabet, the word Man is not greater than Woman. The ability to compare strings can be of significant value when sorting string data or arranging names in a particular order.
Again, because Access string comparisons are not case sensitive, XYZ is not greater than xyz.
The less-than-or-equal-to operator (<=
) returns True
if the operand on the left side of the equation is either less than or equal to the right-side operand, as in this example:
[Price] <= 2500 |
Returns True if Price equals 2500 or is less than 2500 ; returns False for any Price that is more than 2500 . |
The greater-than operator (>
) is the opposite of less than. This operator returns True
when the left-side operand is greater than the operand on the right side. For example:
[TaxRate] > 3.5 |
Returns True if TaxRate is greater than 3.5 ; returns False whenever TaxRate is less than or equal to 3.5 |
The greater-than-or-equal-to operator (>=
) returns True
if the left side is greater than or equal to the right side. For example:
[TaxRate] >= 5 |
Returns True if TaxRate is 5 or greater; returns False when TaxRate is less than 5 |
Access has three string operators for working with strings. Unlike the mathematical and logical operators, the string operators are specifically designed to work with the string data type:
& |
Concatenates operands. |
Like |
Operands are similar. |
Not Like |
Operands are dissimilar. |
The concatenation operator joins two strings into a single string. In some ways, concatenation is similar to addition. Unlike addition, however, concatenation always returns a string:
[FirstName] & [LastName]
However, there is no space between the names in the returned string. If [FirstName]
is “Fred” and [LastName]
is “Smith,” the returned string is FredSmith
. If you want a space between the names, you must explicitly add a space between the strings, as follows:
[FirstName] & " " & [LastName]
The concatenation operator easily joins a string with a numeric- or date-type value. Using the &
operator eliminates the need for special functions to convert numbers or dates to strings.
Suppose, for example, that you have a number field (HouseNumber) and a text field (StreetName), and you want to combine both fields:
[HouseNumber] & " " & [StreetName]
If HouseNumber
is “1600” and StreetName
is “Pennsylvania Avenue N.W.,” the returned string is:
"1600 Pennsylvania Avenue N.W."
Maybe you want to print the OperatorName and current date at the bottom of a report page. This can be accomplished with the following:
"This report was printed " & Now() & " by " & [OperatorName]
Notice the spaces after the word printed and before and after the word by. If the date is March 21, 2012, and the time is 4:45 p.m., this expression looks like:
This report was printed 3/21/12 4:45:40 PM by Jim Rosengren
The addition operator (+
) also concatenates two character strings. For example, to combine FirstName and LastName from tblContacts to display them as a single string, the expression is:
[FirstName] + " " + [LastName]
Although &
and +
both serve as concatenation operators, using +
might exhibit unexpected results in some situations. The &
operator always returns a string when concatenating two values. The operands passed to &
may be strings, numeric or date/time values, field references, and so on, and a string is always returned.
Because it always returns a string, &
is often used to prevent Invalid use of null
errors when working with data that might be null. For example, let's assume a particular text box on an Access form may or may not contain a value because we can't be sure the user has entered anything in the text box. When assigning the contents of the text box to a variable (discussed in Chapter 24), some developers concatenate an empty string to the text box's contents as part of the assignment:
MyVariable = txtLastName & ""
&
ensures that, even if the text box contains a null value, the variable is assigned a string and no error is raised.
+
, on the other hand, returns a null value when one of the operands is null:
MyVariable = txtLastName + ""
In this case, if txtLastName is truly null, the user may encounter an Invalid use of null
error because the result of the concatenation is null (assuming, once again, that txtLastName contains a null value).
Most experienced Access developers reserve +
for arithmetical operations and always use &
for string concatenation.
The Like
operator and its opposite, the Not Like
operator, compare two string expressions. These operators determine whether one string matches, or doesn't match, the pattern of another string. The returned value is True
, False
, or Null
. The Like
and Not Like
operators are case insensitive.
The Like
operator uses the following syntax:
expression Like pattern
Like
looks for the expression in the pattern; if it's present, the operation returns True
. For example:
[FirstName] Like "John" |
Returns True if the first name is John. |
[LastName] Like "SMITH*" |
Returns True if the last name is Smith, Smithson, or any other name beginning with “Smith,” regardless of capitalization. |
[State] Not Like "NY" |
Returns True for any state other than New York. |
The Like
and Not Like
operators provides powerful and flexible tools for string comparisons. Wildcard characters extend the flexibility of the Like
operator.
Boolean operators (also referred to as logical operators) are used to create multiple conditions in expressions. Like comparison operators, these operators always return True
, False
, or Null
. Boolean operators include the following:
And |
Returns True when both Expression1 and Expression2 are true. |
Or |
Returns True when either Expression1 or Expression2 is true. |
Not |
Returns True when the Expression is not true. |
Xor |
Returns True when either Expression1 or Expression2 is true, but not both. |
Eqv |
Returns True when both Expression1 and Expression2 are true or both are false. |
Imp |
Performs bitwise comparisons of identically positioned bits in two numerical expressions. |
Use the And
operator to perform a logical conjunction of two expressions. The operator returns True
if both expressions are true. The general syntax of And
is as follows:
Expression1 And Expression2
For example:
[tblContacts].[ZipCode] = "02379" |
Returns True only if both expressions are true. |
The logical And
operator depends on how the two operands are evaluated by Access. Table 9.1 describes all the possible results when the operands are True
or False
. Notice that And
returns True
only when both operands are true.
Table 9.1 And Operator Results
Expression1 | Expression2 | Expression1 And Expression2 |
True |
True |
True |
True |
False |
False |
True |
Null |
Null |
False |
True |
False |
False |
False |
False |
False |
Null |
False |
Null |
True |
Null |
Null |
False |
False |
Null |
Null |
Null |
The Or
operator performs a logical disjunction of two expressions. Or
returns True
if either condition is true. The general syntax of Or
is as follows:
Expression1 Or Expression2
The following examples show how the Or
operator works:
[LastName] = "Casey" Or [LastName] = "Gleason" |
Returns True if LastName is either Casey or Gleason. |
[TaxLocation] = "TX" Or [TaxLocation] = "CT" |
Returns True if TaxLocation is either TX or CT. |
The Or
operator (like And
) returns True
or False
depending on how Access evaluates its operands. Table 9.2 shows all possible combinations with two operands. Notice that Or
returns False
only when both operands are false.
Table 9.2 Or Expression Results
Expression1 | Expression2 | Expression1 Or Expression2 |
True |
True |
True |
True |
False |
True |
True |
Null |
True |
False |
True |
True |
False |
False |
False |
False |
Null |
Null |
Null |
True |
True |
Null |
False |
Null |
Null |
Null |
Null |
The Not
operator negates a numeric or Boolean expression. The Not
operator returns True
if the expression is false, and False
if the expression is true. The general syntax of Not
is:
Not [numeric|boolean] expression
The following examples show how to use the Not
operator:
Not [Price] <= 100000 |
Returns True if Price is greater than 100,000. |
If Not (City = "Seattle") Then |
Returns True for any city that is not Seattle. |
If the operand is null, the Not
operator returns Null
. Table 9.3 shows all the possible values.
Table 9.3 Not Operator Results
Expression | Not Expression |
True |
False |
False |
True |
Null |
Null |
Access has three very useful miscellaneous operators:
Between…And |
Range |
In |
List comparison |
Is |
Reserved word |
Between…And
determines whether an expression's value falls within a range of values:
expression Between value1 And value2
If the value of the expression falls within value 1
and value 2
, or is the same as value 1
or value 2
, the result is True
; otherwise, it's False
. Note that the Between … And
operator is inclusive, the equivalent of >=
and <=
.
The following examples show how to use the Between…And
operator:
[TotalCost] Between 10000 And 19999 |
Returns True if the TotalCost is between 10,000 and 19,999, or equal to 10,000 or 19,999 |
[SaleDate] Between #1/1/2012# And #12/31/2012# |
Returns True when the SaleDate occurs within the year 2012. |
The Between…And
operator can also be used with the Not
operator to negate the logic:
Not [SaleDate] Between #1/1/2012# And #3/31/2012# |
Returns True only when SaleDate is not within the first quarter of 2012. |
The In
operator determines whether an expression's value is the same as any value within a list. The general syntax of In
is:
Expression In (value1, value2, value3, …)
If the expression's value is found within the list, the result is True
; otherwise, the result is False
.
The following example uses the In
operator as a query's criteria in the Category column:
In ('SUV','Trucks')
This query displays only those models that are SUVs or trucks.
The In
operator is also used in VBA code:
If [tblCustomers].[City] In("Seattle", "Tacoma") Then
In this case the body of the If…Then…Else
statement executes only if the City field is either Seattle or Tacoma.
The return value of the In
operator can be negated with Not
:
If strCity Not In ("Pittsburgh", "Philadelphia") Then
In this case, the body of the If…Then…Else
statement executes only if strCity is not set to either Pittsburgh or Philadelphia.
The Is
operator is generally used with the keyword Null
to determine whether the value of an object is null:
expression Is Null
In the VBA environment, the Is
operator can be used to compare various objects to determine if they represent the same entity.
The following example uses the Is
operator:
[LastName] Is Null |
Returns True if the LastName field is null; returns False if the LastName field contains any value. |
It is important to note that the Is
operator applies only to objects and object variables, such as fields in tables. The Is
operator can't be used with simple variables such as strings or numbers.
When you work with complex expressions that have many operators, Access must determine which operator to evaluate first, and then which is next, and so forth. Access has a built-in predetermined order for mathematical, logical, and Boolean operators, known as operator precedence. Access always follows this order unless you use parentheses to override its default behavior.
Operations within parentheses are performed before operations outside parentheses. Within parentheses, Access follows the default operator precedence.
Precedence is determined first according to category of the operator. The operator rank by order of precedence is:
Each category contains its own order of precedence, which we explain in the following sections.
Mathematical operators follow this order of precedence:
Comparison operators observe this order of precedence:
The Boolean operators follow this order of precedence:
One of the most common uses of operators and expressions is when building complex query criteria. A thorough understanding of how these constructs work can ease the process of building sophisticated, useful queries. This section deals specifically with building query criteria using operators and expressions. Some of the information in the remainder of this chapter parallels earlier discussions, but the context is specifically query design.
Knowing how to specify criteria is critical to designing and writing effective queries. Although queries can be used against a single table for a single criterion, many queries extract information from several tables using more complex criteria.
Because of this complexity, your queries are able to retrieve only the data you need, in the order that you need it. You might, for example, want to select and display data from the database to get the following information:
As your database system evolves, you'll want to retrieve subsets of information like these examples. Using operators and expressions, you create complex select queries to limit the number of records returned by the query. This section discusses select queries that use operators and expressions. Later, you'll apply this knowledge when working with forms, reports, and VBA code.
When working with select queries, you may need to specify one or more criteria to limit the scope of information shown. You specify criteria by using comparison operators in equations and calculations. The categories of operators are mathematical, relational, logical, and string. In select queries, operators are used in either the Field cell or the Criteria cell of the Query by Example (QBE) pane.
Table 9.4 shows the most common operators used with select queries.
Table 9.4 Common Operators Used in Select Queries
Mathematical | Relational | Logical | String | Miscellaneous |
* (multiply) |
= (equal) |
And |
& (concatenate) |
Between …And |
/ (divide) |
<> (not equal) |
Or |
Like |
In |
+ (add) |
> (greater than) |
Not |
Not Like |
Is Null |
– (subtract) |
< (less than) |
Is Not Null |
Using these operators, you can ferret out groups of records like these:
And
and Or
criteria, such as all records that are cars and are not either a truck or an SUVWhen you add criteria to a query, use the appropriate operator with an example of what you want. In Figure 9.1, the example is Cars
. The operator is equal (=
). Notice that the equal sign is not shown in the figure because it's the default operator for select queries.
You build complex query criteria using any combination of the operators shown in Table 9.4. For many queries, complex criteria consist of a series of And
s and Or
s, as in these examples:
These examples demonstrate the use of both logical operators: And
/Or
. Many times, you can create complex criteria by entering example data in different cells of the QBE pane, as shown in Figure 9.2. In Figure 9.2, criteria is specified in both the State and Category columns. Within the State column, the criteria specifies “either California or Arizona,” while the additional criteria in the Category column adds “not Cars.” When combined, the criteria in the two columns limit the returned records to those where the customer state is either California or Arizona, and the product category is not cars.
However, using explicit Boolean operators is not the only way to select records based on multiple criteria. Figure 9.3 demonstrates a common Access technique using complex criteria without entering the operator keywords And
/Or
at all. In this example, the criteria “stacked” within a single column specifies Or
. For example, in the State column, the criteria is interpreted as "CA" Or "AZ"
. The presence of criteria in another column in the QBE grid implies And
. Therefore, the criteria in the Category column is combined with the state criteria and is interpreted as:
(State = "CA" And Category <> "Cars") Or
(State = "AZ" And Category <> "Cars")
In any case, the queries in Figures 9.2 and 9.3 are equivalent and return the same data.
One confusing aspect about the query in Figure 9.3 is that the criteria in the Category column must appear twice, once for each value in the State column. If the Category criteria appeared only once, perhaps in the same row as "AZ"
in the State column, the combined criteria would be interpreted as:
(State = "AZ" and Category <> "Cars") Or (State = "CA")
You learn how to create this type of complex query in the “Entering Criteria in Multiple Fields” section, later in this chapter.
Access takes your graphical query and creates a single SQL SELECT
statement to actually extract the information from your tables. Click the drop-down in the Ribbon's View group and select SQL View to change the window's contents to display the SQL SELECT
statement (shown in Figure 9.4), which Access creates from the fields and criteria placed in the QBE pane in Figure 9.3.
The SQL statement in Figure 9.4 has been slightly rearranged by the author for clarification purposes. When you switch to SQL view in your database, you'll see one long multi-line statement with no breaks between sections.
An expression for this query's criteria is:
(tblCustomers.State = "CA" AND tblProducts.Category <> "Cars") OR
(tblCustomers.State = "AZ" AND tblProducts.Category <> "Cars")
You must enter the category criteria (<> "Cars"
) for each state in the QBE pane, as shown in Figure 9.3. In the “Entering Criteria in Multiple Fields” section later in this chapter, you learn to use the And/Or
operators in a Criteria cell of the query, which eliminates the redundant entry of these fields.
The And/Or
operators are the most common operators when working with complex criteria. The operators consider two different expressions (one on each side of the And/Or
operators) and then determine whether the expressions are true or false. Then the operators compare the results of the two expressions against each other for a logical true/false answer. For example, take the first And
statement in the expression given in the preceding paragraph:
(tblCustomers.State = "
CA"
AND tblProducts.Category <> "
Cars"
)
The right side of the criteria (tblProducts.Category <> "Cars"
) evaluates to True
if the Category is anything other than Cars. The And
operator compares the logical true/false from the left and right expressions to return a true/false answer.
When the result of an And/Or
operation is True
, the overall condition is true, and the query displays the records meeting the true condition.
Notice that the result of an And
operation is true only when both sides of the expression are true, whereas the result of an Or
operation is true when either side of the expression is true. In fact, one side can be a null value, and the result of the Or
operation will still be true if the other side is true. This is the fundamental difference between And/Or
operators.
When you work with queries, you might want to use built-in Access functions to display information. For example, you might want to display items such as:
You can display all this information by creating calculated fields for the query.
When you reference table names and field names in queries, it is a best practice to enclose names in square brackets ([]
). Access actually requires brackets around any name that contain spaces or punctuation characters. An example of a field name in brackets is:
[tblSales].[SaleDate] + 30
In this example, 30 days is added to the SaleDate field in tblSales.
You'll encounter situations in which you want to limit the query records returned on the basis of a single field criterion, such as in these queries:
Each of these queries requires a single-value criterion. Simply put, a single-value criterion is the entry of only one expression in the QBE grid. The expression can be example data, such as "CA"
, or a function, such as DatePart("m",[SaleDate]) = 1
. Criteria expressions can be specified for virtually any data type: Text, Numeric, Date/Time, and so forth. Even OLE Object and Counter field types can have criteria specified.
You use character criteria for Text or Memo data-type fields. These are either examples or patterns of the contents of the field. To create a query that returns customers who live in New York, for example, follow these steps:
You don't have to enter an equal sign before the literal word NY, because this is a select query. To see all states except New York, you must enter either the <>
(not equal) or the Not
operator before NY.
You also don't have to type quotes around NY. Access assumes that you're using a literal string NY and adds the quotes for you automatically.
Special considerations apply when data in the field contains quotation marks. For example, consider a query to find a person whose name is given as Robert “Bobby” Jones. Ideally, the contacts table would include a nickname field to capture “Bobby,” but, in the absence of a nickname field, the data entry clerk may enter the first name as Robert “Bobby,” using the quotation marks around “Bobby.”
In this case, Access sees the double-quotation characters as data, and you may want to include the quotes in the criteria. The simplest solution is to use a criteria expression such as the following:
'Robert "Bobby"'
Notice the single quotes surrounding the criteria string. Access correctly interprets the single quotes as delimiting characters, and understands that the double quotes within the single quotes are just data. You shouldn't use an expression such as the following:
"Robert 'Bobby'"
This is, of course, the opposite use of quotation marks as the previous example. In this case, Access expects to find single quotes around “Bobby” in the first name field, and no records will be returned.
In previous sections, you worked with literal criteria. You specified the exact field contents for Access to find, which was NY in the previous example. Access used the literal to retrieve the records. Sometimes, however, you know only a part of the field contents, or you might want to see a wider range of records on the basis of a pattern.
For example, you might want to see all product information for items with “convertible” in the description. Many different makes and models may be convertibles, and there's no field where “convertible” will work by itself as the query's criteria. You'll need to use wildcards to make sure you successfully select all records containing “convertible” in the description.
Here's another example: Suppose you have a buyer who has purchased a couple of red models in the last year. You remember making a note of it in the Notes field about the color, but you don't remember which customer it was. To find these records, you're required to use a wildcard search against the Notes field in tblCustomers to find records that contain the word red.
Use the Like
operator in the Criteria cell of a field to perform wildcard searches against the field's contents. Access searches for a pattern in the field; you use the question mark (?
) to represent a single character or the asterisk (*
) for several characters. In addition to ?
and *
, Access uses three other characters for wildcard searches. The table in the “Using Wildcards” sidebar earlier in this chapter lists the wildcards that the Like
operator can use.
The question mark (?
) stands for any single character located in the same position as the question mark in the example expression. An asterisk (*
) stands for any number of characters in the same position in which the asterisk is placed. The pound sign (#
) stands for a single digit (0–9) found in the position occupied by the pound sign. The brackets ([]
) and the list they enclose stand for any single character that matches any one character in the list located within the brackets. Finally, the exclamation point (!
) inside the brackets represents the Not
operator for the list—that is, any single character that does not match any character in the list.
These wildcards can be used alone or in conjunction with each other. They can even be used multiple times within the same expression.
To create an example using the Like
operator, let's suppose you want to find the customer who likes red model cars. You know that red is used in one of the Notes field in tblCustomers. To create the query, follow these steps:
There is, however, one issue with this example. Notice that the criteria ("* red *"
) requires a space after the word red. This means that a record containing the following note will not be returned by this query:
Because there is no space immediately after red, this record will be missed. The proper criteria to use is:
Like "* red[ ,.!*]"
The brackets around “ ,.!*” instruct Access to select records when the Notes field ends with the word red, followed by a space or punctuation character. Obviously, there may be other characters to consider within the brackets, and you must have a good idea of the variety of data in the queried field.
When you click outside the Criteria cell, Access automatically adds the Like
operator and the quotation marks around the expression. Your query QBE pane should look like Figure 9.6.
After creating this query, click on the Datasheet View command to view the query's results. It should look like Figure 9.7.
If you click the Datasheet View command on the Ribbon, you see that a number of records match your query's criteria. The recordset returned by this query includes redundant information in the Company and Notes columns, but the redundancy is the result of asking for this information along with the sales and product data.
Access automatically adds the Like
operator and quotation marks if you meet these conditions:
?
, *
, or #
.[]
) inside quotation marks (""
).If you use the brackets without quotation marks, you must supply the Like
operator and the quotation marks.
Using the Like
operator with wildcards is the best way to perform pattern searches through memo fields. It's just as useful in text and date fields, as the examples in Table 9.5 demonstrate. Table 9.5 shows several examples that can be used to search records in the tables of the database.
Table 9.5 Using Wildcards with the Like Operator
Expression | Field Used In | Results of Criteria |
Like "Ca*" |
tblCustomers.LastName | Finds all records of contacts whose last name begins with Ca (for example, Carson and Casey). |
Like "* red *" |
tblProducts.Features | Finds all records where the Features fields starts and ends with any character, and has red somewhere in the text. |
Like "C*" |
tblSales.PaymentMethod | Finds all sales where the payment method starts with a C. |
Like "## South Main" |
tblCustomers.Address | Finds all records of contacts with houses containing house numbers between 10 and 99 inclusively (for example, 10, 22, 33, 51 on South Main). |
Like "[CDF]*" |
tblCustomers.City | Finds all records of contacts for customers who live in any city with a name beginning with C, D, or F. |
Like "[!EFG]*" |
tblCustomers.City | Finds all records of contacts who live in any city with a name beginning with any letter except E, F, or G. |
To specify a non-matching value, you simply use either the Not
or the <>
operator in front of the expression that you don't want to match. For example, you might want to see all contacts that have purchased a vehicle, but you want to exclude buyers from New York. Follow these steps to see how to specify this non-matching value:
You use numeric criteria with numeric or currency data-type fields. You simply enter the numbers and the decimal symbol—if required—following the mathematical or comparison operator (but do not use commas). For example, you might want to see all sales where the product's inventory count is less than ten:
The criteria applied to numeric fields usually include comparison operators, such as less than (<
), greater than (>
), or equal to (=
). If you want to specify a comparison other than equal, you must enter the operator as well as the value. Remember that Access defaults to equal when running a select query. That's why you needed to specify <10
in the QtyInStock column in the example shown in Figure 9.9.
Access does not surround the criteria with quotes because QtyInStock is numeric and requires no delimiter.
True and false criteria are used with Yes/No type fields. The example data that you supply as criteria must evaluate to true or false. You can also use the Not
and the <>
operators to signify the opposite, but the Yes/No data also has a null state that you might want to consider. Access recognizes several forms of true and false.
Thus, instead of typing Yes, you can type any of these in the Criteria: cell: On, True, Not No, <> No, <No, or –1.
You can specify criteria for OLE objects: Is Null
or Is Not Null
. For example, suppose you don't have pictures for all the products and you want to view only those records that have a picture—that is, those in which the picture is not null. You specify the Is Not Null
criterion for the Picture field of tblProducts.
In previous sections of this chapter, you worked with single-condition criteria on a single field. As you learned in those sections, you can specify single-condition criteria for any field type. In this section, you work with multiple criteria based on a single field. For example, you might be interested in seeing all records in which the buyer comes from New York, California, or Arizona. Or maybe you want to view the records of all the products sold during the first quarter of the year 2012.
The QBE pane has the flexibility to solve these types of problems. You can specify criteria for several fields in a select query. Using multiple criteria, for example, you can determine which products were sold for the past 90 days. Either of the following expressions could be used as criteria in the SaleDate field's criteria:
Between Date() And Date() - 90
Between Date() And DateAdd("d",-90,Date())
Of these, the expression using the DateAdd
function is less ambiguous and more specific to the task.
You use an Or
operator in queries when you want a field to meet either of two conditions. For example, you might want to see all the records where the customer has an address in either New York or California. In other words, you want to see all records where a customer has addresses in NY, in CA, or both. The general expression for this operation is:
[State] = "
NY"
Or [State] = "
CA"
If either side of this expression is true, the resulting answer is also true. To clarify this point, consider these conditions:
The Or
operator is used to specify multiple values for a field. For example, you use the Or
operator if you want to see all records of buyers who live in CT or NJ or NY. To do this, follow these steps:
Besides using the literal Or
operator as a single expression on the Criteria row under the State
field, you can supply individual criteria for the field vertically on separate rows of the QBE pane, as shown in Figure 9.11.
Access rearranges the design shown in Figure 9.11 when the query is saved to match the query in Figure 9.10. In fact, when you open qryFigure_9-11
in the Chapter09.accdb
example database, you'll see that it is exactly the same as qryFigure_9-10
because of the way Access rearranged the criteria when qryFigure_9-11
was originally saved. When you build a query using “vertical” Or
criteria, Access optimizes the SQL statement behind the query by placing all the Or
criteria into a single expression.
Another method for specifying multiple values of a single field is using the In
operator. The In
operator finds a value from a list of values. For example, use the expression IN(AZ,
CA, NY)
under the State
field in the query used in Figure 9.11. The list of values in the parentheses becomes an example criterion. Your query should resemble the query shown in Figure 9.12.
Access automatically adds quotation marks around AZ, CA, and NY.
The And
operator is frequently used in fields that have numeric or date/time data types. It's seldom used with text data types, although it can be this way in some situations. For example, you might be interested in viewing all buyers whose names start with the letters d, e, or f. The And
operator can be used here (>="D" And <="G"
), although the Like
operator is better (Like "[DEF]*"
) because it's much easier to understand.
You use the And
operator in queries when you want a field to meet two or more conditions that you specify. For example, you might want to see records of buyers who have purchased products between October 1, 2012, and March 31, 2013. In other words, the sale had to have occurred during the last quarter of the year 2012 and the first quarter of 2013. The general expression for this example is:
(SaleDate >= #10/1/2012#) And (SaleDate <= #3/31/2013#)
Unlike the Or
operation (which has several conditions under which it is true), the And
operation is true only when both sides of the expression are true. To clarify the use of the And
operator, consider these conditions:
SaleDate
(9/22/2012) is not greater than 10/01/2012 but is less than 3/31/2013: The result is false.SaleDate
(4/11/2013) is greater than 10/01/2012 but is not less than 3/31/2013: The result is false.SaleDate
(11/22/2012) is greater than 10/01/2012 and less than 3/31/2013: The result is true.Using an And
operator with a single field sets a range of acceptable values in the field. Therefore, the key purpose of an And
operator in a single field is to define a range of records to be viewed. For example, you can use the And
operator to create a range criterion to display all buyers who have purchased products between October 1, 2012 and March 31, 2013, inclusively. To create this query, follow these steps:
Notice the pound signs (#
) used to delimit the dates in the expressions on both sides of the And
operator. Access recognizes pound signs as delimiters for date and time values. Without the pound signs, Access evaluates the date values as numeric expressions (10 divided by 1 divided by 2012, for example).
You can request a range of records using another method—the Between…And
operator. With Between…And
, you can find records that meet a range of values—for example, all sales where the list price of the product was $50 or $100. Using the previous example, create the query shown in Figure 9.14.
The operands for the Between…And
operator are inclusive. This means that sales on 10/1/2012 and 3/31/2013 are included in the query results.
A field might have no contents for several reasons. For example, perhaps the value wasn't known at the time of data entry, or the person who did the data entry simply forgot to enter the information, or the field's information was removed. Access does nothing with this field. Unless a default value is specified in the table design, the field simply remains empty. (A field is said to be null when it's truly empty.)
Logically, null is neither true nor false. A null field is not equivalent to all spaces or to zero. A null field simply has no value.
Access lets you work with null value fields by means of two special operators:
Is Null
Is Not Null
You use these operators to limit criteria based on the null state of a field. Earlier in this chapter, you learned that a null value can be used to query for products having a picture on file. In the next example, you look for buyers that don't have the Notes field filled in:
Your query should look like Figure 9.15. Select the Datasheet View command to see the records that don't have a value in the Notes field.
You unchecked the Show box because there is no need to display the Notes field in the query results. The criteria selects only those rows where the Notes field is null, so there is, quite literally, nothing to see in the Notes field and no reason to display it in the results.
Earlier in this chapter, you worked with single and multiple criteria specified in single fields. In this section, you work with criteria across several fields. When you want to limit the records based on several field conditions, you do so by setting criteria in each of the fields that will be used for the scope. Suppose you want to search for all sales of models to resellers in Kansas. Or suppose you want to search for motorcycle model buyers in Massachusetts or Connecticut. Or suppose you want to search for all motorcycle buyers in Massachusetts or trucks in Connecticut. Each of these queries requires placing criteria in multiple fields and on multiple lines.
To use the And
operator and the Or
operator across fields, place your example or pattern data in the Criteria cells (for the And
operator) and the Or cells of one field relative to the placement in another field. When you want to use And
between two or more fields, you place the example or pattern data across the same row in the QBE pane. When you want to use Or
between two fields, you place the criteria on different rows in the QBE pane. Figure 9.16 shows the QBE pane and a rather extreme example of this placement.
The query in Figure 9.16 displays a record if a value matches any of the following criteria:
And
Make = Ford And
Model = Coupe (all must be true).As long as one of these three criteria is true, the record appears in the query's results.
Here's the core SQL statement behind the query in Figure 9.16:
SELECT ModelYear, Make, Model, Color, Category
FROM tblProducts
WHERE ((ModelYear="1932") AND (Make="Ford") AND (Model="Coupe"))
OR (Color="Green")
OR (Category="Cars")
The locations of the parentheses in this SQL statement are significant. One set of parentheses surrounds the criteria for Field1, Field2, and Field3, while parentheses surround each of the criteria applied to Field4 and Field5.
This means, of course, that ModelYear, Make, and Model are applied as a group, while Color and Category are included individually.
Although the Or
operator isn't used across fields as commonly as the And
operator, occasionally Or
is very useful. For example, you might want to see records of any models bought by contacts in Connecticut or you might want to see records on truck models, regardless of the state the customers live in. To create this query, follow these steps:
OR
cell under Category. Your query should resemble Figure 9.17. Notice that the criteria entered are not in the same row of the QBE pane for State and Category. When you place criteria on different rows in the QBE grid, Access interprets this as an Or
between the fields. This query returns customers who either live in Connecticut or have bought truck models.
Here's the SQL statement behind the query in Figure 9.17:
SELECT tblCustomers.Company, tblCustomers.State,
tblProducts.Description, tblProducts.Category
FROM tblProducts
INNER JOIN (tblCustomers
INNER JOIN (tblSales INNER JOIN tblSalesLineItems
ON tblSales.InvoiceNumber = tblSalesLineItems.InvoiceNumber)
ON tblCustomers.CustomerID = tblSales.CustomerID)
ON tblProducts.ProductID = tblSalesLineItems.ProductID
WHERE (tblCustomers.State="CT") OR (tblProducts.Category="Trucks")
Notice the placement of parentheses in the WHERE
clause. Either condition (State = "CT"
or Category="Trucks"
) can be true, and the record is returned by the query.
Moving “Trucks” to the same row as “CT” in the QBE grid changes the query's logic to return customers who live in Connecticut and have bought truck models. The rearranged query is shown in Figure 9.18.
Here's the SQL statement for this minor rearrangement:
SELECT tblCustomers.Company, tblCustomers.State,
tblProducts.Description, tblProducts.Category
FROM tblProducts
INNER JOIN (tblCustomers
INNER JOIN (tblSales INNER JOIN tblSalesLineItems
ON tblSales.InvoiceNumber = tblSalesLineItems.InvoiceNumber)
ON tblCustomers.CustomerID = tblSales.CustomerID)
ON tblProducts.ProductID = tblSalesLineItems.ProductID
WHERE (tblCustomers.State="CT") AND (tblProducts.Category="Trucks")
The difference is significant because the rearrangement is considerably more restrictive when returning records. Only one record is returned by qryFigure_5-18
, while qryFigure5-17
returns 17 rows.
After you've worked with And
and Or
separately, you're ready to create a query using And
and Or
in different fields. In the next example, the query displays records for all buyers of motorcycle models in Connecticut and buyers of truck models in New York:
OR
row under CT in QBE grid.And
s across fields, with an Or
in each field.
The important thing to notice about this query is that Access returns, essentially, two sets of data: car model owners in Connecticut and truck model owners in New York. All other customers and model combinations are ignored.
Suppose you want to view all records of Chevy models bought in the first six months of 2012 where the buyer lives in Massachusetts or any type of vehicle from buyers in California, regardless of when they were bought. In this example, you use two fields for setting criteria: tblCustomers.State, tblProducts.Description, and tblSales.SaleDate. Here's the expression for setting these criteria:
((tblSales.SaleDate Between #1/1/2012# And #6/30/2012#) And
(tblProducts.Description = Like "
*Chev*"
) And
(tblCustomers.State = "
MA"
)) OR (tblCustomers.State = "
CA"
)
The query design is shown in Figure 9.20.