Examples of expressions

Woman writing equation: (c) Digital Vision

Applies to
Microsoft Office Access 2003
Microsoft Access 2000 and 2002

In this article

Introduction

Examples of expressions used in forms and reports

Examples of expressions used in queries and filters

Examples of default value expressions

Examples of field validation rule expressions

Examples of macro condition expressions

Introduction

Often you need information that isn't directly available in a field in your database. For example, you might need to calculate sales tax on an order. At other times, you need to supply a query or a filter with criteria — information that determines which records you work with. Perhaps you want to set a default value for a field or control, or a validation rule for a field or table. In all of these cases, you use an expression.

This article provides examples of expressions. The examples are organized first by where you would employ them, such as in a form or report, or as a default value. Then they're organized by what they do, such as manipulate text or calculate arithmetic values. The examples are designed to work in databases that use the default ANSI SQL query mode, which is ANSI-89.

In Access, the term expression is synonymous with formula. An expression consists of a number of possible elements that are used, alone or in combination, to produce a result. These elements include identifiers (the names of fields, controls, or properties), operators such as + (plus) or - (minus), functions, constants, and values. You use an expression to perform a calculation, retrieve the value of a control, supply criteria to a query, define rules, create calculated controls and calculated fields, and define a group level for a report.

For more information about how and where to use expressions, see the article Create an expression.

 Tip   Try Office 2010 The Expression Builder in Access 2010 has IntelliSense, which lets you see what arguments your expression requires! Read an article or try Office 2010.

Examples of expressions used in forms and reports

This section contains examples of expressions that you can use to create a calculated control in a form or report. A calculated control is a control whose ControlSource property is an expression, instead of a field. Calculated controls are easy to spot, because they always start with the = (equal sign) operator. You use the ControlSource property to tell Access where to get the data for the control.

To enter an expression in a control (for this example, a text box control)    

  1. In the Database window, under Objects, click Forms or Reports.
  2. Click the form or report, and then click Design in the Database window.
  3. Click the text box to select it.
  4. On the View menu, click Properties to display the property sheet for the text box.
  5. Change the value in the Control Source property box of the text box to the expression. For example, insert an expression from the Expression column in the table in the following section.
  6. Close the property sheet.

    Expressions that combine or manipulate text

The expressions in the following table use the & (ampersand) and the + (plus) operators to combine text strings, or use built-in functions to operate on a text string, or otherwise operate on text to create a calculated control.

Expression Result
="N/A" Displays N/A.
=[FirstName] & " " & [LastName] Displays the values of the FirstName and LastName fields, separated by a space.
=Left([ProductName], 1) Uses the Left function to display the first character of the value of the ProductName control.
=Right([AssetCode], 2) Uses the Right function to display the last 2 characters of the value of the AssetCode control.
=Trim([Address]) Uses the Trim function to display the value of the Address control, removing any leading or trailing spaces.
=IIf(IsNull([Region]), [City] & " " & [PostalCode], [City] & " " & [Region] & " " & [PostalCode]) Uses the IIf function to display the values of the City and PostalCode controls if the value in the Region control is null; otherwise, it displays the values of the City, Region, and PostalCode controls, separated by spaces.
=[City] & (" " + [Region]) & " " & [PostalCode] Uses the + operator and null propagation to display the values of the City and PostalCode controls if Region is null; otherwise, it displays the values of the City, Region, and PostalCode controls, separated by spaces. Null propagation means that if any component of an expression is null, the entire expression is also null. The + operator supports null propagation; the & operator does not.

    Expressions for headers and footers

You use the Page and the Pages properties to display or print page numbers in forms or reports. The Page and Pages properties are available only during printing or print preview, so they are not listed on the property sheet. Most often, you place expressions such as these in a text box control in the header or footer section of your form or report.

Expression Result
=[Page] 1
="Page " & [Page] Page 1
="Page " & [Page] & " of " & [Pages] Page 1 of 3
=[Page] & " of " & [Pages] & " Pages" 1 of 3 Pages
=[Page] & "/" & [Pages] & " Pages" 1/3 Pages
=[Country] & " - " & [Page] UK - 1
=Format([Page], "000") 001
="Printed on: " & Date() Printed on: 12/31/04

    Expressions that perform arithmetic operations

You can use expressions to add, subtract, multiply, and divide the values in two or more fields or controls. You can also use expressions to perform arithmetic operations on dates. For example, if RequiredDate is a Date/Time data type field or control, the expression =[RequiredDate] - 2 returns a Date/Time value equal to two days before RequiredDate.

Expression Result
=[Subtotal]+[Freight] The sum of the values of the Subtotal and Freight controls.
=[RequiredDate]-[ShippedDate] The difference between the values of the RequiredDate and ShippedDate controls.
=[Price]*1.06 The product of the value of the Price control and 1.06 (adds 6 percent to the Price value).
=[Quantity]*[Price] The product of the values of the Quantity and Price controls.
=[EmployeeTotal]/[CountryTotal] The quotient of the values of the EmployeeTotal and CountryTotal controls.

 Note   When you use an arithmetic operator (+, -, *, and /) in an expression, and the value of one of the controls in the expression is null, the result of the entire expression will be null. If some records in one of the controls that you used in the expression might have a null value, you can convert the null value to zero by using the Nz function, for example, =Nz([Subtotal])+Nz([Freight]). See the article Nz function for more information.

    Expressions that refer to values in controls

Sometimes you need a value that exists somewhere else, such as in a field or control on another form or report. You can use an expression to return the value from another field or control.

The following table lists examples of expressions that you can use in calculated controls on forms.

Expression Result
=Forms![Orders]![OrderID] The value of the OrderID control on the Orders form.
=Forms![Orders]![Orders Subform].Form![OrderSubtotal] The value of the OrderSubtotal control on the Orders subform on the Orders form.
=Forms![Orders]![Orders Subform]![ProductID].Column(2) The value of the third column in ProductID, a multiple-column list box on the Orders subform on the Orders form. (0 refers to the first column, 1 refers to the second column, and so on.)
=Forms![Orders]![Orders Subform]![Price] * 1.06 The product of the value of the Price control on the Orders subform on the Orders form and 1.06 (adds 6 percent to the value of the Price control).
=Parent![OrderID] The value of the OrderID control on the main or parent form of the current subform.

The following table lists examples of expressions that you can use in calculated controls on reports.

Expression Result
=Reports![Invoice]![OrderID] The value of the OrderID control on the Invoice report.
=Reports![Summary]![Summary Subreport]![SalesTotal] The value of the SalesTotal control on the Summary subreport on the Summary report.
=Parent![OrderID] The value of the OrderID control on the main or parent report of the current subreport.

    Expressions that count, sum, and average values by using aggregate functions

Often you need to calculate a sum of the values that are stored in a group of records. For example, you might want to calculate a group total for the group footer in a report, or an order subtotal for line items on a form. At other times, you need to count the number of items rather than to sum them; or you need to calculate the average value. The expressions in the following table use functions that are designed to aggregate or summarize data. You will often see these functions (for example, Sum, Count, and Avg) referred to as aggregate functions.

Expression Description
=Avg([Freight]) Uses the Avg function to display the average of the values of the Freight control.
=Count([OrderID]) Uses the Count function to display the number of records in the OrderID control.
=Sum([Sales]) Uses the Sum function to display the sum of the values of the Sales control.
=Sum([Quantity]*[Price]) Uses the Sum function to display the sum of the product of the values of the Quantity and Price controls.
=[Sales]/Sum([Sales])*100

Displays the percentage of sales, determined by dividing the value of the Sales control by the sum of all the values of the Sales control.

 Note   If the Format property of the control is set to Percent, do not include *100 in the expression.

    Expressions that selectively count, sum, and look up values by using domain aggregate functions

Sometimes you need to sum or count values selectively. For example, you might want to count only those values that are within a certain range or that evaluate to Yes. At other times you might need to look up a value from another table for display. Access supports a series of functions that can be used for this sort of task. They are called the domain aggregate functions.

Expression Description
=DLookup("[ContactName]", "[Suppliers]", "[SupplierID] = " & Forms("Suppliers")("[SupplierID]")) Uses the DLookup function to return the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table matches the value of the SupplierID control on the Suppliers form.
=DLookup("[ContactName]", "[Suppliers]", "[SupplierID] = " & Forms![New Suppliers]![SupplierID]) Uses the DLookup function to return the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table matches the value of the SupplierID control on the New Suppliers form.
=DSum("[OrderAmount]", "[Orders]", "[CustomerID] = 'RATTC'") Uses the DSum function to return the sum total of the values in the OrderAmount field in the Orders table where the CustomerID is RATTC.
=DCount("[Retired]","[Assets]","[Retired]=Yes") Uses the DCount function to return the number of Yes values in the Retired field (a Yes/No field) in the Assets table.

    Expressions that manipulate and calculate dates

Certain things are fundamental to a database application, among them, the need to track dates and times. You work with dates and times in Access by using the Date/Time data type. Access can perform arithmetic calculations on dates; for example, you can calculate how many days have elapsed since the invoice date to age your accounts receivable. You can format dates and times in numerous ways, as shown in the following table.

Expression Description
=Date() Uses the Date function to display the current date in the form of mm-dd-yy, where mm is the month (1 through 12), dd is the day (1 through 31), and yy is the last two digits of the year (1980 through 2099).
=Format(Now(), "ww") Uses the Format function to display the week number of the year for the current date, where ww represents weeks 1 through 53.
=DatePart("yyyy", [OrderDate]) Uses the DatePart function to display the four-digit year of the value of the OrderDate control.
=DateAdd("y", -10, [PromisedDate]) Uses the DateAdd function to display a date that is 10 days before the value of the PromisedDate control.
=DateDiff("d", [OrderDate], [ShippedDate]) Uses the DateDiff function to display the number of days' difference between the values of the OrderDate and ShippedDate controls.
=[InvoiceDate] + 30 Uses arithmetic operations on dates to calculate the date 30 days after the date in the InvoiceDate field or control.

    Conditional expressions that return one of two possible values

The example expressions in the following table use the IIf function to return one of two possible values. You pass the IIf function three arguments: The first argument is an expression that must return a True or False value. The second argument is the value to return if the expression is true, and the third argument is the value to return if the expression is false.

Expression Description
=IIf([Confirmed] = "Yes", "Order Confirmed", "Order Not Confirmed") Uses the IIf function to display the message "Order Confirmed" if the value of the Confirmed control is Yes; otherwise, it displays the message "Order Not Confirmed."
=IIf(IsNull([Country]), " ", [Country]) Uses the IIf function to display an empty string if the value of the Country control is null; otherwise, it displays the value of the Country control.
=IIf(IsNull([Region]), [City] & " " & [PostalCode], [City] & " " & [Region] & " " & [PostalCode]) Uses the IIf function to display the values of the City and PostalCode controls if the value in the Region control is null; otherwise, it displays the values of the City, Region, and PostalCode controls.
=IIf(IsNull([RequiredDate]) Or IsNull([ShippedDate]), "Check for a missing date", [RequiredDate] - [ShippedDate]) Uses the IIf function to display the message "Check for a missing date" if the result of subtracting ShippedDate from RequiredDate is null; otherwise, it displays the difference between the values of the RequiredDate and ShippedDate controls.

Top of Page Top of Page


Examples of expressions used in queries and filters

This section contains examples of expressions that you can use to create a calculated field in a query or to supply criteria to a query. A calculated field is a column in a query that results from an expression. For example, you can calculate a value or format a portion of a date. You use criteria in a query to limit the records that you work with. For example, you can use the Between operator to supply a date range for the ShippedDate field in order to limit the query result to orders that were shipped between those dates.

Expressions that create a calculated field (perform calculations on or manipulate field values)

The example expressions in the following list can be used to create a calculated field in a query.

To enter a calculated field in query Design view    

  1. In the Database window, under Objects, click Queries.
  2. Click the query, and then click Design in the Database window.
  3. Click the field cell in the column where you want to create the calculated field.
  4. Type the expression, or click the Build button Button image on the toolbar to create an expression by using the Expression Builder. You should start the expression with a name followed by a colon; for example, type ExtendedPrice: to start a calculated field called ExtendedPrice.

    Expressions that manipulate text in a query or filter

The expressions in the following table use the & and the + operators to combine text strings, use built-in functions to operate on a text string, or otherwise operate on text to create a calculated field.

Expression Description
FullName: [FirstName] & " " & [LastName] Displays the value of the FirstName and LastName fields, separated by a space, in the FullName field.
Address2: [City] & " " & [Region] & " " & [PostalCode] Displays the value of the City, Region, and PostalCode fields, separated by spaces, in the Address2 field.
ProductInitial: Left([ProductName], 1) Uses the Left function to display, in the ProductInitial field, the first character of the value in the ProductName field.
TypeCode: Right([AssetCode], 2) Uses the Right function to display, in the TypeCode field, the last two characters of the value in the AssetCode field.
AreaCode: Mid([Phone],2,3) Uses the Mid function to display, in the AreaCode field, the three characters starting with the second character of the value in the Phone field.

    Expressions that perform arithmetic operations in calculated fields

You can use expressions to add, subtract, multiply, and divide the values in two or more fields or controls. You can also perform arithmetic operations on dates. For example, if RequiredDate is a Date/Time data type field or control, the expression =[RequiredDate] - 2 will return a Date/Time value equal to two days before RequiredDate.

Expression Description
PrimeFreight: [Freight] * 1.1 Displays freight charges plus 10 percent in the PrimeFreight field.
OrderAmount: [Quantity] * [UnitPrice] Displays the product of the values in the Quantity and UnitPrice fields in the OrderAmount field.
LeadTime: [RequiredDate] - [ShippedDate] Displays the difference between the values in the RequiredDate and ShippedDate fields in the LeadTime field.
TotalStock: [UnitsInStock]+[UnitsOnOrder] Displays the sum of the values in the UnitsInStock and UnitsOnOrder fields in the TotalStock field.
FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100

Displays, in the FreightPercentage field, the percentage of freight charges in each subtotal, by dividing the sum of the values in the Freight field by the sum of the values in the Subtotal field. (This example uses the Sum function.)

The Total row in the design grid must be displayed, and the Total cell for this field must be set to Expression.

If the Format property of the field is set to Percent, do not include *100.

    Expressions that manipulate and calculate with dates in calculated fields

Certain things are fundamental to a database application, among them, the need to track dates and times. You work with dates and times in Access by using the Date/Time data type. Access can perform arithmetic calculations on dates; for example, you can calculate how many days have elapsed since the invoice date to age your accounts receivable. As the following table shows, you can format dates and times numerous ways.

Expression Description
LagTime: DateDiff("d", [OrderDate], [ShippedDate]) Uses the DateDiff function to display in the LagTime field the number of days between the order date and ship date.
YearHired: DatePart("yyyy",[HireDate]) Uses the DatePart function to display in the YearHired field the year each employee was hired.
MinusThirty: Date( )- 30 Uses the Date function to display the date 30 days prior to the current date.

    Expressions that count, sum, and average values by using SQL aggregate or domain aggregate functions

Often you need to calculate a sum of the values that are stored in a group of records. For example, you might need to calculate a group total for the group footer in a report, or an order subtotal for line items on a form. At other times, you need to count the number of items rather than to sum them, or you want to calculate the average value. The expressions in the following table use functions that are designed to aggregate or summarize data. You will often see these functions (for example, Sum, Count, and Avg) referred to as aggregate functions.

Sometimes you need to sum or count values selectively. For example, you might want to count only those values that are within a certain range, or those that evaluate to Yes. At other times, you need to look up a value from another table so that you can display it. Access supports a series of functions that can be used for this sort of task. These functions are called the domain aggregate functions (for example, DSum, DCount, and DAvg).

To calculate totals, you will often need to create a totals query. For example, to summarize by group, you need to use a totals query. To enable a totals query from the query design grid, click Totals on the View menu.

Expression Description
RowCount:Count(*) Uses the Count function to count the number of records in the query, including records with null (blank) fields.
FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100

Displays, in the FreightPercentage field, the percentage of freight charges in each subtotal by dividing the sum of the values in the Freight field by the sum of the values in the Subtotal field. (This example uses the Sum function.)

The Total row in the design grid must be displayed, and the Total cell for this field must be set to Expression.

If the Format property of the field is set to Percent, do not include *100.

AverageFreight: DAvg("[Freight]", "[Orders]") Uses the DAvg function to display, in the AverageDiscount field, the average discount given on all orders combined in a totals query.

    Expressions for working with fields with missing information (fields with null values)

The expressions shown here work with fields with potentially missing information — those that might have a null value. A null value represents the absence of information; it does not represent zero, or any value at all. Access supports this idea of missing information because the concept is vital to the integrity of a database. In the real world, information is often missing, even if only temporarily (for example, the as-yet undetermined price for a new product). Therefore, a database that models a real world entity, such as a business, must be able to record information as missing. You can use the IsNull function to determine if a field or control contains a null value, and you can use the Nz function to convert a null value to zero.

Expression Description
CurrentCountry: IIf(IsNull([Country]), " ", [Country]) Uses the IIf and IsNull functions to display an empty string in the CurrentCountry field if the Country field is null; otherwise, it displays the contents of the Country field.
LeadTime: IIf(IsNull([RequiredDate] - [ShippedDate]), "Check for a missing date", [RequiredDate] - [ShippedDate]) Uses the IIf and IsNull functions to display, in the LeadTime field, the message "Check for a missing date" if the value of either the RequiredDate field or the ShippedDate field is null; otherwise, it displays the difference.
SixMonthSales: Nz([Qtr1Sales]) + Nz([Qtr2Sales]) Displays, in the SixMonthSales field, the total of the values in the first-quarter and second-quarter sales fields combined, by first using the Nz function to convert the null values to zero.

    Expression that uses a subquery to create a calculated field

Sometimes a nested query, also called a subquery, can be used to create a calculated field. A subquery is expressed by using Structured Query Language (SQL) — the query language that Access uses. The expression in the following table is one example of a calculated field that results from a subquery.

Expression Description
Cat: (SELECT [CategoryName] FROM [Categories] WHERE [Products].[CategoryID]=[Categories].[CategoryID]) Displays the CategoryName, if the CategoryID from the Categories table is the same as the CategoryID from the Products table.

Expressions used as matching criteria to limit the records you work with

You can use an expression to define the criteria for matching rows in a query. Access then returns only those rows that match the criteria. In the list that follows, you will find sample expressions that you can use to define criteria. To define criteria, you open a query and then click Design, which opens the query design grid. Then you locate the field for which you want to enter the criteria. Each column in the query design grid represents a field. Finally, you click in the Criteria cell for that field and type your criteria.

To enter criteria in the query design grid    

  1. In the Database window, under Objects, click Queries.
  2. Click the query, and then click Design in the Database window.
  3. Click in the criteria cell in the column for which you want to enter matching criteria.
  4. Type the criteria expression or click the Build button Button image on the toolbar to create an expression by using the Expression Builder.

 Note   Do not precede the criteria expression with the = operator.

If you want a larger area in which to type an expression, press SHIFT+F2 to display the Zoom box.

    Expressions that match whole or partial text values

The sample expressions in the Expression column of the following table define the criteria that match whole or partial text values.

Field Expression Description
ShipCity "London" Displays orders shipped to London.
ShipCity "London" Or "Hedge End" Uses the Or operator to display orders shipped to London or Hedge End.
ShipCountry In("Canada", "UK") Uses the In operator to display orders shipped to Canada or the UK.
ShipCountry Not "USA" Uses the Not operator to display orders shipped to countries other than the USA.
ProductName Not Like "C*" Uses the Not operator and the * wildcard character to display products whose names do not begin with C.
CompanyName >="N" Displays orders shipped to companies whose names start with the letters N through Z.
ProductCode Right([ProductCode], 2)="99" Uses the Right function to display orders with ProductCode values that end in 99.
ShipName Like "S*" Displays orders shipped to customers whose names start with the letter S.

    Expressions that use dates in matching criteria

Access can perform arithmetic calculations on dates; for example, you can use the OrderDate field to display orders more than 30 days old (see the following table). You can also use a variety of built-in functions to extract and manipulate portions of dates or to place a date within calendar periods (for example, to determine what calendar quarter a date is in). The sample expressions that follow demonstrate the use of dates and related functions in criteria expressions.

Field Expression Description
ShippedDate #2/2/2000# Displays orders shipped on February 2, 2000.
ShippedDate Date() Displays orders shipped today.
RequiredDate Between Date( ) And DateAdd("m", 3, Date( )) Uses the Between...And operator and the DateAdd and Date functions to display orders required between today's date and three months from today's date.
OrderDate < Date( ) - 30 Uses the Date function to display orders more than 30 days old.
OrderDate Year([OrderDate])=2005 Uses the Year function to display orders with order dates in 2005.
OrderDate DatePart("q", [OrderDate])=4 Uses the DatePart function to display orders for the fourth calendar quarter.
OrderDate DateSerial(Year ([OrderDate]), Month([OrderDate])+1, 1)-1 Uses the DateSerial, Year, and Month functions to display orders for the last day of each month.
OrderDate Year([OrderDate])= Year(Now()) And Month([OrderDate])= Month(Now()) Uses the Year and Month functions and the And operator to display orders for the current year and month.
ShippedDate Between #1/5/2005# And #1/10/2005# Uses the Between...And operator to display orders shipped no earlier than 5-Jan-2005 and no later than 10-Jan-2005.
RequiredDate Between Date( ) And DateAdd("M", 3, Date( )) Uses the Between...And operator to display orders required between today's date and three months from today's date.
BirthDate Month([BirthDate])=Month(Date()) Uses the Month and Date functions to display employees who have birthdays this month.

    Expressions that match a missing value (null) or a zero-length string

The expressions in the following table work with fields that have potentially missing information — those that might contain a null value or a zero-length string. A null value represents the absence of information; it does not represent a zero or any value at all. Access supports this idea of missing information because the concept is vital to the integrity of a database. In the real world, information is often missing, even if only temporarily (for example, the as-yet undetermined price for a new product). Therefore, a database that models a real world entity, such as a business, must be able to record information as missing. You can use the IsNull function to determine if a field or control contains a null value, and you can use the Nz function to convert a null value to zero.

Field Expression Description
ShipRegion Is Null Displays orders for customers whose ShipRegion field is null (missing).
ShipRegion Is Not Null Displays orders for customers whose ShipRegion field contains a value.
Fax "" Displays orders for customers who don't have a fax machine, indicated by a zero-length string value in the Fax field instead of a null (missing) value.

    Expressions that use patterns to match records

The Like operator provides a great deal of flexibility when you are trying to match rows that follow a pattern. That is because Like can be used with special characters called wildcard characters that let you define patterns for Access to match. For example, the * (asterisk) wildcard character matches a sequence of characters of any type, and makes it easy to find all names that begin with a letter. You use the expression Like "S*" to find all names that begin with the letter S, for example. For more information, see the article Like operator.

Field Expression Description
ShipName Like "S*" Orders shipped to customers whose names start with the letter S.
ShipName Like "*Imports" Orders shipped to customers Orders shipped to customers whose names end with the word "Imports".
ShipName Like "[A-D]*" Orders shipped to customers whose names start with A through D.
ShipName Like "*ar*" Orders shipped to customers whose names include the letter sequence "ar".
ShipName Like "Maison Dewe?" Orders shipped to the customer with "Maison" as the first part of its name and a five-letter second name in which the first four letters are "Dewe" and the last letter is unknown.
ShipName Not Like "A*" Orders shipped to customers whose names do not start with the letter A.

    Expressions that match rows based on the result of a domain aggregate function

Sometimes you need to sum or count values selectively. For example, you might want to count only those values that are within a certain range, or that evaluate to Yes. At other times you might need to look up a value from another table so that you can display it. Access supports a series of functions called the domain aggregate functions (for example, DSum, DCount, and DAvg) that can be used for this sort of task. The sample expressions in the following table use the domain aggregate functions to perform a calculation on a set of values, and use the result as the query criteria.

Field Expression Description
Freight > (DStDev("[Freight]", "Orders") + DAvg("[Freight]", "Orders")) Uses the DAvg and DStDev functions to display all orders for which the freight cost rose above the mean plus the standard deviation for freight cost.
Quantity > DAvg("[Quantity]", "[Order Details]") Uses the DAvg function to display products ordered in quantities above the average order quantity.

    Expressions that match based on the results of subqueries

Sometimes a nested query, also called a subquery, can be used to calculate a value to be used as the criteria. A subquery is expressed by using Structured Query Language (SQL) — the query language that Access uses. The sample expressions in the following table match rows based on the results from a subquery.

Field Expression Displays
UnitPrice (SELECT [UnitPrice] FROM [Products] WHERE [ProductName] = "Aniseed Syrup") Products whose price is the same as the price of Aniseed Syrup.
UnitPrice >(SELECT AVG([UnitPrice]) FROM [Products]) Products that have a unit price above the average.
Salary > ALL (SELECT [Salary] FROM [Employees] WHERE ([Title] LIKE "*Manager*") OR ([Title] LIKE "*Vice President*")) Salary of every sales representative whose salary is higher than that of all employees with "Manager" or "Vice President" in their titles.
OrderTotal: [UnitPrice] * [Quantity] > (SELECT AVG([UnitPrice] * [Quantity]) FROM [Order Details]) Orders with totals that are higher than the average order value.

Expressions used to update the data in an update query

Often you need to modify the values in a column in your database. One of the ways that you can do this is by using an update query. With an update query, you can tell Access which records to update and how to compute the new values for the fields that you want to update. When you create an update query to update a field, you provide the expression that supplies the replacement value. The expressions in the following table represent example expressions that supply a replacement value.

Use expressions such as the following in the Update To cell in the query design grid for the field that you want to update.

Field Expression Result
Title "Salesperson" Changes a text value to Salesperson.
ProjectStart #8/10/99# Changes a date value to 10-Aug-99.
Retired Yes Changes a No value in a Yes/No field to Yes.
PartNumber "PN" & [PartNumber] Adds PN to the beginning of each specified part number.
LineItemTotal [UnitPrice] * [Quantity] Calculates the product of UnitPrice and Quantity.
Freight [Freight] * 1.5 Increases freight charges by 50 percent.
Sales DSum("[Quantity] * [UnitPrice]",
"Order Details", "[ProductID]=" & [ProductID])
Where the ProductID values in the current table match the ProductID values in the Order Details table, updates sales totals based on the product of Quantity and UnitPrice.
ShipPostalCode Right([ShipPostalCode], 5) Truncates the leftmost characters, leaving the five rightmost characters.
UnitPrice Nz([UnitPrice]) Changes a null (Null: A value you can enter in a field or use in expressions or queries to indicate missing or unknown data. In Visual Basic, the Null keyword indicates a Null value. Some fields, such as primary key fields, can't contain a Null value.) value to a zero (0) in the UnitPrice field.

Expressions used in SQL statements

Structured Query Language, or SQL, is the query language that Access uses. Every query that you create in query Design view can also be expressed by using SQL. To see the SQL for any query, click SQL View on the View menu. The following table shows sample SQL statements that employ an expression.

SQL statement that uses an expression Result
SELECT [FirstName],[LastName] FROM [Employees] WHERE [LastName]="Davolio" Displays the values in the FirstName and LastName fields for employees whose last name is Davolio.
SELECT [ProductID],[ProductName] FROM [Products] WHERE [CategoryID]=Forms![New Products]![CategoryID]; Displays the values in the ProductID and ProductName fields in the Products table for records in which the CategoryID value matches the CategoryID value specified in an open New Products form.
SELECT Avg([ExtendedPrice]) AS [Average Extended Price] FROM [Order Details Extended] WHERE [ExtendedPrice]>1000; Calculates the average extended price for orders for which the value in the ExtendedPrice field is more than 1000, and displays it in a field named Average Extended Price.
SELECT [CategoryID], Count([ProductID]) AS [CountOfProductID] FROM [Products] GROUP BY [CategoryID] HAVING Count([ProductID])>10; In a field named CountOfProductID, displays the total number of products for categories with more than 10 products.

Top of Page Top of Page


Examples of default value expressions

It is often useful to give a field or control a default value. That way, Access supplies the default value when a new record with the field is created or when the object that contains the control is created. The expressions in the following table represent the sample default values for a field or control.

To enter a default value for a field in a table    

  1. In the Database window, under Objects, click Tables.
  2. Click the table, and then click Design in the Database window.
  3. Click the field name for the field that you want.
  4. Click the Default Value property box.
  5. Type the expression, or click the Build button button image to the right of the property box to create an expression by using the Expression Builder.

If a control is bound to a field in a table, and the field has a default value, the default value of the control takes precedence.

Field Expression Default field value
Quantity 1 1
Region "MT" MT
Region "New York, N.Y." New York, N.Y. (Note that you must enclose the value in quotation marks if it includes punctuation.)
Fax "" A zero-length string to indicate that by default this field should be empty instead of a null value
Order Date Date( ) Today's date
DueDate Date() + 60 The date 60 days forward from today

Top of Page Top of Page


Examples of field validation rule expressions

You can create a validation rule for a field or control by using an expression. Access then enforces the rule when data is entered into the field or control. To create a validation rule, you modify the ValidationRule property of the field or control. You should also consider setting the ValidationText property, which holds the text that Access displays when the validation rule is violated. If you don't set the ValidationText property, Access displays a default error message.

The examples in the following table demonstrate the validation rule expressions for the ValidationRule property and the associated text for the ValidationText property.

To enter a validation rule for a field in a table    

  1. In the Database window, under Objects, click Tables.
  2. Click the table, and then click Design in the Database window.
  3. Click the field name for the field that you want.
  4. Click the Validation Rule property box.
  5. Type the expression, or click the Build button button image to the right of the property box to create an expression by using the Expression Builder.

 Note   Do not precede the expression with the = operator when you create a validation rule.

ValidationRule property ValidationText property
<> 0 Please enter a nonzero value.
0 Or > 100 Value must be either 0 or more than 100.
Like "K???" Value must be four characters beginning with the letter K.
< #1/1/2005# Enter a date prior to 1/1/2005.
>= #1/1/2005# And < #1/1/2006# Date must be in 2005.

Top of Page Top of Page


Examples of macro condition expressions

In some cases, you might want to carry out an action or series of actions in a macro only if a particular condition is true. For example, suppose you want an action to run only when the value of the Counter text box is 10. You use an expression to define the condition in the Condition column of the macro: [Counter]=10.

To enter a condition for a macro action    

  1. In the Database window, under Objects, click Macros.
  2. Click the macro, and then click Design in the Database window.
  3. Click the Condition cell for the macro action.

If the Condition column is not visible, on the View menu, click Conditions.

  1. Type a conditional expression.
  2. Close the macro.

As with the ValidationRule property, the Condition column expression is a conditional expression. It must resolve to either a True or False value. The action takes place only when the condition is true.

Use this expression To carry out the action if
[City]="Paris" Paris is the City value in the field on the form from which the macro was run.
DCount("[OrderID]", "Orders") > 35 There are more than 35 entries in the OrderID field of the Orders table.
DCount("*", "[Order Details]", "[OrderID]=" & Forms![Orders]![OrderID]) > 3 There are more than three entries in the Order Details table for which the OrderID field of the table matches the OrderID field on the Orders form.
[ShippedDate] Between #2-Feb-2005# And #2-Mar-2005# The value of the ShippedDate field on the form from which the macro is run is no earlier than 2-Feb-1995 and no later than 2-Mar-1995.
Forms![Products]![UnitsInStock] < 5 The value of the UnitsInStock field on the Products form is less than 5.
IsNull([FirstName]) The FirstName value on the form from which the macro is run is null (has no value). This expression is equivalent to [FirstName] Is null.
[Country]="UK" And Forms![SalesTotals]![TotalOrds] > 100 The value in the Country field on the form from which the macro is run is UK, and the value of the TotalOrds field on the SalesTotals form is greater than 100.
[Country] In ("France", "Italy", "Spain") And Len([PostalCode])<>5 The value in the Country field on the form from which the macro is run is either France, Italy, or Spain, and the postal code is not 5 characters long.
MsgBox("Confirm changes?",1)=1 You click OK in a dialog box that the MsgBox function displays. If you click Cancel in the dialog box, Access ignores the action.

 Note   To force Access to temporarily ignore an action, enter False as a condition. Forcing Access to temporarily ignore an action can be helpful when you are trying to find problems in a macro.

Top of Page Top of Page

 
 
Applies to:
Access 2003