Access Week 2

 

Home
Windows Essentials
Word Week 1
Word Week 2
Word Week 3
Web with Word
Excel Week 1
Excel Week 2
Excel Week 3
Excel Week 4
Excel Week 5
Access Database files
Access Week 1
Access Week 2
Access Week 3
Access Week 4
Access Week 1 Class Exercise

Queries: What they are and how they work

You use queries to view, change, and analyze data in different ways. You can also use them as the source of records for forms and reports.

The most common type of query is a select query. A select query retrieves data from one or more tables using criteria you specify, and then displays it in the order you want.

You will create a query from scratch using the Design View in this lecture. In the Design View, you specify the data you want to work with by adding tables or queries that contain the data and then by filling in the design grid.

The steps to create a Select Query using the Design View:

In the Database window, click the Queries tab, and then click New.

In the New Query dialog box, click Design View, and then click OK.

In the Show Table dialog box, click the tab that lists the objects whose data you want to work with.

Double-click the name of each object you want to add to the query, and then click Close.

If you have multiple tables or queries in the query, make sure they are connected to each other with a join line so that Microsoft Access knows how the information is related. If the tables or queries are joined, you can change the type of join to affect which records the query selects.

Add fields to the query by dragging the field names (alternatively use the double click method) from the field list to the design grid.

Refine your query by entering criteria, adding a sort order, creating calculated fields, computing the sum, average, count, or another type of total on the data it retrieves, or otherwise modifying the query's design.

To save the query, click Save button on the toolbar. Enter a name that follows Microsoft Access object-naming rules, and then click OK.

To see the results of the query, click View button the toolbar.

Insert or delete a criteria row in a query

To insert a criteria row, in query Design view, click in the row that is below where you want the new row to appear, and then click Insert Row on the Insert menu. A new row is inserted above the row that you clicked.

To delete a criteria row, click anywhere in the row, and then click Delete Rows on the Edit menu.

Enter criteria in a query to retrieve certain records

Open a query in Design view, or display the Advanced Filter/Sort window for a table, query, or form.

Click the first Criteria cell for the field you want to set criteria for.

Enter the criteria expression by typing it or by using the Expression Builder. To display the Expression Builder, right-click in the Criteria cell, and then click Build.

To enter another expression in the same field or in another field, move to the appropriate Criteria cell and enter the expression.

Criteria examples

Text Fields:

Field

Expression

Description

ShipCity

"London"

Displays orders shipped to London.

ShipCity

"London" Or "Hedge End"

Uses the Or operator to display orders shipped to London or Hedge End.

ShippedDate

Between #1/5/95# And #1/10/95#

Uses the Between...And operator to display orders shipped no earlier than 5-Jan-95 and no later than 10-Jan-95.

ShippedDate

#2/2/95#

Displays orders shipped on 2-Feb-95.

ShipCountry

In("Canada", "UK")

Uses the In operator to display orders shipped to Canada or the UK.

ShipCountry

Not "USA"

Uses the Not operator to display orders shipped to countries other than the USA.

ShipName

Like "S*"

Orders shipped to customers whose name starts with the letter S.

CompanyName

>="N"

Displays orders shipped to companies whose name starts with the letters N through Z.

OrderID

Right([OrderID], 2)="99"

Uses the Right function to display orders with OrderID values ending in 99.

CompanyName

Len([CompanyName]) >Val(30)

Uses the Len and Val functions to display orders for companies whose name is more than 30 characters long.

 

Date/Time fields:

Field

Expression

Description

OrderDate

< Date( )- 30

Uses the Date function to display orders more than 30 days old.

OrderDate

Year([OrderDate])=1996

Uses the Year function to display orders with order dates in 1996.

OrderDate

Month([OrderDate]) < 7

Uses the Month function to display orders with order dates before July.

OrderDate

Day([OrderDate]) = 1

Uses the Day function to display orders ordered on the1st of any month.

 

Null or 0-length string test

Field

Expression

Description

ShipRegion

Is Null

Displays orders for customers whose ShipRegion field is Null (blank).

ShipRegion

Is Not Null

Displays orders for customers whose ShipRegion field contains a value.

Fax

" "

Displays orders for customers who don't have a fax machine, indicated by a zero-length string value in the Fax field instead of a Null (blank) value.

 

Using part of a field value

Field

Expression

Displays

ShipName

Like "S*"

Orders shipped to customers whose names start with the letter S.

ShipName

Like "*Imports"

Orders shipped to customers whose names end with the word "Imports".

ShipName

Like "[A-D]*"

Orders shipped to customers whose names start with A through D.

ShipName

Like "*ar*"

Orders shipped to customers whose names include the letter sequence "ar".

ShipName

Like "Maison Dewe?"

Orders shipped to the customer with "Maison" as the first part of its name and a 5-letter second name in which the first 4 letters are "Dewe" and the last letter is unknown.

 

Domain aggregate functions

Field

Expression

Description

Freight

> ( DStDev ("[Freight]", "Orders") + DAvg ("[Freight]", "Orders") )

Uses the DAvg and DStDev functions to display all orders for which the freight cost rose above the mean plus the standard deviation for freight cost.

Quantity

>DAvg("[Quantity]", "Order Details")

Uses the DAvg function to display products ordered in quantities above the average order quantity.

 

Using OR and AND

 

 

 

 

 

 

 

 

 

               Figure 1

Figure 1 matches to the query which displays the title, author and year attributes for those books that have been published in 1996 or 1997.

 

 

 

 

 

                Figure 2

Figure 2 corresponds to displaying the title, author and year fields for those records that were published in 1997 or that were written by Ozlem.

 

 

 

 

 

 

 

                Figure 3

Figure 3 matches to displaying the title, author and the year published for those books who were written by Ozlem and published in 2000.

Defining the sort order for the results of a query

Open a query in Design view or display the query.

To sort on more than one field, first arrange the fields in the design grid in the order you want the sorts performed. Microsoft Access sorts on the leftmost field first, then on the next field to the right, and so on. For example, to sort on the LastName field first and then on the FirstName field, the LastName field must be to the left of the FirstName field in the grid.

In the Sort cell for each of the fields you want to sort on, click an option.

To see the results of the query, click View button on the toolbar.

Displaying calculated information for a table

You perform calculations in a query using:

Predefined calculations, called "totals," to compute the following amounts for groups of records or for all the records combined in the query: sum, average, count, minimum, maximum, standard deviation, or variance.

q A custom calculation to perform numeric, date, and text calculations on each record using data from one or more fields. You need to create a new calculated field directly in the design grid for these types of calculations.

Instead of displaying a calculation's results, you can use them:

As criteria to determine the records the query selects or to determine which records to perform an action on.

To update data from an update query.

You can create a new field that displays the results of a calculation you define with an expression.

Open the query in Design view.

Do one of the following:

Type an expression in an empty cell in the Field row. If the expression includes a field name, you must place brackets around the name.

If you need help creating the expression, use the Expression Builder. To display it, right-click in the Field cell where you're adding the calculated field, and then click Build.

After you press ENTER or move to another cell, Microsoft Access enters the default field name ExprN, where N is an integer incremented for each new expression field in the query. The name appears before the expression and is followed by a colon. In a datasheet, this name is the column heading.

You can select ExprN and type a more descriptive name, such as NewPrice.

If the expression includes one or more aggregate functions (Sum, Avg, Count, Min, Max, StDev, or Var), and if the design grid includes another field or fields that you want to use for grouping, click Totals (the sigma sign) on the toolbar (unless the Total row is already displayed). Leave Group By in the Total cell for the grouping field, and in the calculated field, change Group By to Expression.

If you want, do any of the following to complete the query:

Enter criteria to affect the calculation..

Sort the results

Set field properties such as Format (since the field doesn't inherit properties from the underlying table).

 

NOTE: To enter or view an entire expression without scrolling, press SHIFT+F2 to display the Zoom box.

 

Sample1:

AGE:(Date()-[BirthDate])/365

 

Sample2:

GPA:[QualityPoints]/[Credits]

Sample Queries:

1. Display all the available information for the students, including the department names. The result should be sorted in descending order of the department names.

This query will yield in the following table:

 

All Information sorted in descending order of major

SSN

First Name

Last Name

Address

City

State

BirthDate

Gender

Credits

QualityPoints

Financial Aid

Campus

Major

888-88-8888

Your Name

Your Surname

Bilkent

Ankara

         

Yes

1

Political Sciences

919-19-1919

New

Student

CTP, Bilkent

Ankara

 

1/ 1/80

M

10

35

Yes

2

Other

666-66-6666

George

Master

Sunset Bulvard

Los Angeles

CA

1/ 1/60

M

15

40

No

3

Other

555-55-5555

Saygin

Ozgu

X

Boston

 

10/10/76

M

20

78

Yes

3

Other

222-22-2222

Didem

Bakar

Cayyolu

Ankara

 

10/ 4/69

F

10

35

Yes

2

Other

444-44-4444

Seda

Unlu

Lauderdale

Florida

FL

7/12/74

F

15

50

No

1

Management

777-77-7777

Aysin

White

Y

San Fransisco

CA

2/ 2/62

F

18

60

No

1

Computer Science

111-11-1111

Ozlem

Ozgu

Cayyolu

Ankara

 

2/12/65

F

10

40

Yes

1

Computer Science

 

The corresponding design view is as follows:

 

 

2. Display the name, surname and department for all students, sorted in ascending order of department names.

 

The result of this query would look like:

 

Department List

First Name

Last Name

Major

Aysin

White

Computer Science

Ozlem

Ozgu

Computer Science

Seda

Unlu

Management

New

Student

Other

George

Master

Other

Saygin

Ozgu

Other

Didem

Bakar

Other

Your Name

Your Surname

Political Sciences

 

The design of this query should be as follows:

 

 

3. Display the name, surname, credits, quality points and GPA(label) for each student. Note that GPA = Quality Points / Credits. Format GPA to 2 decimal places.

 

 

The result of this query looks like:

GPA

First Name

Last Name

Credits

QualityPoints

GPA

Ozlem

Ozgu

10

40

4.00

Didem

Bakar

10

35

3.50

Seda

Unlu

15

50

3.33

Saygin

Ozgu

20

78

3.90

George

Master

15

40

2.67

Aysin

White

18

60

3.33

Your Name

Your Surname

 

 

 

New

Student

10

35

3.50

 

 

The design of this query should be as follows:

 

4. Display the number of students that are receiving financial aid and the number of students that are not receiving financial aid according to their classification.

 

The result of this query will be as follows:

Number of Students with and without financial aid

Financial Aid

Total Of Financial Aid

Yes

6

No

3

 

 

The design of this query should be as follows:

 

5. Display the first name, last name and age of all the students. Sort the result from oldest student to youngest. Note that AGE should be calculated by using the formula:

AGE=INT( (DATE() – BirthDate) / 365 )

 

 

The result of this query is:

Sorted on AGE

First Name

Last Name

Age

George

Master

40

Aysin

White

38

Ozlem

Ozgu

35

Didem

Bakar

31

Seda

Unlu

26

Saygin

Ozgu

24

New

Student

20

Your Name

Your Surname

 

 

The design of this query is

 

6. Display name , surname, and birth date for those students who are younger than 35.

 

The result of this query is as follows:

Younger than 35

First Name

Last Name

BirthDate

New

Student

1/ 1/80

Saygin

Ozgu

10/10/76

Didem

Bakar

10/ 4/69

Seda

Unlu

7/12/74

 

There may be several solutions to this query. Two that follows are: