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.

 Note   Aggregate query functions, such as Sum or Count, are not available in Web queries.

Using queries makes many database tasks easier

In this article


Overview

This article provides basic information about queries and provides examples of the different types of queries.

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.

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.

Open an existing query

If you are not familiar with the Navigation Pane, you may not know how to open a query that already exists. The Navigation Pane is a feature that replaces the Database Window from versions prior to Access 2007. You'll see the Navigation Pane along the left side of your screen.

To open any database object, including a query, you can double-click the object in the Navigation Pane.

Use the Northwind database to follow along with examples

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

  1. Click the File tab, and then click New.
  2. In the middle pane, under Available Templates, click Sample Templates, and then click Northwind.
  3. In the right pane, review the name for the database file in the File Name box, and make any changes to the name. You can also browse for a different file location by clicking the folder icon.
  4. Click Create.
  5. 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 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 some of the data in a table, 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 the Northwind database that you previously set up by using these steps.
  2. On the Create tab, in the Query 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 (design grid: The grid that you use to design a query or filter in query Design view or in the Advanced Filter/Sort window. For queries, this grid was formerly known as the QBE 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 Top of Page

Review data from more than one table simultaneously

Tables in a well-designed database bear logical relationships (relationship: An association that is established between common fields (columns) in two tables. A relationship can be one-to-one, one-to-many, or many-to-many.) 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 (one-to-many relationship: An association between two tables in which the primary key value of each record in the primary table corresponds to the value in the matching field or fields of many records in the related table.) 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 the Northwind database that you previously set up by using these steps.
  2. On the Create tab, in the Query 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 and the Customer ID field in the Orders table. This line shows the relationship between the two tables.

  1. In the Customers table, double-click Company and City to add these fields to the query design grid.
  2. In the query design grid, in the City column, clear the check box in the Show row.
  3. In the Criteria row of the City column, type Las Vegas.

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.

  1. 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.
  2. 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.

  1. Press CTRL+S to save the query.

The Save As dialog box appears.

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

Top of Page Top of Page

Ask variations of a question by using parameters

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 the Northwind database that you previously set up by using these steps.
  2. Press F11 to display the Navigation Pane.

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

  1. 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.
  2. 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 ask for input, and the text (in this case, For what city?) is the question that the parameter prompt displays.

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

  1. Select the check box in the Show row of the City column, so that the query results will display the city.
  2. On the Design tab, in the Results group, click Run.

The query prompts you to enter a value for City.

  1. 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:

  1. On the Home tab, in the Views group, click View, and then click Design View.
  2. 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."

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

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

  1. 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 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 the Northwind database that you previously set up by using these steps.
  2. On the Create tab, in the Query 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.

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

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

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

Top of Page 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.

Access allows you to review simple aggregate data in any datasheet (datasheet: Data from a table, form, query, view, or stored procedure that is displayed in a row-and-column format.) by adding a Total row. A Total row is a row at the bottom of the datasheet that can display a running total or other aggregate value.

 Note   You cannot add a Total row to the datasheet of a Web query.

You can 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 (Datasheet view: A view that displays data from a table, form, query, view, or stored procedure in a row-and-column format. In Datasheet view, you can edit fields, add and delete data, and search for data.).
  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.

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

Note that an arrow appears in the cell.

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

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

  1. Select Count.

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

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

Note that an arrow appears in the cell.

  1. Click the arrow, and then click Sum.

The field displays a sum of the column values.

  1. 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 (aggregate function: A function, such as Sum, Count, Avg, or Var, that you use to calculate totals.), to see total sales per product.

 Note   You cannot use aggregate functions in a Web query.

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.

  1. 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.
  1. In the second column of the design grid, in the Total row, select Sum from the drop-down list.
  2. On the Design tab, in the Results group, click Run.

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

  1. 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 (crosstab query: A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information: one down the left side of the datasheet and the other across the top.).

 Note   A crosstab query cannot be displayed in a web browser.

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.

  1. 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.
  2. In the Zoom box, type or paste the following:

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

  1. Click OK.
  2. 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.
  3. On the Design tab, in the Results group, click Run.

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

  1. Press CTRL+S to save the query.

Top of Page 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.

 Note   A make-table query cannot be run in a web browser.

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 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 the Northwind database that you previously set up by using these steps.
  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 if the database is untrusted when you open it.

ShowShow me how to enable the database

  • On the Message Bar, click Enable content.

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

  1. Close the Login Dialog form.
  2. On the Create tab, in the Query group, click Query Design.
  3. In the Show Table dialog box, double-click Order Details and Orders.
  4. Close the Show Table dialog box.
  5. In the Orders table, double-click Customer ID and Ship City to add these fields to the design grid.
  6. In the Order Details table, double-click Order ID, Product ID, Quantity, Unit Price, and Discount to add these fields to the design grid.
  7. 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.

  1. On the Design tab, in the Results group, click Run.
  2. Press CTRL+S to save the query.

The Save As dialog box appears.

  1. In the Query Name box, type Chicago Orders Query, and then click OK.
  2. On the Home tab, in the Views group, click View, and then click Design View.
  3. On the Design tab, in the Query Type group, click Make Table.

The Make Table dialog box appears.

  1. In the Make Table dialog box, in the Table Name box, type Chicago Orders, and then click OK.
  2. On the Design tab, in the Results group, click Run.
  3. 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.

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

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

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

Top of Page 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.

 Note   An append query cannot be run in a web browser.

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.
  1. In the Append dialog box, click the arrow in the Table Name box, and then select Chicago Orders from the drop-down list.
  2. Click OK.

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

  1. In the design grid, in the Criteria row of the Ship City column, delete 'Chicago', and then type 'Milwaukee'.
  2. 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.

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

 Note    While running a query that returns a large amount of data you might get an error message indicating that you will not be able to undo the query. Try increasing the limit on the memory segment to 3MB to allow the query to go through.

Top of Page 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.

 Note   An update query cannot be run in a web browser.

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 Query 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.

  1. In the Chicago Orders table, double-click Product ID to add this field to the design grid.
  2. 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.

  1. 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).

  1. 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.

  1. 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 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.

 Note   A delete query cannot be run in a web browser.

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 Query 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.

  1. In the Chicago Orders table, double-click Order ID to add it to the grid.
  2. In the design grid, in the Criteria row of the Order ID column, type Is Null.
  3. On the Design tab, in the Results group, click Run.

Top of Page Top of Page

Try Office 2010 today!

 
 
Maikakapit sa:
Access 2010