Thursday, April 27, 2017

Introduction to queries

Introduction to queries

When you want to review, add, change, or delete data from your database, consider using a query.

Using a query, you can answer very specific questions about your data that would be difficult to answer by looking at table data directly. You can use queries to filter your data, to perform calculations with your data, and to summarize your data. You can also use queries to automate many data management tasks and to review changes in your data before you commit to those changes.

Using queries makes many database tasks easier

In this article

Overview

Look at a subset of the data in a table

Review data from more than one table simultaneously

Ask variations of a question by using parameters with a query

Make calculations based on your data

Look at summarized or aggregate data

Create a new table by using data from other tables

Add data to a table by using data from other tables

Change data in an automated fashion

Delete data in an automated fashion

Overview

A query is a request for data results, for action on data, or for both. 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. Queries that you use to retrieve data from a table or to make calculations are called select queries. Queries that add, change, or delete data are called action queries.

This article provides basic information about queries and provides examples of the different types of queries. For more information about each type of query, search Help, or click the links in the See Also section of this article.

You can also use a query to supply data for a form or report. In a well-designed database, the data that you want to present by using a form or report is often located in several different tables. By using a query, you can assemble the data that you want to use before you design your form or report.

For more information about using a query to supply data for forms and reports, refer to the links in the See Also section, or search Help.

Note: Examples in this article use a database that was created by using the Northwind 2007 database template.

Show me how to set up Northwind 2007

  1. Click the Microsoft Office Button Office button image , and then click New.

  2. In the left pane, under Template Categories, click Local Templates.

  3. Under Local Templates, click Northwind 2007, and then click Create.

  4. Follow the directions on the Northwind Traders page (on the Startup Screen object tab) to open the database, and then close the Login Dialog window.

Top of Page

Look at a subset of the data in a table

Sometimes you may want to review all of the data from a table, but at other times, you may want to review only the data from certain fields, or you may want to review data only if certain fields meet certain criteria. To review data using criteria, you use a select query.

Suppose that you want to review a list of products and their prices. You can create a query that returns product and price information by using the following procedure:

  1. Open Northwind 2007.

  2. On the Create tab, in the Other group, click Query Design.

  3. In the Show Table dialog box, on the Tables tab, double-click Products.

  4. Close the Show Table dialog box.

  5. In the Products table, double-click Product Name and List Price to add these fields to the query design grid.

  6. On the Design tab, in the Results group, click Run.

    The query runs, and then displays a list of products and their prices.

Top of Page

Review data from more than one table simultaneously

Tables in a well-designed database bear logical relationships to each other. These relationships exist on the basis of fields that the tables have in common. When you want to review data from related tables, you use a select query.

Suppose that you want to review orders for customers who live in a particular city. Data about orders and data about customers are stored in two tables in the same database. Each table has a Customer ID field, which forms the basis of a one-to-many relationship between the two tables. You can create a query that returns orders for customers in a particular city, for example, Las Vegas, by using the following procedure:

  1. Open Northwind 2007.

  2. On the Create tab, in the Other group, click Query Design.

  3. In the Show Table dialog box, on the Tables tab, double-click Customers and Orders.

  4. Close the Show Table dialog box.

    Note the line, called a join, that connects the ID field in the Customers table to the Customer ID field in the Orders table. This line shows the relationship between the two tables.

  5. In the Customers table, double-click Company and City to add these fields to the query design grid.

  6. In the query design grid, in the City column, clear the check box in the Show row.

  7. In the Criteria row of the City column, type 'Las Vegas' (include the single quotation marks).

    Clearing the Show check box prevents the query from displaying the city in its results, and typing 'Las Vegas' in the Criteria row specifies that you want to see only records where the value of the City field is Las Vegas. In this case, the query returns only the customers that are located in Las Vegas — Company L and Company AA.

    Note that you do not have to display a field to use it with a criterion.

  8. In the Orders table, double-click Order ID and Order Date to add these fields to the next two columns of the query design grid.

  9. On the Design tab, in the Results group, click Run.

    The query runs, and then displays a list of orders for customers in Las Vegas.

  10. Press CTRL+S to save the query.

    The Save As dialog box appears.

  11. In the Query Name box, type Orders by City, and then click OK.

Top of Page

Ask variations of a question by using parameters with a query

Sometimes you may want to run a query that is only slightly different from an existing query. You can change the original query to use your new criteria, but if you frequently want to run variations of a particular query, consider using a parameter query. When you run a parameter query, the query prompts you for field values, and then uses the values that you supply to create criteria for your query.

In the previous example, you created a query that returns orders for customers who are located in Las Vegas. You can modify the query to prompt you to specify the city each time that you run the query by using the following procedure:

  1. Open Northwind 2007.

  2. Click the Shutter Bar to display the Navigation Pane.

    Note: This step is not necessary if the Navigation Pane is displayed.

  3. In the Navigation Pane, right-click the query named Orders by City (that you created in the previous section), and then click Design View on the shortcut menu.

  4. In the query design grid, in the Criteria row of the City column, delete 'Las Vegas', and then type [For what city?].

    The string [For what city?] is your parameter prompt. The square brackets indicate that you want the query to prompt for a parameter, and the text (in this case, For what city?) is the question that the prompt displays.

    Note: Neither a period (.) nor an exclamation point (!) can be used as text in a parameter prompt.

  5. Select the check box in the Show row of the City column, so that the query results will display the city.

  6. On the Design tab, in the Results group, click Run.

    The query prompts you to enter a value for City.

  7. Type New York, and then press ENTER.

    The query runs, and then displays orders for customers in New York.

    But what if you don't know what values you can specify? To make your parameter more flexible, you can use wildcard characters as part of the prompt:

  8. On the Home tab, in the Views group, click View, and then click Design View.

  9. In the query design grid, in the Criteria row of the City column, type Like [For what city?]&"*".

    In this parameter prompt, the Like keyword, the ampersand (&), and the asterisk (*) enclosed in quotation marks allow the user to type a combination of characters, including wildcard characters, to return a variety of results. For example, if the user types *, the query returns all cities; if the user types L, the query returns all cities that start with the letter "L;" and if the user types *s*, the query returns all cities that contain the letter "s."

  10. On the Design tab, in the Results group, click Run.

    At the query prompt, type New, and then press ENTER.

  11. The query runs, and then displays orders for customers in New York.

Specify parameter data types

You can also specify what type of data a parameter should accept. You can set the data type for any parameter, but it is especially important to set the data type for numeric, currency, or date/time data. When you specify the data type that a parameter should accept, users see a more helpful error message if they enter the wrong type of data, such as entering text when currency is expected.

Note: If a parameter is set to accept text data, any input is interpreted as text, and no error message is displayed.

To specify the data type for parameters in a query, use the following procedure:

  1. With the query open in Design view, on the Design tab, in the Show/Hide group, click Parameters.

  2. In the Query Parameters dialog box, in the Parameter column, type the prompt for each parameter for which you want to specify the data type. Make sure that each parameter matches the prompt that you use in the Criteria row of the query design grid.

  3. In the Data Type column, select the data type for each parameter.

Top of Page

Make calculations based on your data

Most of the time, you do not use tables to store calculated values that are based on data in the same database. For example, the Order Details table in Northwind 2007 does not store product subtotals, because the subtotal for any given product is calculated by using data that is stored in the Quantity, Unit Price, and Discount fields of the Order Details table.

In some cases, calculated values can become out-of-date, because the values that they are based on change. For example, you would not want to store someone's age in a table, because every year you would have to update the value; instead, you store the person's date of birth, and then use an expression in a query to calculate the person's age.

Use the following procedure to create a query that calculates product subtotals based on data from the Order Details table.

  1. Open Northwind 2007.

  2. On the Create tab, in the Other group, click Query Design.

  3. In the Show Table dialog box, on the Tables tab, double-click Order Details.

  4. Close the Show Table dialog box.

  5. In the Order Details table, double-click Product ID to add this field to the first column of the query design grid.

  6. In the second column of the grid, right-click the Field row, and then click Zoom on the shortcut menu.

  7. In the Zoom box, type or paste the following:

    Subtotal: ([Quantity]*[Unit Price])-([Quantity]*[Unit Price]*[Discount])

    Click OK.

    This is the calculated field. The calculated field multiplies the quantity of each product by the unit price for that product, multiplies the quantity of each product by the unit price and discount for that product, and then subtracts the total discount from the total unit price.

  8. On the Design tab, in the Results group, click Run.

    The query runs, and then displays a list of products and subtotals, per order.

  9. Press CTRL+S to save the query, and then name the query Product Subtotals.

Top of Page

Look at summarized or aggregate data

When you use tables to record transactions or store regularly occurring numeric data, it is useful to be able to review that data in aggregate, such as sums or averages.

Microsoft Office Access 2007 provides a new feature, the Total row, which allows you to review simple aggregate data in any datasheet. Add a Total row to the Product Subtotals query that you created in the previous example by using the following procedure:

  1. Run the Product Subtotals query, and leave the results open in Datasheet view.

  2. On the Home tab, in the Records group, click Totals.

    A new row appears at the bottom of the datasheet, with the word Total in the first column.

  3. Click the cell in the last row of the datasheet named Total.

    Note that an arrow appears in the cell.

  4. Click the arrow to view the available aggregate functions.

    Because the column contains text data, there are only two choices: None and Count.

  5. Select Count.

    The content of the cell changes from Total to a count of the column values.

  6. Click the adjoining cell (the second column).

    Note that an arrow appears in the cell.

  7. Click the arrow, and then click Sum.

    The field displays a sum of the column values.

  8. Leave the query open in Datasheet view.

Create a totals query for more complex summaries

The Total row in a datasheet is very useful, but for more complex questions, you use a totals query. A totals query is a select query that allows you to group and summarize data. For example, suppose that you want to see total sales per product. In a totals query, you can use Sum, an aggregate function, to see total sales per product.

Use the following procedure to modify the Product Subtotals query to make it summarize product subtotals by product.

  1. On the Home tab, in the Views group, click View, and then click Design View.

    The Product Subtotals query opens in Design view.

  2. On the Design tab, in the Show/Hide group, click Totals.

    The Totals row is displayed in the query design grid.

    Note: Although they have similar names, the Totals row in the design grid and the Total row in a datasheet are not the same:

    • You can group by field values by using the Totals row in the design grid.

    • You can add a datasheet Total row to the results of a totals query.

    • When you use the Totals row in the design grid, you must choose an aggregate function for each field. If you do not want to perform a calculation on a field, you can group by the field.

  3. In the second column of the design grid, in the Total row, select Sum from the drop-down list.

  4. On the Design tab, in the Results group, click Run.

    The query runs, and then displays a list of products with subtotals.

  5. Press CTRL+S to save the query. Leave the query open.

Create a crosstab query to add another level of grouping

Now suppose that you want to review product subtotals, but you also want to aggregate by month, so that each row shows subtotals for a product, and each column shows product subtotals for a month. To show subtotals for a product and to show product subtotals for a month, use a crosstab query.

You can modify the Product Subtotals query again so that the query returns rows of product subtotals and columns of monthly subtotals.

  1. On the Home tab, in the Views group, click View, and then click Design View.

  2. In the Query Setup group, click Show Table.

  3. In the Show Table dialog box, double-click Orders, and then click Close.

  4. On the Design tab, in the Query Type group, click Crosstab.

    In the design grid, the Show row is hidden, and the Crosstab row is displayed.

  5. In the third column of the design grid, right-click the Field row, and then click Zoom on the shortcut menu. The Zoom box opens.

  6. In the Zoom box, type or paste the following:

    Month: "Month " & DatePart("m", [Order Date])

  7. Click OK.

  8. In the Crosstab row, select the following values from the drop-down list: Row Headingfor the first column, Value for the second column, and Column Heading for the third column.

  9. On the Design tab, in the Results group, click Run.

    The query runs, and then displays product subtotals, aggregated by month.

  10. Press CTRL+S to save the query.

Top of Page

Create a new table by using data from other tables

You can use a make-table query to create a new table from data that is stored in other tables.

For example, suppose that you want to send data for Chicago orders to a Chicago business partner who uses Access to prepare reports. Instead of sending all of your order data, you want to restrict the data that you send to data specific to Chicago orders.

You can build a select query that contains Chicago order data, and then use the select query to create the new table by using the following procedure:

  1. Open Northwind 2007.

  2. To run a make-table query, you may need to enable the database content by using the Message Bar, which appears beneath the Ribbon (part of the Microsoft Office Fluent user interface) if the database is untrusted when you open it.

    Show me how to enable the database

    1. On the Message Bar, click Options.

      The Microsoft Office Security Options dialog box appears.

    2. Click Enable this content, and then click OK.

    Note: If your database is in a trusted location, the Message Bar does not appear and enabling the content is unnecessary.

  3. Close the Login Dialog form.

  4. On the Create tab, in the Other group, click Query Design.

  5. In the Show Table dialog box, double-click Order Details and Orders.

  6. Close the Show Table dialog box.

  7. In the Orders table, double-click Customer ID and Ship City to add these fields to the design grid.

  8. In the Order Details table, double-click Order ID, Product ID, Quantity, Unit Price, and Discount to add these fields to the design grid.

  9. In the Ship City column of the design grid, clear the box in the Show row. In the Criteria row, type 'Chicago' (include the single quotation marks).

    Verify the query results before you use them to create the table.

  10. On the Design tab, in the Results group, click Run.

  11. Press CTRL+S to save the query.

    The Save As dialog box appears.

  12. In the Query Name box, type Chicago Orders Query, and then click OK.

  13. On the Home tab, in the Views group, click View, and then click Design View.

  14. On the Design tab, in the Query Type group, click Make Table.

    The Make Table dialog box appears.

  15. In the Make Table dialog box, in the Table Name box, type Chicago Orders, and then click OK.

  16. On the Design tab, in the Results group, click Run.

  17. In the confirmation dialog box, click Yes to confirm.

    The new table is created, and the table appears in the Navigation Pane.

    Note: If there is already a table that has the name that you specified, that table is deleted before the query runs.

  18. On the Design tab, in the Results group, click Run.

    Because the Chicago Orders table exists, a warning dialog box appears.

  19. Click No to cancel the action and to dismiss the dialog box.

Top of Page

Add data to a table by using data from other tables

You can use an append query to retrieve data from one or more tables and add that data to another table.

Suppose that you created a table to share with a Chicago business associate, but you realize that the associate also works with clients in the Milwaukee area. You want to add rows that contain Milwaukee area data to the table before you share the table with your associate.

You can add Milwaukee area data to the Chicago Orders table that you created in the previous example by using the following procedure:

  1. Open the query named "Chicago Orders Query" in Design view.

  2. On the Design tab, in the Query Type group, click Append. The Append dialog box opens.

  3. In the Append dialog box, click the arrow in the Table Name box, and then select Chicago Orders from the drop-down list.

  4. Click OK.

    The Append dialog box closes. In the design grid, the Show row disappears, and the Append To row appears.

  5. In the design grid, in the Criteria row of the Ship City column, delete 'Chicago', and then type 'Milwaukee'.

  6. In the Append To row, select the appropriate field for each column.

    In this example, the Append To row values should match the Field row values, but that is not required for append queries to work.

  7. On the Design tab, in the Results group, click Run.

Top of Page

Change data in an automated fashion

You can use an update query to change the data in your tables, and you can use an update query to enter criteria to specify which rows should be updated. An update query provides you an opportunity to review the updated data before you perform the update.

Important: An action query cannot be undone. You should consider making a backup of any tables that you will update by using an update query.

In the previous example, you appended rows to the Chicago Orders table. In the Chicago Orders table, the Product ID field shows the numeric Product ID. To make the data more useful for reports, you may want to replace the product IDs with product names. To replace the product IDs, you must first change the data type of the Product ID field of the Chicago Orders table from Number to Text, so that the Product ID field can accept product names.

You can update the values in the Chicago Orders table by using the following procedure:

  1. Open the Chicago Orders table in Design view.

  2. In the Product ID row, change the Data Type from Number to Text.

  3. Save and close the Chicago Orders table.

  4. On the Create tab, in the Other group, click Query Design.

  5. In the Show Table dialog box, double-click Chicago Orders and Products.

  6. Close the Show Table dialog box.

  7. On the Design tab, in the Query Type group, click Update.

    In the design grid, the Sort and Show rows disappear, and the Update To row appears.

  8. In the Chicago Orders table, double-click Product ID to add this field to the design grid.

  9. In the design grid, in the Update To row of the Product ID column, type or paste the following:

    [Products].[Product Name]

    Tip: You can use an update query to delete field values by using an empty string ("") or NULL in the Update To row.

  10. In the Criteria row, type or paste the following:

    [Product ID] Like ([Products].[ID])

    The Like keyword is necessary because the fields that you are comparing contain different data types (Product ID is text data, ID is numeric data).

  11. You can review which values will be changed by an update query by viewing the query in Datasheet view.

    On the Design tab, in the Results group, click View, and then click Datasheet View.

    The query returns a list of Product IDs that will be updated.

  12. On the Design tab, in the Results group, click Run.

    When you open the Chicago Orders table, you will see that the numeric values in the Product ID field have been replaced by the product names from the Products table.

Top of Page

Delete data in an automated fashion

You can use a delete query to delete data from your tables, and you can use a delete query to enter criteria to specify which rows should be deleted. A delete query provides you an opportunity to review the rows that will be deleted before you perform the deletion.

Suppose that you are preparing to send the Chicago Orders table (updated in the previous example) to your Chicago business associate, and you notice that some of the rows contain a number of empty fields. You would like to remove these rows that contain empty fields before you send the table. You could just open the table and delete the rows manually, but you might find it helpful to use a delete query if there are more than a few rows that you want to delete and you have clear criteria for which rows should be deleted.

You can use a query to delete rows in the Chicago Orders table that do not have a value for Order ID by using the following procedure:

  1. On the Create tab, in the Other group, click Query Design.

  2. In the Show Table dialog box, double-click Chicago Orders.

  3. Close the Show Table dialog box.

  4. On the Design tab, in the Query Type group, click Delete.

    In the design grid, the Sort and Show rows disappear, and the Delete row appears.

  5. In the Chicago Orders table, double-click Order ID to add it to the grid.

  6. In the design grid, in the Criteria row of the Order ID column, type Is Null.

  7. On the Design tab, in the Results group, click Run.

Top of Page

No comments:

Post a Comment