Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Microsoft Access XP Advanced Queries

Group/Summary Operations Change Join Properties Not Equal Query Parameter Queries Working with Text IIF Queries Expression Builder Backing up Tables Action Queries (Update, Make Table, Delete, & Append) Crosstab Queries

USC - Marshall School of Business

AIS User Support

Table of Contents
GROUP/SUMMARY OPERATIONS..............................................................................................3 Using Summary Operators.............................................................................................................3 JOIN PROPERTIES .........................................................................................................................9 Linking When Data Doesnt Match................................................................................................9 NOT EQUAL BETWEEN FIELDS................................................................................................12 PARAMETER QUERIES ...............................................................................................................13 Parameter Query in a Text Field...................................................................................................13 Parameter Query Using a Range in a Number Field ......................................................................13 Parameter Query Using a Range of Dates.....................................................................................14 MANIPULATING TEXT FIELDS .................................................................................................15 Joining Text Fields (Catenation)....................................................................................................15 Display Partial Text (Truncation) ..................................................................................................15 IIF STATEMENTS.........................................................................................................................16 IIF Statements using Text.............................................................................................................16 Calculations in IIF Statements ......................................................................................................17 Nested IIF Statements .................................................................................................................18 Using OR in IIF Statements.......................................................................................................20 Using AND in IIF Statements....................................................................................................20 USING THE EXPRESSION BUILDER .........................................................................................21 BACKING UP A TABLE...............................................................................................................24 BACKING UP A DATABASE FILE .............................................................................................24 ACTION QUEIRES .......................................................................................................................25 Update Query: Raise the Credit Limit of all U.S. Customers by $500...........................................26 Update Query: Replace the Manufacturer General Foods with Bobs Foods..........................27 Make Table Query: Create a Table of Only Those Customers Living in the UK.............................28 Delete Query: Delete all UK Customers from Sweets Customers.................................................29 Append Query: Copy Records from One Table to Another ..........................................................30 CROSSTAB QUERIES ..................................................................................................................31

AccessXP-Adv_Queries.doc

April 23, 2003

Page 2 of 35

USC - Marshall School of Business

AIS User Support

GROUP/SUMMARY OPERATIONS
Group/Summary operations allow the user to perform mathematical operations on unfiltered data in a table or multiple tables, data which meets a specific criteria, or data which has been broken down into groups. Operators available are sum, count, average, standard deviation, etc. The summary operations are performed in queries and can include one or linked tables.

Using Summary Operators


Use the Totals icon when you wish to perform summary operations. Note that because the Totals icon affects the way queries normally operate, you should only activate the Totals icon when you wish to perform summary operations. When the Totals row is active, a summary operator must be placed in the Totals row beneath each field placed on the grid. When performing summary operations involving multiple tables, only have the tables necessary to complete the links present. Having tables present that are not somehow involved in creating the link can yield erroneous results.

Summary Operators: Group By: This will place identical data together in groups and then list one representative from each group in the answer. Note that if Group By is used in more than one field then Access will consider both fields as one when searching for identical data. Sum: Sums the numbers in the table or group. Count: Lists how many members are in the table or group. StDev: Finds the Standard Deviation of the fields in the table or group. Var: Finds the Variance of the fields in the table or group. Average: Finds the Average of the fields in the table or group. Min: Returns the smallest number found in the table or group. Max: Returns the largest number found in the table or group. First: Returns the data from the first record in the table or the first record in each group. Last: Returns the data from the last record in the table or the last record in each group. Where: Used when employing a criteria and summary operators. Expression: Used when employing calculations and summary operators in a query.

Using Sum: What is the Total Quantity of Products Sold? The Order Detail table keeps track of the quantities sold. 1. Select the Tables tab in the Database Window. 2. Select the Order Detail table. 3. From the menu, click on: INSERT - QUERY 4. Select Design View and then click on Ok. 5. Double click the field Quantity to place it on the grid. 6. 7. Click on the Totals icon Click in the Total row for the to perform the summary operation. Quantity field.
April 23, 2003 Page 3 of 35

AccessXP-Adv_Queries.doc

USC - Marshall School of Business

AIS User Support

8.

Change the Total operator to by clicking the down arrow and select:

Sum

9. Run the query (write the answer down for later use). Grouping & Sum: How Many of Each Candy Have Been Sold? 1. 2. 3. 4. Return to Design view. Click & drag Candy ID to the query grid. Set Candy IDs Total operator to: Group by Run the query .

You should see each Candy ID listed only once and its total quantity sold.

Grouping & Count: How Many Times has each Candy Been Ordered? 1. 2. 2. 3. Return to Design view. Add another Quantity field to the query grid. Set the Total for the newly added Quantity field to: Count Run the query .

Grouping & Linking: List the Sales People and the Total Quantity Each has Sold This involves the following tables: Order Detail, Orders, & Sweets Employees 1. 2. 3. Return to Design view. Clear the grid: EDIT - CLEAR GRID Add Orders & Sweets Employees: a. Click the icon Show Table b. Double click Orders c. Double click Sweets Employees Close the Show Table box. Set up the grid as shown: Sort by Quantity in descending order. Click Totals if its not active. Set the Total operator for First Name Last Name to: Group By Set the Quantity Total to: Sum .

4. 5. 6. 7. 8. & 9.

10. Run the query

AccessXP-Adv_Queries.doc

April 23, 2003

Page 4 of 35

USC - Marshall School of Business

AIS User Support

Grouping and Linking: How Many Orders has Each Salesperson Taken? 1. 2. 3. Return to Design view. Change the Total for Quantity Run the query . to: Count

Grouping with a Criteria: Which Customers have Placed 2 or More Orders? 1. Close the current query. 2. Click on the Tables tab. 3. Select the table: Orders 4. From the menu, click on: INSERT - QUERY 5. Select Design View then click Ok. 6. 7. 8. 9. Click on the Show Table icon. Double click: Sweets Customers Close the Show Table window. Set up the query grid as shown. .

10. Run the query

Note that Customer ID must come from the Orders table and that we could have used any field from Orders and we would have gotten the same answer. This is because Access is counting how many items exist in each group. It does not matter what the items are. However, if the fields being counted contain blanks, you will get an inaccurate count. It is therefore, a good idea to use a field such as Customer ID or Order ID that you can be fairly certain contains no blanks.

Using Where: What was each Sales Persons Total Quantity Sold in May of 1989? 1. 2. 3. 4. 5. 6. 7. 8. Return to Design view. Use the menu to clear the grid: EDIT - CLEAR GRID Click on the Show Table icon. Double click the table: Order Detail Close the Show Table window. Make sure the Total row is turned on. Set up the query grid as shown. Run the query .

Note the use of Where in the Total row beneath Order Date and that Show is not checked. This is because we are requesting a single total quantity for
AccessXP-Adv_Queries.doc April 23, 2003 Page 5 of 35

USC - Marshall School of Business

AIS User Support

each group over a range of dates.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 6 of 35

USC - Marshall School of Business

AIS User Support

Grouping with Calculations: How Much Money has Each Company Spent with You? This query will use linked tables and a calculation between two tables to arrive at a dollar amount. 1. 2. 3. 4. 5. Return to Design view. Use the menu to clear the grid: EDIT - CLEAR GRID

Click on the Show Table icon. Double click the table: General Candy Info Close the Show Table window.

6. 7.

Make sure the Total row is activated. Set up the query grid as shown.

The equation is:

Spent: [Cost Per Unit]/[Quantity]


8. Run the query .

To format the numbers with $ signs: 1. 2. 3. 4. 6. Return to Design view. Right click the equation for Spent: Select Properties from the list. In the Format box, select: Currency Rerun the query .

AccessXP-Adv_Queries.doc

April 23, 2003

Page 7 of 35

USC - Marshall School of Business

AIS User Support

Expression: By Percent, do a Breakdown of the Quantity Sold of Each Candy. This query requires that you know the total quantity sold. To get the total quantity sold, see the first query example shown in this handout.

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

From the Database window, click on the Table tab. Select the table: Order Detail From the menu, click on: INSERT - QUERY. Select Design View and click on Ok. Click on the Show Table icon. Double click the table: General Candy Info Close the View Table window. Set up the query as shown: Activate the Totals row. Set the Totals row options Right-click the equation. Select Properties. Click in the Format box. Select Percent Close Properties . .

16. Run the query

AccessXP-Adv_Queries.doc

April 23, 2003

Page 8 of 35

USC - Marshall School of Business

AIS User Support

JOIN PROPERTIES
Linking When Data Doesnt Match
This example shows what happens in a linked query when both tables do not contain the same data in the linked fields. Note that linked fields do not always have to contain exactly the same data; the purpose of this example is to increase your understanding of field links.
Below are two tables. On the left is a table that lists every product we carry. On the right is a table of only those products sold. (Some are listed more than once because they have been sold more than once in different orders.) Note that in the table on the right, we have never sold Candy ID number 2 (Milky Way). Lists every product we carry. Lists only those products sold.

When the tables are linked through their common field of Candy ID , the query produces the data below. Note that Candy ID number 2 is not listed (Milky Way). Milky Way is not listed because although it does exist in one of the tables, its Candy ID does not exist in both tables. By default, Access will only list records when the data contained in the linking fields exists in both tables. Note that this is not a bad thing, if you have not sold Candy 2, you probably would not want to list it anyway.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 9 of 35

USC - Marshall School of Business

AIS User Support

Changing Join Properties: Which Candies Havent We Sold? We would like to know which candies that we carry have never been sold. Or in other words, which candy IDs are listed in General Candy Info but not listed in Order Details? To accomplish this, we will need to change the properties of the query. 1. 2. 3. 4. 5. 6. 7. 8. From the Database window, click on the Table tab. Select the table: General Candy Info From the menu, click on: INSERT - QUERY. Select Design View and click on Ok. Click on the Show Table icon. Double click the table: Order Detail Close the Show Table window. Set up the query as follows:
This Candy ID comes from Order Detail This Candy ID comes from G.C.I.

9. Double click the line connecting the two tables. 10. Select the option: Include ALL records from General Candy Info and only those records from Order Detail where the joined fields are equal. 11. Click on Ok. 12. Run the query .

Brands that were not sold will have blanks in the Candy ID from the Order Detail table.

13. Return to Design view. 14. Add the Is Null criteria as shown. 15. Run the query again.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 10 of 35

USC - Marshall School of Business

AIS User Support

Changing Join Properties: Which Sweets Employees Have Never Taken an Order? The table Sweets Employees contains a list of all of our employees. If they have made any sales, their Employee ID would exist in the table Orders. What we would like to know is, which employees exist in our employees table but do not exist in our orders table? 1. 2. 3. 4. 5. 6. 7. 8. From the Database window, click on the Table tab. Select the table: Orders. From the menu, click on: INSERT - QUERY. Select Design View and click on Ok. Click on the Show Table icon. Double click the table: Sweets Employees Close the Show Table window. Double click the line connecting the two tables.

9. Select the option shown. 10. Click on Ok. 11. Construct the query grid as shown. 12. Run the query .

AccessXP-Adv_Queries.doc

April 23, 2003

Page 11 of 35

USC - Marshall School of Business

AIS User Support

NOT EQUAL BETWEEN FIELDS


This example demonstrates how to find two fields that do not contain matching data in corresponding records. Note that this is not the same as the examples of joins above. Here, were are not interested in the linking fields. Syntax: <>[Table].[Field]

Which Customers have a Billing Address that is Different Than Their Shipping Address? The Orders table contains the shipping addresses and the Sweets Customers table contains the billing addresses. 1. 2. 3. 4. 5. 6. 7. 8. From the Database window, click on the Table tab. Select the table: Orders. From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Click on the Show Table icon. Double click the table: Sweets Customers Close the Show Table window. This query can be constructed in two ways, see the examples below.
If the criteria is in the Address field of the Sweets Customers table, then the code refers to the Ship Address from Orders. . If the criteria is in the Ship Address field of the Orders table, then the code refers to the Address from Sweets Customers.

9.

Run the Query

AccessXP-Adv_Queries.doc

April 23, 2003

Page 12 of 35

USC - Marshall School of Business

AIS User Support

PARAMETER QUERIES
A parameter query is a query which asks the user questions when the query is executed. Parameter queries are useful when the same fields are being queried but the criteria changes slightly. To create a parameter query, simply place your question in [ ] where you would normally place the criteria.

Parameter Query in a Text Field


This parameter query will prompt the user to enter the manufacturer they are searching for. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11 12. 13. From the Database window, click on the Tables tab. Select the table: General Candy Info. From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Set up the query as shown. Run the query . Type in a manufacturer ( Nabisco for example) Press ENTER Save the query as Search by Manufacturer Close the query. In the Database window, click on the Queries tab. Double click the query Search by Manufacturer Type in: General Foods and click on Ok

Parameter Query Using a Range in a Number Field


This parameter query will prompt the user to enter the minimum cost per unit desired. 1. From the Database window, click on the Tables tab. 2. Select the table: General Candy Info 3. From the menu, click on: INSERT - QUERY. 4. Select Design View and click on Ok . 5. Set up the query as shown. 6. 7. Run the query . Type in 50 and press ENTER

AccessXP-Adv_Queries.doc

April 23, 2003

Page 13 of 35

USC - Marshall School of Business

AIS User Support

Parameter Query Using a Range of Dates


We wish to find employees who were born during a certain period. This parameter query asks the user for a beginning date and an ending date and lists only those records which match the criteria. 1. 2. 3. 4. 5. From the Database window, click on the Tables tab. Select the table: Sweets Employees From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Set up the query as shown.

6. 7. 8.

Run the query . Type in a beginning date and press ENTER. Type in an ending date and press ENTER.

Parameter Query: Multiple Criteria This query requests both a country and a credit limit using the Sweets Customers table. 1. Set up the query as shown. 2. Run the query .

AccessXP-Adv_Queries.doc

April 23, 2003

Page 14 of 35

USC - Marshall School of Business

AIS User Support

MANIPULATING TEXT FIELDS


Joining Text Fields (Concatenation)
This example demonstrates how to take to separate columns and join them together in one column. We will perform a query on the Sweets Employees table that will join Last Name followed by a comma, a space, and then First Name . 1. 2. 3. 4. 5. 6. Use the & symbol to join text fields. Surround extra characters with quotes . Field names must be in square braces [ ]. The new column should be given a name by the user followed by a colon. From the Database window, click on the Tables tab. Select the table: Sweets Employees From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Set up the query as shown. The code is: Name: [Last Name]&, Run the query .

&[First Name]

Display Partial Text (Truncation)


This example will display just the first letter of the first name and follow it with a period, a space, and then the last name. (i.e. L. Callahan instead of Linda Callahan). We will also sort by Last Name. To truncate, use the LEFT function. Syntax: Left([Field Name],Number of letters to display going left to right) Code: Name: Left([First Name],1)&. &[Last Name] 1. 2. 3. 4. 5. 6. 7. From the Database window, click on the Tables tab. Select the table: Sweets Employees From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Set up the query as shown. Note that it is sorting by Last Name in Ascending order, but that the not show. Run the query .

Last Name

field will

AccessXP-Adv_Queries.doc

April 23, 2003

Page 15 of 35

USC - Marshall School of Business

AIS User Support

IIF STATEMENTS
IIF Statements in Access are used to evaluate data based upon a predetermined condition and then take an action depending on what the evaluation found. Syntax: IIF(Condition,What to do if condition is True, What to do if condition is false)

IIF Statements using Text


This IIF statement will look at the Cost Per Unit in the General Candy Info table. If an item cost over $25, Approval is required to reorder, else it is ok to reorder. 1. 2. 3. 4. 5. 6. Text within IIF statements must be enclosed by quotes. From the Database window, click on the Tables tab. Select the table: General Candy Info From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Set up the query as shown. Run the Query . Note that you can press SHIFT + F2 on your keyboard for more room to type.

STATUS: IIF([Cost Per Unit]>50,Approval Needed, OK to Reorder)

The condition

What to do if the condition is true.

What to do if the condition is false.

In the status column, items costing $50 and under should have OK to Reorder and items costing over $50 should have Approval needed .
April 23, 2003 Page 16 of 35

AccessXP-Adv_Queries.doc

USC - Marshall School of Business

AIS User Support

Note that is was not necessary to include the

Cost Per Unit

column on the qrid.

Calculations in IIF Statements


Sweets Candies gives a volume discount when a customer orders 1,000 or more of an item. The discount is 50%. This query will involve two tables: General Candy Info which contains the Cost Per Unit & Order Detail which contains the Quantity ordered. 1. 2. 3. 4. 5. 6. 7. 8. 9. From the Database window, click on the Tables tab. Select the table: General Candy Info From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Click on the Show Tables icon. Double click the table: Order Detail Close the Show Table window. Construct the query as shown. Run the query .

Cost: IIf([Quantity]>=1000,[Quantity]*0.5,[Quantity])*[Cost Per Unit]


Condition If True If False

The IIF Statement

AccessXP-Adv_Queries.doc

April 23, 2003

Page 17 of 35

USC - Marshall School of Business

AIS User Support

Nested IIF Statements


When there are more than two possible outcomes, nested IIF statements can be used. Nested IIF statements are simply an IIF statement within an IIF statement. Exercise: We are giving bonus based on hire date Employees hired prior to 8/2/88 are given $500. Employees hired between 8/2/88 and 1/1/91 are given $100. And employees hired after 1/1/91 are given a free dinner for two. 1. From the Database window, click on the Tables tab. 2. Select the table: Sweets Employees 3. From the menu, click on: INSERT - QUERY. 4. Select Design View and click on Ok . 5. Construct the query as shown. 6. Run the Query .

Bonus: IIf([Hire Date]<#8/2/88#,"$500",IIf([Hire Date]<#1/1/91#,"$100","Free Dinner"))

Condition 1

If Condition 1 is True

Condition 2

If Condition 2 If Condition 2 is True is False

If Condition 1 is False

Notes: Access reads IIF Statements from left to right and stops reading as soon as it finds a match. For example, 1/1/66 is less than 8/2/88 which would indicate $500; however, 1/1/66 is also less than 1/1/91 which
AccessXP-Adv_Queries.doc April 23, 2003 Page 18 of 35

USC - Marshall School of Business

AIS User Support

would indicate $100, but because Access stops reading after the True part of condition 1, it never sees condition 2 and any mention of 1/1/91. Note that the IIF Statement ends in two closing round brackets. )). The number of opening and closing brackets must be equal.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 19 of 35

USC - Marshall School of Business

AIS User Support

Using OR in IIF Statements


When the Or operator is used in IIF statements, data need only meet one of the possible conditions to validate the true portion of the IIF statement. Example: Sweets Candies does business in three countries, USA, Canada, and the UK. They would like a list that states whether the country is foreign or domestic. 1. 2. 3. 4. 5. 6. From the Database window, click on the Tables tab. Select the table: Sweets Customers From the menu, click on: INSERT - QUERY Select Design View and click on Ok . Construct the query as shown. Run the query .

Status: IIf([Country]="Canada" Or [Country]="UK","Foreign","Domestic")


Condition using the OR operator. i.e. If country equals Canada or UK What to do if condition is true. What to do if condition is False.

Using AND in IIF Statements


When the And operator is used in IIF statements, data must meet all of the possible conditions to validate the true portion of the IIF statement. In this example, if a customer is from the USA and their credit limit is over $30,000, they are considered a Preferred customer, else they are a Normal customer.

Status: IIf([Country]="USA" And [Credit Limit]>30000,"Preferred","Normal")


Condition using AND True False

AccessXP-Adv_Queries.doc

April 23, 2003

Page 20 of 35

USC - Marshall School of Business

AIS User Support

USING THE EXPRESSION BUILDER


The Expression Builder is a tool that can be used to help you build equations in queries, forms, and reports. It lists all Access functions, operators, and fields.

Exercise:
To get the dollar amount on an item, we multiply: [Cost Per Unit] x [Quantity] x [Ship Rate] There are two different ship rates based on weather they are domestic or foreign customers: Domestic Customers (USA) pay 10%. Foreign Customers pay 25%. We will use the Expression Builder to create the following equation. Note that the expression builder will also place the table names in the equation. This is acceptable.

Total: IIF([Country]="USA",[COST PER UNIT]*1.10,[COST PER UNIT]*1.25)*[Quantity]


True section. (Cost with 10%) False section. (Cost with 25%)

Condition

1. 2. 3. 4. 5. 6. 7.

From the Database window, click on the Tables tab. Select the table: Orders. From the menu, click on: INSERT - QUERY. Select Design View and click on Ok . Click on the Show Tables icon. Add following tables: Order Detail, General Candy Info, and Sweets Customers Close the Show Tables window.

8.

Add the fields shown to the grid:

AccessXP-Adv_Queries.doc

April 23, 2003

Page 21 of 35

USC - Marshall School of Business

AIS User Support

9.

Click in the next available blank column in the field row (to the right of icon:

Cost Per Unit ).

10. Click on the Build

Construct your equations here. Common operators. Click add to the equation. Click a folder to view its contents. Double click folders with + signs to expand the folder.

11. 12. 13. 14. 15.

Double click the Functions folder. Click Built-in-Functions. Select the All category. Select IIF in the right column. Click on the PASTE button.

16. In the expression window, click on the <<expr>> to select it.

17. 18. 19. 20.

Double click the Tables folder. Click the table: Sweets Customers Click the field: Country Click on PASTE

21. Place the cursor after: [Country]


AccessXP-Adv_Queries.doc April 23, 2003 Page 22 of 35

USC - Marshall School of Business

AIS User Support

22. 23. 24. 25.

Click the = operator. Select the <<expr>> Type: USA (in quotes). Select <<truepart>>.

26. Click in Tables folder:General Candy Info. 27. Select the field: Cost Per Unit 28. Click on PASTE 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. Click after [Cost Per Unit]. Click on the multiplication operator: * Select the <<Expr>> code. Type: 1.10 Select <<falsepart>> Select the General Candy Info folder again. Select the field Cost Per Unit and click on PASTE Place the cursor after [Cost Per Unit] Click on the multiplication operator: * Select the <<Expr>> code. Type: 1.25

40. Click after the closing ) 41. Click the multiplication operator:

42. 43. 44. 45.

Click on the Tables folder. Select the table: Order Detail Select the field: Quantity Click on PASTE

46. 47. 46. 47.

Click in front of the equation. Type: Total: Click on Ok Press ENTER to leave the field. .

48. Run the query

AccessXP-Adv_Queries.doc

April 23, 2003

Page 23 of 35

USC - Marshall School of Business

AIS User Support

BACKING UP A TABLE
Making a backup copy of a table is invaluable if you wish to protect your data from accidental deletions. Note that this only backs up the table and not the entire database file. If you wish to back up the entire file and all the objects it contains (tables, forms, reports, queries), see below Backing up a Database File. 1. 2. 3. 4. 5. 6. 7. Click on the Tables tab in the main Database window. Select but do not open the table: General Candy Info From the menu, click on: EDIT - COPY From the menu, click on: EDIT - PASTE Type in a name for the new table. Select the option: Structure and Data Click on Ok .

A copy of General Candy Info is created within the Database window.

BACKING UP A DATABASE FILE


This uses the Windows Explorer to backup the entire database file including all tables, forms, reports, and queries it contains. 1. 2. 3. 4. 5. From the Windows Task Bar, right-mouse click the word START. From the pop-up list, select: Explorer Browse to and select the file to be copied. From the menu, click on: EDIT - COPY From the menu, click on: EDIT - PASTE

A copy of the file is created. The copy will be named: Copy of Original File Name

AccessXP-Adv_Queries.doc

April 23, 2003

Page 24 of 35

USC - Marshall School of Business

AIS User Support

ACTION QUEIRES
By default, queries are SELECT queries which means they select data but they do not alter it. ACTION queries are another type of query which do alter data in some way. It is strongly recommended that before performing an action query that you back up your table. You can not undo an action query! There are several types of action queries: Update Query Update queries can be used to make global changes to your records based upon a criteria. For example, you would like to raise the credit limit of those people who live in the USA by 10%. Delete Query Delete queries can be used to delete records that meet a specific criteria. For example, you would like to delete the records of all customers who have not make a purchase in the last five years. Make Table Query Make table queries are used to make a new table. The new table can include some or all fields from the old table(s) and some or all of the records from the old table(s). For example, you wish to make a table of only those people who have made purchases under $5. Append Query Append Queries take data from one table and add it to another. This is useful when you have two people doing data entry into the same type of table and you now wish to merge the two together.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 25 of 35

USC - Marshall School of Business

AIS User Support

Update Query: Raise the Credit Limit of all U.S. Customers by $500
This query takes what already exists in a field and alters it mathematically. Note that to include the old data in some form in the update, the old field name must be present in the calculation. 1. 2. 3. 4. 5. 6. From the Database window, click on the Tables tab. Select the table: Sweets Customers From the menu, select: INSERT - QUERY. Select Design View Construct the query as shown. Run the query to verify that this will only affect people living in the USA.

Note that if USA was not present, $500 would be added to the credit limit of all records. 7. 8. 9. Return to Design View From the menu, click on: QUERY - UPDATE QUERY Place the code in the Update To row in the Credit Limit

column.

Note that the code is: [Credit Limit]+500. If you would have typed just: +500 or 500 without the [Credit Limit] in front of it, Access would have replaced all U.S. customers credit limit with 500. 10. Run the query . 11. Click on Yes if your message reads as follows. Note that if you run this query again, you will add another $500 to the credit limits. Also note that Access does not display the results of the action query. To see the results, change the query back to a select query and run it again. 12. From the menu, click on: 13. Select: Select Query 14. Run the query . INSERT - QUERY

AccessXP-Adv_Queries.doc

April 23, 2003

Page 26 of 35

USC - Marshall School of Business

AIS User Support

Update Query: Replace the Manufacturer General Foods with Bobs Foods
This update query takes data in a text field and replaces it with other data. 1. 2. 3. 4. 5. 6. From the Database window, click on the Tables tab. Select the table: General Candy Info From the menu, select: INSERT - QUERY. Select Design View Construct the query as shown. Run the query to verify that this will only affect General Foods manufactureres.

Note that if General Foods was not present, all manufacturers would change to Bobs Foods. 7. 8. 9. Return to Design View From the menu, click on: QUERY - UPDATE QUERY Place the code in the Update To row in the Manufacturer

column.

Note that it is not necessary to include the old field name in the code. This is because we are completely replacing old data rather than altering it as in the last example. 10. Run the Query . 11. Click on Yes if your message reads as follows.

Note that Access does not display the results of the action query. To see the results, change the query back to a select query and run it again. Be sure to remove the criteria General Foods or the query will return an empty record set. (General Foods no longer exists.) 12. From the menu, click on: 13. Select: Select Query 14. Run the query . INSERT - QUERY

AccessXP-Adv_Queries.doc

April 23, 2003

Page 27 of 35

USC - Marshall School of Business

AIS User Support

Make Table Query: Create a Table of Only Those Customers Living in the UK
This query will copy only those customers who live in the UK into a new table called UK Customers. Note that you can include any columns desired in the new table but because we will be using this table in a later exercise, we will place all of the columns in the new table. 1. 2. 3. 4. 5. 6. 7. 8. From the Database window, click on the Tables tab. Select the table: Sweets Customers From the menu, select: INSERT - QUERY. Select Design View Double click the table name Sweets Customers (All fields are selected.) Click & drag any one of the selected fields to the first column of the data grid. (All fields are placed on the grid.) Move to the Country column and place the letters UK in the criteria row. Run the query to verify that only UK customers will be placed into the new table. QUERY - MAKE TABLE QUERY

9. Return to Design View 10. From the menu, click on:

11. Fill out the pop-up box as shown. 12. Click on Ok . 13. Run the Query . 14. When the information box opens, click on Yes to create the new table.

To see the new table: a. Close the query. (Save it if you wish.) b. Click on the Tables tab in the main Database window. c. Double click the new table (UK Customers) to open it.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 28 of 35

USC - Marshall School of Business

AIS User Support

Delete Query: Delete all UK Customers from Sweets Customers


From the Sweets Customers table, this query will delete the records of any customer living in the UK. 1. 2. 3. 4. 5. In the Database window, click on the Tables tab. Select the table: Sweets Customers From the menu, select: INSERT - QUERY. Select Design View Set up the query grid as shown. Note that placing Company Name on the grid was not necessary. Run the query to verify only UK customers will be deleted. Return to Design View From the menu, click on: QUERY - DELETE QUERY

6. 7. 8.

Note that a Delete row is added and the where keyword is placed in the row for you. 9. Run the query . 10. Click Yes when you get the warning about deleting rows. Note that Access does not display the results of the action query. To see the results, change the query back to a SELECT query and run it again. Be sure to remove the criteria UK or the query will return an empty record set. (Records for UK customers no longer exist.)

AccessXP-Adv_Queries.doc

April 23, 2003

Page 29 of 35

USC - Marshall School of Business

AIS User Support

Append Query: Copy Records from One Table to Another


This query will copy records from the table UK Customers to the table Sweets Customers. Append Guidelines The table being appended to should always be backed up prior to executing the append. The query is based upon the table where data is being appended (copied) from. If you get an error message when attempting to append, consider any complications caused by a keyed table. For example, if you are appending into a table that has a primary key set but you are not appending any data into keyed field, Access will not allow the append because keyed fields can not contain blanks. Another problem sometimes arises when data is being appended into the keyed field. If the data being added duplicates data that is already in the keyed field, then Access will not allow the append. When appending from one table to another, if the field names are an exact match, Access will place data from one table into its corresponding field in the other table. When the field names do not match, the user must tell Access the corresponding fields. The field names do not have to be in the same order in both tables. Not all fields (columns) need to be copied into the table. Not all records need to be copied into the new table. You can append based upon a criteria. Appending has no affect on the table being appending from but can dramatically affect the table being appended to.

1. 2. 3. 4. 5. 6. 7.

In the Database window, click on the Tables tab. Select the table: UK Customers (Created above in the Make Table Query example.) From the menu, select: INSERT - QUERY. Select Design View Double click the table name UK Customers (All fields are selected.) Click & drag any one of the selected fields to the first column of the data grid. (All fields are placed on the grid and will be appended to the Sweets Customers table.) From the menu, click on: QUERY - APPEND QUERY

8. 9.

Select Sweets Customers as the table you are appending to. Make sure Current Database is selected and click on Ok .

AccessXP-Adv_Queries.doc

April 23, 2003

Page 30 of 35

USC - Marshall School of Business

AIS User Support

This is the field being appended from. This is the table being appended from. This is the field data is being copied to. Note that if the field names between the two tables were not spelled the same, you would need to select the field name yourself from a drop down list.

10. Verify that the 11. 12. 13. 14.

From

and

To

field names match for each column.

Run the query . Click Yes when you get the message about the append taking place. Close the query and save if desired. Open the Sweets Customers table.

There should be customers listed who do live in the UK.

CROSSTAB QUERIES
A crosstab query takes data that is in a list and summarizes it into columns and rows. They are useful for performing data analysis by category. A crosstab query is not an action query and has no effect on the table it is based on. To perform a crosstab query, at least 3 different columns are needed. Crosstab queries are simple to create using the Crosstab Query Wizard. Crosstab queries can also be created manually but that procedure can be somewhat tedious.

In this example, we have a list of movies made between 1972 and 1994. The list contains the name of the movie, its rating, release date, profit made, production company, and the type of movie it is. We would like to know the total profit for each year broken down by movie rating. 1. 2. 3. 4. In the main Database window, click on the Tables tab. From the menu, click on: INSERT - QUERY Select Crosstab Query Wizard and click on Ok . When asked for the table to base the query on, select the table

MOVIES and click NEXT .

AccessXP-Adv_Queries.doc

April 23, 2003

Page 31 of 35

USC - Marshall School of Business

AIS User Support

5.

Select

Rating for the Row Headings and then click on NEXT .

6.

Select

Year

for the Column Headings and then click on NEXT .

The Row Headings have been set to Rating and the Column Headings have been set to . The data that goes where these two intersect must now be selected. 7. 8. 9. Select Profit as the field to be calculated. Select Sum as the function which is to be performed upon the profit field. Make sure Yes, include row sums is checked.
April 23, 2003

Years

AccessXP-Adv_Queries.doc

Page 32 of 35

USC - Marshall School of Business

AIS User Support

10. Click on NEXT . 11. Type a name for the query. 12. Click on FINISH .

You data is now summarized into columns and rows as shown below. Where Rating and Year intersect is the total profit for that category of movie. For example, the total profit for all G rated moves in 1972 was $109,890,890.00. Total of Profit is a special summary column which contains the total profit for all movies regardless of the year it was made, broken down by rating. For example, the total profit for all G rated movies was $2,185,869,138.00.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 33 of 35

USC - Marshall School of Business

AIS User Support

AUTOMATICALLY DELETE DUPLICATE RECORDS


This procedure will delete all duplicate records from a table leaving only one record with the original data. The process takes several steps and involves: Creating a duplicate structure of the table that contains duplicates without any data in it. Making primary keys of all the fields that contain duplicates Running an append query from the original table to the new table.

Because keyed tables do not allow duplicate records, Access will not allow any duplicates to be copied to the new table. In other words, you will get only on instance of the duplicate record.

Step A:
1. 2. 3. 4. 5. 6.

Copy the Structure of the Table Containing Duplicates

Click on the Tables tab. Right mouse click Sweets Customers and select: Copy Click the Paste button. Name the table: Sweets Customers without Duplicates Select: Structure Only Click Ok .

Step B:
1. 2. 3.

Assign Primary Keys to Duplicate Fields

Open Sweets Customers without Duplicates in Design View . Assign a primary key to the Company Name field. Save and close the table.

Step C:
1. 2. 3. 4. 5. 6. 7. 8. 9.

Append from the Original Table to the New Table

Single click the Sweets Customers table. From the menu, click: INSERT - QUERY - DESIGN VIEW In the field list box, double click the asterisk (*) to tell Access to include all columns. From the menu, select: QUERY - APPEND QUERY Select Sweets Customers without Duplicates as the table to append to. Click on Ok . Run the query . Click Yes to append all records. Click Yes when access give you an error message.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 34 of 35

USC - Marshall School of Business

AIS User Support

If you open Sweets Customers without Duplicates , it now contains records but no duplicates.

AccessXP-Adv_Queries.doc

April 23, 2003

Page 35 of 35

You might also like