Download presentation
Presentation is loading. Please wait.
Published byGarey McDonald Modified over 6 years ago
1
MS Access - Query A queryis a request for data results, and for action on data. Purpose The purpose of a query in Microsoft Access is to retrieve a particular set of data from one or more tables the query is concerned with. It can be used to group or filter the data according to the needs of the custom
2
You can use a query to answer a simple question, to perform calculations, to combine data from different tables, or even to add, change, or delete table data.
6
select, append, update, delete, make table.
Query types select, append, update, delete, make table. The goal of the query determines the type of query to use. A select query helps the user simply pull information from the table based upon the user-defined needs. For example, a select query can isolate customer names beginning with the letter "M.“ .
7
An append query is created to add information to a table.
An update query can modify table records according to the user's needs. Delete queries remove records from the table. A make table query allows a user to make a new table from selected records
20
Update Query
21
UPDATE An Update Query is used when you want to update records in your Access tables based on specific criteria. For example, "update the State field to 'NY' for all records in the Customer table where the City is New York."
24
Create and run an update query
You can think of update queries as a powerful form of the Find and Replace dialog box. You use update queries in Access databases to add, change, or delete the information in an existing record. You cannot use an update query to add new records to a database, or to delete records from a database. To add new records to a database you use an append query, and to delete whole records from a database you use a delete query.
25
Update lots of records in one pass.
Change records in more than one table at the same time. Use criteria that do not depend on the value that you want to replace.
26
An update query cannot be used to update data in the following types of fields:
Calculated fields Fields from a totals query or a crosstab query AutoNumber fields Fields that are primary keys Fields in a union query Fields in unique-values queries and unique-records queries
27
An update query cannot be used to update data in the following types of fields:
Calculated fields The values in calculated fields do not permanently reside in tables. They only exist in your computer's temporary memory after Access calculates them. Because calculated fields do not have a permanent storage location, you cannot update them. Fields from a totals query or a crosstab query The values in these types of query are calculated, and therefore cannot be updated by an update query. AutoNumber fields By design, the values in AutoNumber fields change only when you add a record to a table.
28
Fields that are primary keys
In some cases, such as if the primary key field is used in a table relationship, you cannot update the field by using a query unless you first set the relationship to automatically cascade updates. Fields in unique-values queries and unique-records queries The values in such queries are summarized. Some of the values represent a single record, and others represent more than one record. The update operation is not possible because it is not possible to determine what records were excluded as duplicates, and therefore not possible to update all the necessary records. This restriction applies whether you use an update query or try to update data manually by entering values in a form or a datasheet. Fields in a union query You cannot update data from fields in a union query because each record that appears in two or more data sources only appears once in the union query result. Because some duplicate records are removed from the results, Access cannot update all the necessary records.
29
Step 2: Update the records
On the Design tab, in the Query Type group, click Update. The following illustration shows an update query that returns all the assets purchased after January 5, 2005 and changes the location to "Warehouse 3" for all the records that meet that criterion.
31
You can use any valid expression in the Update to row.
Table of example expressions This table shows some example expressions and explains how they change data. Expression Result "Salesperson" In a Text field, changes a text value to Salesperson. #8/10/07# In a Date/Time field, changes a date value to 10-Aug-07. Yes In a Yes/No field, changes a No value to Yes. "PN" & [PartNumber] Adds "PN" to the beginning of each specified part number. [UnitPrice] * [Quantity] Multiplies the values in fields named UnitPrice and Quantity. [Freight] * 1.5 Increases the values in a field named Freight by 50 percent. DSum("[Quantity] * [UnitPrice]", "Order Details", "[ProductID]=" & [ProductID]) Where the ProductID values in the current table match the ProductID values in table named Order Details, this expression updates sales totals by multiplying the values in a field named Quantity by the values in a field named UnitPrice. The expression uses the DSum function because it can operate against more than one table and table field. Right([ShipPostalCode], 5) Truncates (removes) the leftmost characters in a text or numeric string and leaves the 5 rightmost characters. IIf(IsNull([UnitPrice]), 0, [UnitPrice]) Changes a null (unknown or undefined) value to a zero (0) value in a field named UnitPrice.
32
Append Query
33
An append query selects records from one or more data sources and copies the selected records to an existing table. For example, suppose that you acquire a database that contains a table of potential new customers, and that you already have a table in your existing database that stores that kind of data. You'd like to store the data in one place, so you decide to copy it from the new database into your existing table. To avoid entering the new data manually, you can use an append query to copy the records.
34
Benefits of using an append query
By using a query to copy data, you can: Append multiple records in one pass If you copy data manually, you usually have to perform multiple copy/paste operations. By using a query, you select all the data at once, and then copy it. Review your selection before you copy it You can view your selection in Datasheet view and can make adjustments to your selection as needed before you copy the data. This can be particularly handy if your query includes criteria or expressions, and you need several tries to get it just right. You cannot undo an append query. If you make a mistake, you must either restore your database from a backup or correct your error, either manually or by using a delete query. Use criteria to refine your selection For example, you might want to only append records of customers who live in your city. Append records when some of the fields in the data sources don't exist in the destination table For example, suppose that your existing customer table has eleven fields, and the new table that you want to copy from only has nine of those eleven fields. You can use an append query to copy the data from the nine fields that match and leave the other two fields blank.
35
Basic steps of an append query
The process of creating an append query follows these basic steps: Create a select query You start by selecting the data that you want to copy. You can adjust your select query as needed, and run it as many times as you want to make sure you are selecting the data that you want to copy. Convert the select query to an append query After your selection is ready, you change the query type to Append. Choose the destination fields for each column in the append query In some cases, Access automatically chooses the destination fields for you. You can adjust the destination fields, or choose them if Access did not. Preview and run the query to append the records Before you append the records, you can switch to Datasheet view for a preview of the appended records.
39
Select Query
41
Append Append QueryAn Append Query will add records to a table you choose. For example, if you have imported records from an Excel file into a temporary staging table, you can then add them to your actual "live" tables using an Append Query. First, create your Select Query with any necessary filter criteria. Then choose the "Append" Ribbon icon. You will be prompted to indicate what table you want to add records to. Once you choose the table, you can match the fields between the source table and destination table using the "Append To:" row highlighted in the screenshot below.
42
Append
43
Parameterize
44
Criteria section In the Criteria section, we are filtering to shown any record where the Company Name contains "Research." the "Like" statement is very powerful, and lets you find records that begin with a word (Like "Hello*"), end with a word (Like "*Hello"), or contain a word (Like "*Hello*").
45
Cross tab Query When you want to restructure summary data to make it easier to read and understand, consider using a crosstab query. A crosstab query is a matrix, where the column headings come from the values in a field. In the example below, the product names appear down the left, the ... Dr. Anup Kumar
46
Creating crosstab queries
A crosstab query calculates a sum, average, or other aggregate function, and then groups the results by two sets of values— one down the side of the datasheet and the other across the top. Creating crosstab queries When you create a crosstab query, you specify which fields contain row headings, which field contains column headings, and which field contains values to summarize. You can use only one field each when you specify column headings and values to summarize. You can use as many as three fields when you specify row headings. Dr. Anup Kumar
47
The wizard has these benefits: It is easy to use.
Using the Crosstab Query Wizard The Crosstab Query Wizard is usually the fastest and easiest way to create a crosstab query. It does most of the work for you, but there are a few options that the wizard does not offer. The wizard has these benefits: It is easy to use. To use it, you start the wizard, and then answer a series of guided questions. It can automatically group dates into intervals. If you use a field that contains date/time data for column headings, the wizard also helps you group the dates into intervals, such as months or quarters Dr. Anup Kumar
48
It can be used as a starting point.
You can use the wizard to create the basic crosstab query that you want, and then fine-tune the query's design by using Design view. However, by using the wizard, you cannot: Use more than one table or query as a record source. Use an expression to create fields. Add a parameter prompt. Specify a list of fixed values to use as column headings.
49
Working in Design view Design view allows you more control over your query design. It supports the features that are not available in the wizard. Consider using Design view to create your crosstab query if you want to: Have more control over the process. The wizard makes some decisions for you. Use more than one table or query as a record source. Add a parameter prompt to your query. Use expressions as fields in your query. Specify a list of fixed values to use as column headings. Practice using the design grid. Dr. Anup Kumar
50
Create a crosstab query using Wizare
51
Create a crosstab query in Design view
Dr. Anup Kumar
54
Dr. Anup Kumar
57
Dr. Anup Kumar
59
Sport Quarter Sales Golf Qtr3 10 Qtr4 20 Tennis 30 50
60
Add criteria to the query
To restrict the records that are returned in the query results, you can specify one or more criteria. You can think of a query criterion as a condition that you specify for a field. The criterion specifies a condition, based on field values, that expresses what you want to include in the query, such as "show only those records where the value of City is London". Open the query in Design view. You will add a criterion to the City field so that you see only those contacts who are from London in the query results. You will also add criteria to the Address field and the Phone field, to further refine your query results. Dr. Anup Kumar
63
validation rule so that the Gender field is limited to either “M” or “F” (Male or Female). The field can also be left blank
64
Dr. Anup Kumar
67
Dr. Anup Kumar
68
Criteria Effect >234 Returns all numbers greater than 234. To find all numbers less than 234, use < 234. >="Cajhen" Returns all records from Cajhen through the end of the alphabet. Between #2/2/2007# And #12/1/2007# Returns dates from 2-Feb-07 through 1-Dec-07 (ANSI-89). If your database uses the ANSI-92 wildcard characters, use single quotation marks (') instead of pound signs (#). Example: Between '2/2/2007' And '12/1/2007' . Not "Germany" Finds all records where the exact contents of the field are not exactly equal to "Germany." The criterion will return records that contain characters in addition to "Germany," such as "Germany (euro)" or "Europe (Germany)". Not "T*" Finds all records except those starting with T. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Not "*t" Finds all records that do not end with t. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). In(Canada,UK) In a list, finds all records containing Canada or UK. Like "[A-D]*" In a text field, finds all records that start with the letters A through D. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Like "*ar*" Finds all records that include the letter sequence "ar". If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Like "Maison Dewe?" Finds all records that begin with "Maison" and contain a 5-letter second string in which the first 4 letters are "Dewe" and the last letter is unknown. If your database uses the ANSI-92 wildcard character set, use the underscore (_) instead of the question mark (?).
69
#2/2/2007# Finds all records for February 2, If your database uses the ANSI-92 wildcard character set, surround the date with single quotation marks (') instead of pound signs (#); for example, ('2/2/2007'). < Date() - 30 Uses the Date function to return all dates more than 30 days old. Date() Uses the Date function to return all records containing today's date. Between Date() And DateAdd("M", 3, Date()) Uses the Date and DateAdd functions to return all records between today's date and three months from today's date. Is Null Returns all records that contain a null (blank or undefined) value. Is Not Null Returns all records that contain a value. "" Returns all records that contain a zero-length string. You use zero-length strings when you need to add a value to a required field, but you don't yet know what that value is. For example, a field might require a fax number, but some of your customers might not have fax machines. In that case, you enter a pair of double quotation marks with no space between them ("") instead of a number. Dr. Anup Kumar
71
Dr. Anup Kumard
73
write query to show any book title with a price >10 or a sales amount <=10000
78
You will see that we have added a criteria to the dtmEnrolled field, as specified we want to delete any records that are older than two years from today's date. The criteria that is applied is: <=DateAdd("yyyy",-2,Date()) This will display only records that are older than 2 years from today's date.
80
Input Masks Input Masks Input Masks allow you to set a particular format for your field. For instance, we can set that the postal code has to be three alphanumeric characters, followed by a space, followed by three other alphanumeric characters. You will sometimes find that input masks and validation rules can be used interchangeably. Just do whatever seems easier (on a test however, do whatever the question asks!). To set an input mask, you use placeholder (or literal) characters that show the format you want for your field. Following is the table of characters (from Microsoft Office help) that can be used in input masks. Again, you do not need to memorize this table. Just use it as a reference
82
After you have done that, set 000-000-000 as the input mask
After you have done that, set as the input mask. This input masks restricts values entered into the SIN field to be of the form: 3 required digits, followed by ‘-‘, followed by 3 required digits, followed by ‘-‘, and finally 3 required digits.
83
Exercise 6 Enter an input mask for the postal code so that it restricts the format to three alphanumeric characters, followed by a space, followed by three other alphanumeric characters (for instance, T2N 1N4).
84
Parameter query
85
What is a parameter query?
When you use a parameter query, you're able to quickly enter criteria using prompts that you set up. Prompts could ask you which records you want to retrieve or the value you want to insert in a field. For example, you could insert a Regional Sales parameter that would ask for the name of the state for which you want to retrieve records. Creating a parameter query is easy. Keep reading to learn more about how to do this. Creating a parameter query First, create a new query with the fields you want to use. Or, open the query in which you want to use parameters. You need to specify which field(s) you want to use to group the query, which field(s) you want to be calculated, and which field(s) you want to use to limit the number of records displayed in the query.
86
Parameter A parameter is a piece of information you supply to a query right as you run it. Parameters can be used by themselves or as part of a larger expression to form a criterion in the query. You can add parameters to any of the following types of queries: Select Crosstab Append Make-table Update
90
In the Criteria row of the City field, type london.
Now, add two more criteria to make the results even more meaningful. Suppose that you only want to see the records in which both the address and the phone number are present. In the Criteria row of the Address field, type Is Not Null AND <>"". Do the same in the Criteria row of the Phone field. Note The criterion, Is Not Null AND <>"", is true whenever there is any known, non-empty value for the field for which it is a criterion. It is false whenever there is no known value (Null), or when the value is known to be empty (""). You can use this expression to check a field for a known, non-empty value. Switch to Datasheet view to see the results.
91
Understand ways to count data
Sum, for summing a column of numbers. Average, for averaging a column of numbers. Maximum, for finding the highest value in a field. Minimum, for finding the lowest value in a field. Standard Deviation , for measuring how widely values are dispersed from an average value (a mean). Variance, for measuring the statistical variance of all values in the column.
92
1. On the Create tab, in the Other group, click Query Design.
2. In the Show Table dialog box, double-click the table or tables that you want to use in your query, and then click Close.
93
Each field appears in a column in the query design grid.
Double-click the table fields that you want to use in your query. You can include fields that contain descriptive data, such as names and descriptions, but you must include the field that contains the values that you want to count. Each field appears in a column in the query design grid. On the Design tab, in the Results group, click Run. The results of the query are displayed in Datasheet view
94
Optionally, go back to Design view and adjust your query
Optionally, go back to Design view and adjust your query. To do so, right-click the document tab for the query and click Design View. You can then adjust the query as needed by adding or removing table fields. To remove a field, select the column in the design grid and press DELETE
96
Add calculations to the query
Open the query in Design view. From the Customers table window, drag the BirthDate field to the first blank column in the design grid. You can also double-click the field name to automatically add it in the first blank column. In the next column, in the Field row, type the expression that will calculate the age for each record. Type Age: DateDiff ("yyyy", [BirthDate], Date()). Age is the name you are using for the calculated field. If you do not supply a name, Access will use a generic name for the field, for example, EXPR1. The string following the colon (:) is the expression that supplies the values for each record. The DateDiff function calculates the difference between any two dates, and returns that difference in the specified format. The format, yyyy, returns the difference in years, and the [BirthDate] and Date() elements of the expression supply the two date values. Date is a function that returns the current date, and [BirthDate] refers to the BirthDate field in the underlying table. Note The calculation used for Age in this example is an approximation that may be slightly inaccurate, depending on the current month. Switch to Datasheet view. You see two additional fields, BirthDate and Age, in the result.
97
Summarize query values
Open the query in Datasheet view. On the Home tab, in the Records group, click Totals. Click the Total row in the Contact column. In the drop-down list, you can choose between None and Count. Because the Contact column displays text values, other functions, such as Sum and Average, are not relevant, and are therefore not available
98
The number 5 is displayed in the Total row.
Select Count to count the number of contacts that are displayed in the result. The number 5 is displayed in the Total row. 5. In the Age field, select Average. Because the Age field evaluates to a number, it supports the Sum,Average, Count, Maximum, Minimum, Standard Deviation and Variance functions. Access displays the average age in the Total row.
99
Click SQL View on the Access status bar, or right-click the query document tab and then click SQL View. Access displays the following SQL code: SELECT Customers.[Contact], Customers.[Address], Customers.[Phone], Customers.[City] FROM Customers WHERE (((Customers.[Address]) Is Not Null And (Customer.[Address])<>"") AND ((Customer.[Phone]) Is Not Null And (Customer.[Phone])<>"") AND ((Customer.[City])="london"));
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.