Sunday, June 28, 2015

Learning select query in access

Introduction

A select query is a type of database object that shows information in Datasheet view. A query can get its data from one or more tables,
from existing queries, or from a combination of the two.
The tables or queries from which a query gets its data are referred to as its recordsource.
Whether you create simple select queries by using a wizard or by working in Design view, the steps are essentially the same. You choose the recordsource that you want to use and the fields that you want to include in the query — and, optionally, you specify criteria to refine the results.
After you have created a select query, you run it to see the results. Running a select query is simple — you just open it in Datasheet view. You can then reuse it whenever you need, for example, as a recordsource for a form, report, or another query.
NOTE   For more information about using a query as a recordsource for a form or report, see the article Use a query as a recordsource for a form or report.
There are several types of query, each serving a different purpose. For example, a select query displays data. An action query changes the data in its datasource, or creates a new table. A parameter query prompts you to supply criteria when you run it. This topic only covers select queries.
NOTE   This topic describes how to create select queries that return data from a single table. If you want to create queries that return data from two or more tables, see the article Create a query based on multiple tables.

Create a select query

A select question is employed to form subsets of information that you simply will use to answer specific queries. It also can be wont to offer knowledge to different info objects. Once you produce a choose question, you'll use it whenever you would like.

This topic explains a way to produce an easy choose question that searches the info in a very single table. you may conjointly learn the way to reinforce the question by process record criteria and adding calculated values.

Enter the sample data manually

  1. On the Create tab, in the Tables group, click Table.
    Office Access 2007 adds a new, blank table to your database.
    NOTE   You do not need to follow this step if you open a new, blank database, but you will need to follow it whenever you need to add a table to the database.
  2. Double-click the first cell in the header row and type the name of the field in the sample table.
    By default, Access denotes blank fields in the header row with the text Add New Field, like so:
    A new field in a datasheet
  3. Use the arrow keys to move to the next blank header cell and then type the second field name (you can also press TAB or double-click the new cell). Repeat this step until you enter all field names.
  4. Enter the data in the sample table.
    As you enter the data, Access infers a data type for each field. Each field in a table has a specific data type, such as Number, Text, or Date/Time. Data types help ensure accurate data entry and help to prevent mistakes, such as using a telephone number in a calculation. You can specify the data type for each field in a table, and can change a field's data type under certain circumstances. For this sample table, you should let Access infer the data type.
  5. When you finish entering the data, click Save
    Keyboard shortcut  Press CTRL+S.
    The Save As dialog box appears.
  6. In the Table Name box, enter Customers, and then click OK.

Copy the table to a spreadsheet program and then import it into Access
  1. Start your spreadsheet program and create a new, blank file. If you use Excel, a new, blank workbook is created by default.
  2. Copy the sample table provided in the previous section and paste it into the first cell of the first worksheet.
  3. Using the technique provided by your spreadsheet program, name the worksheet Customers.
  4. Save the spreadsheet file to a convenient location and go to the next steps.
Import the table into Access
  1. In a new or existing database:
    On the External Data tab, in the Import group, click Excel.
    -or-
    Click More, and then select a spreadsheet program from the list.
    The Get External Data - Program Name Spreadsheet dialog box appears.
  2. Click Browse, open the spreadsheet file that you created in the previous steps, and then click OK.
    The Import Spreadsheet Wizard starts.
  3. By default, the wizard selects the first worksheet in the workbook (Customers, if you followed the steps in the previous section), and data from the worksheet appears in the lower section of the wizard page. Click Next.
  4. On the next page of the wizard, select First row contains column headings, and then click Next.
  5. The next page of the wizard offers you an opportunity to change field names and data types or to omit fields from the import operation, by using the text boxes and lists under Field Options. You should not do this for this example. Click Next.
  6. On the next page of the wizard, in the Field Options box, select Yes (No Duplicates) from the Indexed list, and select Long Integer from the Data Type list. Click Next to continue.
  7. On the next page of the wizard, select the Choose my own primary key option, choose CustomerID from the list, and then click Next.
  8. By default, Access applies the name of the worksheet to your new table. Make sure that the table is namedCustomers, and then click Finish.
  9. On the last page of the wizard, you have the option of saving the import steps for later reuse. Because you are importing a sample table, it is not recommended that you save the import steps.
NOTE   If you don't have a spreadsheet program, you can copy the sample data to a text editor, such as Notepad. For more information about importing text data, see the article Import or link to data in a text file.

Build the query

First, you will use a wizard to create the query, based on the sample table that you just created. Then, you will enhance the query in Design view. At each step, you can review the SQL statement that is automatically generated by the steps that you take.
  1. On the Create tab, in the Other group, click Query Wizard.
  2. In the New Query dialog box, click Simple Query Wizard, and then click OK.
  3. Under Tables/Queries, click the table that has the data that you want to use. In this case, click Table: Customers. Note that a query can also use another query as a recordsource.
  4. Under Available Fields, double-click the ContactAddressPhone, and City fields. This adds them to theSelected Fields list. When you have added all four fields, click Next.
  5. Name the query London Contacts, and then click Finish.
    Access displays all of the contact records in Datasheet view. The results show all of the records, but show only the four fields that you specified in the query wizard.

Step-by-Step: Select Query


What you will learn:to design a select query manually
to add all fields from a table at once to grid
to clear the design grid
to add fields to design grid
to move columns in a query
to use criteria in a select query
to combine criteria in a select query
to find Null or Not Null values
to use Like operator
to name and save a query

Start with:  Class disk, Project database open.
First you will create and modify a basic Select query. Then you will experiment with different types and combinations of criteria.

Icon: Design  Query Design View

  1. Database Window: Staff table selectedWith the Projects database open, in the Database Window, select the Staff table.
     
  2. Button: New Object = QueryClick on the New Objects button and select   Query .
    Dialog: New Query The New Query dialog  appears.
     
  3. Select Design View.
    The Query Design View opens with the Staff table already showing in the top part of the window.  The query grid at the bottom is blank.
     
    Query Design View: Staff table, no fields selected

Include All Fields in Query

You add fields to the query by dragging them from the table at the top and dropping them onto the grid. You can drag more than one at a time.
  1. Animation: Drag asterisk to Design gridMove your  mouse pointer over the * at the top of the list of fields in the Staff table.
     
  2. Drag the * down to the first column and drop.
    The image at the right is an animation. Refresh this window to see it run again.

    The * asterisk represents all of the fields in the table. 
     
  3. Click the Run button Button: Run to execute this query. You will see all of the fields and all of the records in the Staff table.
    Datasheet View: Query - all fields from Staff table
    Of course this query is not very useful! You might as well have used the table itself.
  4. Icon: Design  Switch back to the Query Design View by clicking the View button Button: Views - Design (2003).
     
  5. Menu: Edit | Clear gridFrom the menu select  Edit | Clear Grid .
    The grid is now blank again. This command is especially useful when there too many fields to select them all easily.Icon: Keyboard Remove a column: You can also select the columns you don't want and press the Delete key.
     

Add Fields to Query Design Grid

Recall that sorting rearranges the records while using criteria hides some records.
When selecting fields to drag to the design grid, you can use the normal selection methods.
  • Single field: Drag any single field.
  • Adjacent fields: Hold SHIFT down to select all items between the two you click on.
  • Non-adjacent fields: Hold CTRL down to select items individually which are not next to each other.
  1. Single field:
    Click
     on the field EmployeeID and drag it down to the design grid and drop it on the first column.
     
  2. Staff table in query design. FirstName field is selected.Multiple fields:
    1. Click on the field FirstName.
      Scroll, if necessary, until the field LastName shows.
       
    2. Hold the SHIFT key down and click on the field LastName.
      Three fields are selected: FirstNameMiddleName, and LastName.
       
    3. Drag the selection down to the design grid and drop on the second column.
      All three fields appear, in the same order as in the table list.
    Query Design View: 4 fields from Staff table in grid

Sort: Multiple Fields

You will usually need to kind many fields in your question. The order of the columns is very important. Sorting and criteria ar applied beginning with the left-most column and moving to the correct.
  1. Click in the Sort row in the second column, FirstName.
     
  2. Query Design View: sort ascendingClick on the arrow that appears to open the list of choices and select Ascending
     
  3. Repeat for the fields MiddleName and LastName.
    Query Design View: three name fields sorted ascending
  4. Icon: Datasheet Switch to Datasheet view by clicking the View button Button: View - Datasheet.
    TipBe careful of using the Run button instead of the View button to switch to datasheet view. When your query is an action query, you will want to view the datasheetbefore actually performing the action!
    Query Design View: Sort Ascending - FirstName, MiddleName, LastName
    Hmmm. The first names are in alphabetical order. What we really want is to sort on the LastName and then on FirstName and then on MiddleName. Happily, this is easy to fix!
  5. Icon: Design  Switch back to Query Design View by clicking the Views button Button: Views - Design (2003).
    (Isn't it handy that this button changes as you change views?)
     
  6. Move your mouse pointer over the top of the LastName column until it turns into the Select Column shape Pointer: Select Column and then click.
    The whole column is selected.
     
  7. Query Design View: Select columnPosition your mouse pointer over the top of the LastName column until it changes to the Select shape Pointer: Select
     
  8. Query Design View: dragging column to new positionDrag to the left.
    The mouse pointer changes to the dragging shape Pointer: Drag.
    A black bar between two columns shows you where dropping will place the column that you are dragging.
     
  9. Query Design View: LastName column movedDrop to the left of the FirstName column.
    The LastName column moves.
     
  10. Icon: Datasheet Switch to datasheet view. Aha! Now you have the sort order that you need. Of course since none of the first or middle names are the same, it is hard to be sure!
Query Datasheet View: Names are sorted

Set Criteria

To select just some of the records, you need to enter one thing within the Criteria row within the question style read. solely records that match those rules are going to be shown within the datasheet.
To make things a little a lot of attention-grabbing, let's add a field to the question.
  1. Icon: Design  Switch back to the Query Design View.
     
  2. Scroll the table fields list at the top of the window until you see the field Country/RegionDrag the field and drop it on the second column.
    Unexpectedly, this field does not replace the second column.
    The new field appears between the Employee ID and Last Name columns.
     
  3. Query Design View: Criteria ='Argentina'In the Criteria row, type Argentina in the second column and press TAB to exit the cell.
    Access adds double quote marks around your text automatically after you exit the cell.
    Tip You did not have to type an = before the value. Access assumes that it is there in the Criteria row unless you type something else, like < or >, for example.
     
  4. Icon: Run Run the query. Only records with Argentina in the second column are showing.
    Query Datasheet View: Staff - Country/Region = Argentina

Multiple Criteria Rows

You can use as many various criteria in your question as you wish and in any combination.
The records in an exceedingly query's results datasheet should match the entries in one whole row within the Criteria section. Each row, however, could be a separate set of criteria.
  1. Icon: Design  Switch back to the Query Design View.
     
  2. Query Design View: Multiple criteriaIn the first Criteria row in the first column, type <5.
     
  3. In the second Criteria row in the first column, type >5.
    You now have two different criteria. The query will display records for which:
    • EmployeeID < 5 AND Country/Region = "Argentina"
      OR
    • EmployeeID > 5
       
  4. Icon: Run Run the query.
    Eight of the nine records fit one or the other of the two criteria sets. Records 6, 7, and 8 do not have Argentina as their Country/Region, but they do have EmployeeID numbers > 5. The choice of criteria did not reveal anything interesting, but it did show what can happen when you choose badly!Notice that the records are not sorted by which of the criteria rows they satisfied but on the name fields, as before.
    Query Datasheet View: multiple criteria

Using OR for Criteria for a Field

You can combine criteria for a single field with OR, such as:
     >15 OR <5
    "Chavez" OR "Fuller"
  1. Icon: Design  Switch back to Query Design View.
     
  2. Query Design View: combining criteria for a single field: Argentina Or AustraliaDelete the criteria in column 1.
     
  3. In column 2, edit the criteria to read  "Argentina" Or "Australia" .
     
  4. Icon: Run Run the query.
    Six records match either Argentina or Australia.
    Query Datasheet View: Criteria - Argentina or Austalia
    TipAlternate method: You would get the same results by putting Argentina and Australia on separate Criteria rows. However, if there are also criteria for other columns, you would have to repeat those entries on the second row.

Using NOT

To eliminate records that match a value, the NOT operator is handy.
  1. Icon: Design  Switch back to Query Design View.
     
  2. Query Design View: Not "usa"Replace the entry in the Criteria row for column 2 with Not "usa".
     
  3. Icon: Run Run the query. You get the same results as before! The only values available in the Country/Region field right now are Argentina, Australia, and USA. So Not "usa" is the same thing as "Argentina" Or "Australia"

    TipNote: You did not have to match the capitalization of the value USA.

Finding Null or Non-Null Values

It is common to look tables for blank values. These could also be Null or zero-length strings. within the Table style read, you'll be able to opt for whether or not or to not permit those sneaky zero-length strings. The default is N, thus none of the fields within the employees table area unit allowed to carry a zero-length string.
  1. Icon: Design  Switch back to Query Design View.
     
  2. Delete the entry in the Country/Region criteria row.
     
  3. Query Design View: MiddleName  - Is NullIn the Criteria row for MiddleName, type Is Null.
     
  4. Icon: Run Run the query.
    Only two records are missing a middle name. 
     Query Datasheet View: MiddleName is null
     
  5. Icon: Design  Switch back to Query Design View and change the criteria to Is Not Null.
     
  6. Icon: Run Run the query.
    This query now shows the 7 records which do have a value for MiddleName.
TipFinding Null or zero-length string: You can combine two criteria if you do not know whether or not the field allows zero-length strings, like Is Null Or "".

Using Like

Sometimes you want to see records that match a pattern rather than matching a particular value exactly. For example, you might want to see all names that start with L.
With the Like operator you can create a pattern using wildcard characters. This is a very flexible and powerful method.
  1. Icon: Design  Switch back to Query Design View.
     
  2. Delete the existing criteria.
     
  3. Query Design View: criteria - Like "g"In the Criteria row in the LastName column, type Like "g*".
    The asterisk * is a wildcard character which stands for "any number of characters". So this criterion will match any text value that has the letter g as the firstcharacter. Without the *, the query would match only text that had g as the only character.
     
  4. Query Datasheet View: Criteria Like'g*'Icon: Run Run the query.
    Two last names start with the letter g.
     
  5. Icon: Design  Switch back to Query Design View.
     
  6. Query Design View: Like ??????Edit the criterion to read Like "??????".
    The question mark ? is a wildcard character that stands for 1 character. So this criterion asks for values with exactly 6 characters.
     
  7. Icon: Run Run the query.
    Two last names have exactly 6 characters.
    Query Datasheet View: Like ??????

Save and Name a Query

Later it will be useful to you to be able to tell a query from a table from just its name. Queries and tables are shown alphabetically in the lists from which you choose a source for your forms and reports.

Naming objects:

Many database programmers start the name of a database object with an abbreviation for the kind of object it is, resulting in awful names like tblStaff for a table or qryStaffNames for a query or rptStaff for a report. Such names can be useful when writing the small programs (macros and procedures) that the programmer uses to control how the database behaves. However, recently programmers are getting away from that style of naming. Programmers generally also avoid using spaces in names to make it easier on them to write their programs.
  1. Icon: Design  Switch back to Query Design View.
     
  2. Remove all of the criteria.
     
  3. Dialog: Save As - Query1 as QSort Staff NamesFrom the menu select  File | Save As 
    The Save As dialog appears. Notice that you are not saving the database file, just the query. You cannot use Save As on the database as a whole! Quite different from other programs.
     
  4. Name your query QSort Staff Names. 
  5. Click on OK to save the query and close the dialog.
     
  6. Close the query by clicking its Close button Button: Close.

No comments: