access doc 1 notes

50
MICROSOFT ACCESS Page 1 WHAT IS DATABASE?  A collection of data and objects related to a particular topic or purpose . A Microsoft Access database may contain tables, queries, forms, reports, macros, modules, and shortcuts to data access pages. E.g. Telephone directory, Student Information system database, Bank accounting system database, Library system database, Supermarket database, etc..  The Microsoft Jet database engine manages data in tables that reside in the database.  Data in linked tables may reside in another Access database, in an external data source such as dBASE or Microsoft Excel, or in an ODBC data source such as Microsoft SQL Server. DBMS (Database management system): is a software program in which you can create and maintain databases. Examples of commercially used DBMS are: MS Access 2007, Oracle 10i, MS SQL server, IBM DB2 etc. WHAT IS TABLE?  The fundamental structure of a relational database management system .  In Microsoft Access, a table is an object that stores data in records (rows) and fields (columns). The data is usually about a particular category of things, such as employees or orders. WHAT IS QUERY?  A question about the data stored in your tables, or a request to perform an action on the data . A query can bring together data from multiple tables to serve as the source of data for a form, report, or data access page. WHAT IS FORM?  A Microsoft Access database object on which you place controls for taking actions or for entering, displaying, and editing data in fields. WHAT IS REPORT?  A Microsoft Access database object that prints information formatted and organized according to your specifications .  Examples of reports are sales summaries, phone lists, and mailing labels. WHAT IS RELATIONAL DATABASE?  A type of database or database management system that stores information in tables (that is, rows and columns of data) .

Upload: pratikbansal11

Post on 06-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 1/50

MICROSOFT ACCESS

Page 1

WHAT IS DATABASE? 

  A collection of data and objects related to a particular topic or purpose . AMicrosoft Access database may contain tables, queries, forms, reports, macros,modules, and shortcuts to data access pages.

E.g. Telephone directory, Student Information system database, Bank accountingsystem database, Library system database, Supermarket database, etc..

  The Microsoft Jet database engine manages data in tables that reside in thedatabase.

  Data in linked tables may reside in another Access database, in an external datasource such as dBASE or Microsoft Excel, or in an ODBC data source such asMicrosoft SQL Server.

DBMS (Database management system): is a software program in which you can

create and maintain databases.Examples of commercially used DBMS are: MS Access 2007, Oracle 10i, MS SQL

server, IBM DB2 etc.

WHAT IS TABLE? 

  The fundamental structure of a relational database management system.  In Microsoft Access, a table is an object that stores data in records (rows) and

fields (columns). The data is usually about a particular category of things, such asemployees or orders.

WHAT IS QUERY?

 A question about the data stored in your tables, or a request to perform anaction on the data. A query can bring together data from multiple tables to serveas the source of data for a form, report, or data access page.

WHAT IS FORM?

  A Microsoft Access database object on which you place controls for taking

actions or for entering, displaying, and editing data in fields.

WHAT IS REPORT?

 A Microsoft Access database object that prints information formatted andorganized according to your specifications.

  Examples of reports are sales summaries, phone lists, and mailing labels.

WHAT IS RELATIONAL DATABASE?

  A type of database or database management system that stores information intables (that is, rows and columns of data).

Page 2: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 2/50

MICROSOFT ACCESS

Page 2

  A relational database uses matching values from two tables to relate information inone table to information in the other table. In a relational database, you typicallystore a specific type of information just once, which makes the database veryefficient and reduces data entry errors.

FIELD :

  An element of a table that contains a specific item of information, such as a lastName.E.g. Student Table (rollNo,firstName,lastName,address)

  A field is represented by a column or cell in a datasheet. On a form, report, or dataaccess page, you can use a control, such as a text box, to display data from a field.In some databases, such as Microsoft SQL Server, "column" is used instead of "field."

PRIMARY KEY : 

  One or more fields (columns) who’s value or values uniquely identify eachrecord in a table. A primary key cannot allow Null values and must always have aunique index.

  A primary key is used to relate a table to foreign keys in other tables.

FOREIGN KEY :

  One or more table fields (columns) that refer to the primary key field or fields

in another table. A foreign key indicates how the tables are related .The data in theforeign key and primary key fields must match, though the field names do not haveto be the same.

  For example, consider 2 tables: Products and Supplier.

Products ( #productId , productName, productDesc,  supplierNo)

Supplier (# supplierId , supplierName, supplierAddress)

  Products table might contain the foreign key supplierNo, which relates to theprimary key supplierId in a Supplier table.

 A foreign key can be Null; if a foreign key consists of more than one field and anyof those fields is Null, all the fields must be Null.

Page 3: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 3/50

MICROSOFT ACCESS

Page 3

INDEX : 

  A feature that speeds up searching and sorting in a table based on key valuesand can enforce uniqueness on the rows in a table. The primary key of a table isautomatically indexed. Some fields can't be indexed because of their data type.

Field data types available in Microsoft Access 

Data type Use for Size

Text Text or combinations of text andnumbers, such as addresses. Alsonumbers that do not requirecalculations, such as phonenumbers, part numbers, or postal

codes.

Up to 255 characters.

Microsoft Access only stores thecharacters entered in a field; itdoes not store space characters

for unused positions in a Textfield. To control the maximumnumber of characters that can beentered, set the FieldSize property.

Memo Lengthy text and numbers, such asnotes or descriptions.

Up to 64,000 characters.

Number Numeric data to be used formathematical calculations, exceptcalculations involving money (use

Currency type). Set the FieldSize property to define the specificNumber type.

1, 2, 4, or 8 bytes. 16 bytes forReplication ID (GUID) only.

Date/Time Dates and times. 8 bytes.

Currency Currency values. Use the Currencydata type to prevent rounding off during calculations. Accurate to 15digits to the left of the decimal pointand 4 digits to the right.

8 bytes.

AutoNumber Unique sequential (incrementing by

1) or random numbers automaticallyinserted when a record is added.

For more information on defining an

AutoNumber field, click  . 

4 bytes. 16 bytes for Replication

ID (GUID) only.

Yes/No Fields that will contain only one of 1 bit.

Page 4: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 4/50

MICROSOFT ACCESS

Page 4

two values, such as Yes/No,True/False, On/Off.

OLE Object Objects (such as Microsoft Worddocuments, Microsoft Excel

spreadsheets, pictures, sounds, orother binary data), created in otherprograms using the OLE protocol,that can be linked to or embedded ina Microsoft Access table. You mustuse a bound object frame in a formor report to display the OLE object.

Up to 1 gigabyte (limited by disk space).

Hyperlink Field that will store hyperlinks. Ahyperlink can be a UNC path or aURL.

Up to 64,000 characters.

Lookup Wizard Creates a field that allows you tochoose a value from another table orfrom a list of values using a combobox. Choosing this option in the datatype list starts a wizard to define thisfor you.

The same size as the primary keyfield that is also the Lookup field;typically 4 bytes.

NOTES:

HYPERLINK :

Colored and underlined text or a graphic that you click to jump to a file, a location in afile, an HTML page on the World Wide Web, or an HTML page on an intranet.Hyperlinks can also jump to Gopher, Telnet, newsgroup, and FTP sites.

NULL(Imp) :  A value that indicates missing or unknown data in a field. You can use Null

values in expressions.  Null values can be entered in fields for which information is unknown, as well as in

expressions and queries. In Visual Basic, the Null keyword indicates a Null value.Some fields, such as those defined as containing the primary key, can't contain Null

values.

FIELD PROPERTIES 

1) FIELD SIZE: You can use the FieldSize property to set the maximum size for datastored in a field set to the Text, Number, or AutoNumber data type.

Page 5: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 5/50

MICROSOFT ACCESS

Page 5

  If the Data Type property is set to Text, enter a number from 0 to 255. The defaultsetting is 50.

  If the Data Type property is set to AutoNumber, the Field Size property can be setto Long Integer.

  If the Data Type property is set to Number, the Field Size property settings and

their values are related in the following way.

Setting Storage size

Byte 1 byte

Decimal 12bytes

Integer 2 bytes

Long Integer 4 bytes

Single 4 bytes

Double 8 bytes

2) FORMAT:

  You can use the Format property to customize the way numbers, dates, times,

and text are displayed and printed.  For example, if you've created a Price text box, you can set its Format property to

Currency and its Decimal Places property to 2 or Auto. If you enter 4321.678 inthe control, the number would be displayed as $4,321.68.

Setting 

The Format property uses different settings for different data types. For informationabout settings for a specific data type, see one of the following topics:

1)  Date/Time Data Type: You can set date and time either long, short or mediumdate and time you required in field.

2)  Number and Currency Data Types: The following table shows the predefinedFormat property settings for numbers.

Setting Description

General Number (Default) Display the number as entered.

Currency Use the thousand separators; follow the settings specified in

Page 6: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 6/50

MICROSOFT ACCESS

Page 6

Regional Settings in Windows Control Panel for negativeamounts, decimal and currency symbols, and decimal places.

Euro Use the currency format, with the euro symbol (), regardless of thecurrency symbol specified in Regional Settings in Windows

Control Panel.Fixed Display at least one digit; follow the settings specified in Regional

Settings in Windows Control Panel for negative amounts, decimaland currency symbols, and decimal places.

Standard Use the thousand separators; follow the settings specified inRegional Settings in Windows Control Panel for negativeamounts, decimal symbols, and decimal places.

Percent Multiply the value by 100 and append a percent sign (%); followthe settings specified in Regional Settings in Windows ControlPanel for negative amounts, decimal symbols, and decimal places.

Scientific Use standard scientific notation.

3)  Text and Memo Data Types: You can create custom text and memo formats byusing the following symbols.

Symbol Description

@ Text character (either a character or a space) is required.

& Text character is not required.

< Force all characters to lowercase.

> Force all characters to uppercase.

4)  Yes/No Data Type: You can set the Format property to the Yes/No, True / False,or On/Off predefined formats or to a custom format for the Yes/No data type.

3) DECIMAL PLACES: You can use the Decimal Places property to specify thenumber of decimal places Microsoft Access uses to display numbers.

The Decimal Places property uses the following settings.

Setting Visual Basic Description

Auto 255 (Default) Numbers appear as specified by theFormat property setting.

0 to 15 0 to 15 Digits to the right of the decimal separator appearwith the specified number of decimal places; digitsto the left of the decimal separator appear as

Page 7: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 7/50

MICROSOFT ACCESS

Page 7

specified by the Format property setting.

5)  INPUT MASK:-

  You can use the Input Mask property to make data entry easier and to controlthe values users can enter in a text box control.

  For example, you could create an input mask for a Phone Number field that showsyou exactly how to enter a new number: (___) ___-____. It is often easier to use theInput Mask Wizard to set the property for you.

The Input Mask property can contain up to three sections separated by semicolons (;).

Section Description

First Specifies the input mask itself; for example! (999) 999-9999.

Second Specifies whether Microsoft Access stores the literal displaycharacters in the table when you enter data. If you use 0 for thissection, all literal display characters (for example, the parenthesesin a phone number input mask) are stored with the value; if youenter 1 or leave this section blank, only characters typed into thecontrol are stored.

Third Specifies the character that Microsoft Access displays for the

space where you should type a character in the input mask. Forthis section, you can use any character; to display an empty string,use a space enclosed in quotation marks (" ").

6) CAPTION:-

You can use the Caption property to provide helpful information to the user throughcaptions on objects in various views:

  Field captions specify the text for labels attached to controls created by dragging afield from the field list and serves as the column heading for the field in table orquery Datasheet view.

  Form captions specify the text that appears in the title bar in Form view.  Report captions specify the title of the report in Print Preview.  Button and label captions specify the text that appears in the control.

7) DEFAULT VALUE:-

Page 8: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 8/50

MICROSOFT ACCESS

Page 8

  You can use the Default Value property to specify a value that is automaticallyentered in a field when a new record is created.

  For example, in an Addresses table you can set the default value for the City fieldto New York. When users add a record to the table, they can either accept this valueor enter the name of a different city.

8) VALIDATION RULE:

  You can use the Validation Rule property to specify requirements for data

entered into a record, field, or control.

9) VALIDATION TEXT:

  When data is entered that violates the Validation Rule setting, you can use the

Validation Text property to specify the message to be displayed to the user.

10) REQUIRED:

  You can use the Required property to specify whether a value is required in afield. If this property is set to Yes, when you enter data in a record, you must entera value in the field or in any control bound to the field, and the value cannot beNull.

  For example, you might want to be sure that a Last Name control has a value foreach record. When you want to permit Null values in a field, you must not only setthe Required property to No but, if there is a Validation Rule property setting, itmust also explicitly state "validation rule Or Is Null".

Note The Required property doesn't apply to AutoNumber fields.

Setting 

The Required property uses the following settings.

Setting Visual Basic Description

Yes True ( – 1) The field requires a value.

No False (0) (Default) The field doesn't require a value.

11) INDEXED:-

  You can use the Indexed property to set a single-field index.  An index speeds up queries on the indexed fields as well as sorting and

grouping operations.

Page 9: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 9/50

MICROSOFT ACCESS

Page 9

  For example, if you search for specific employee names in a Last Name field, youcan create an index for this field to speed up the search for a specific name.

Setting 

The Indexed property uses the following settings.

Setting Description

No (Default) No index.

Yes (Duplicates OK) The index allows duplicates.

Yes (No Duplicates) The index doesn't allow duplicates.

DIFFERENT TYPES OF PRIMARY KEYS: 

There are three kinds of primary keys that can be defined in Microsoft Access:AutoNumber, single-field, and multiple-field.

1.  AutoNumber primary keys2.  Single-field primary keys3.  Multiple-field primary keys

1) AutoNumber primary keys 

  An AutoNumber field can be set to automatically enter a sequential number aseach record is added to the table.

  Designating such a field as the primary key for a table is the simplest way to createa primary key. If you don't set a primary key before saving a newly created table,Microsoft Access will ask if you want it to create a primary key for you. If youanswer Yes, Microsoft Access will create an AutoNumber primary key.

2) Single-field primary keys

  If you have a field that contains unique values such as ID numbers or part

numbers, you can designate that field as the primary key (# P.K.)

  If the field you select as primary key does have duplicate or NULL values,Microsoft Access won't set the primary key.

  You can run a Find Duplicates query to determine which records contain duplicatedata. If you can't readily eliminate duplicate entries by editing your data, you caneither add an AutoNumber field and set it as the primary key or define a multiple-field primary key.

3) Multiple-field primary keys

Page 10: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 10/50

MICROSOFT ACCESS

Page 10

  In situations where you can't guarantee the uniqueness of any single field, you maybe able to designate two or more fields as the primary key.

  The most common situation where this arises is in the table used to relate two othertables in a many-to-many relationship. The Order Details table in the North windsample database is such a table, relating the Orders and Products tables. Its primary

key consists of two fields: OrderID and ProductID. The Order Details table can listmany products and many orders, but each product can only be listed once per order,so combining the OrderID and ProductID fields produces an appropriate primarykey.

  Another example would be an inventory database that uses a field part number of two or more fields (part and subpart).

ABOUT RELATIONSHIPS IN AN ACCESS DATABASE 

RELATIONSHIP:

An association established between common fields (columns) in two tables. A

relationship can be one-to-one, one-to-many, or many-to-many.

This topic provides reference information about:

  Why you should define relationships  How relationships work   A one-to-many relationship  A many-to-many relationship  A one-to-one relationship  Defining relationships

Why define relationships?

  After you've set up different tables for each subject in your Microsoft Accessdatabase, you need a way of telling Microsoft Access how to bring that

information back together again from multiple tables.  The first step in this process is to define relationships between your tables.

Page 11: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 11/50

MICROSOFT ACCESS

Page 11

  After you've done that, you can create queries, forms, and reports to display

information from several tables at once. For example, this form includesinformation from five tables:

How do relationships work?

  In the previous example, the fields in five tables must be coordinated so that theyshow information about the same order. This coordination is accomplished withrelationships between tables.

  A relationship works by matching data in key fields  — usually a field with thesame name in both tables. In most cases, these matching fields are the primarykey from one table, which provides a unique identifier for each record, and aforeign key in the other table.

  For example, employees can be associated with orders they're responsible for by

creating a relationship between the Employees table and the Orders table using theEmployeeID fields.

Page 12: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 12/50

MICROSOFT ACCESS

Page 12

A one-to-many relationship

  A one-to-many relationship is the most common type of relationship. In a one-to-many relationship, a record in Table A can have many matching records in Table B,

but a record in Table B has only one matching record in Table A.

Page 13: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 13/50

MICROSOFT ACCESS

Page 13

A many-to-many relationship

  In a many-to-many relationship, a record in Table A can have many matching

records in Table B, and a record in Table B can have many matching records

in Table A. 

This type of relationship is only possible by defining a third table (called a junctiontable) whose primary key consists of two fields —  the foreign keys from bothTables A and B. A many-to-many relationship is really two one-to-manyrelationships with a third table.

  For example, the Orders table and the Products table have a many-to-manyrelationship that's defined by creating two one-to-many relationships to the OrderDetails table.

Page 14: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 14/50

MICROSOFT ACCESS

Page 14

A one-to-one relationship

  In a one-to-one relationship, each record in Table A can have only one

matching record in Table B, and each record in Table B can have only one

matching record in Table A.   This type of relationship is not common, because most information related in this

way would be in one table. You might use a one-to-one relationship to divide atable with many fields, to isolate part of a table for security reasons, or to storeinformation that applies only to a subset of the main table.

  For example, you might want to create a table to track employees participating in afundraising soccer game.

Page 15: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 15/50

MICROSOFT ACCESS

Page 15

Defining relationships

  You define a relationship by adding the tables that you want to relate to theRelationships window, and then dragging the key field from one table and

dropping it on the key field in the other table. You can also define relationships

by using the keyboard.

Page 16: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 16/50

MICROSOFT ACCESS

Page 16

The kind of relationship that Microsoft Access creates depends on how the related

fields are defined: 

  A one-to-many relationship is created if only one of the related fields is a primarykey or has a unique index.

  A one-to-one relationship is created if both of the related fields are primary keys orhave unique indexes.

  A many-to-many relationship is really two one-to-many relationships with a thirdtable whose primary key consists of two fields  —  the foreign keys from the twoother tables.

Note:- If you drag a field that isn't a primary key and doesn't have a unique index toanother field that isn't a primary key and doesn't have a unique index, an indeterminaterelationship is created. In queries containing tables with an indeterminate relationship,Microsoft Access displays a default join line between the tables, but referential integritywon't be enforced, and there's no guarantee that records are unique in either table.

REFERENTIAL INTEGRITY

  Rules that you follow to preserve the defined relationships between tables

when you enter or delete records.  If you enforce referential integrity, Microsoft Access

Page 17: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 17/50

MICROSOFT ACCESS

Page 17

PREVENTS YOU FROM 

  Adding records to a related table when there is no associated record in the

primary table,  Changing values in the primary table that would result in orphan records in a

related table, and  Deleting records from the primary table when there are matching related records

in a related table.

IMPORTING-EXPORTING AND LINKING 

What is exporting?

  Exporting is a way to output data and database objects to another database,

spreadsheet, or file format so another database, application, or program canuse the data or database objects.

  Exporting is similar in functionality to copying and pasting. In general, you use theExport command on the File menu to export data or database objects, but there areother commands you can use as described below. You can export data to a varietyof supported databases, programs, and file formats.

Exporting database objects

  You can export most database objects from a Microsoft Access database orMicrosoft Access project to another Access database or Access project.

Exporting to or exchanging data with MICROSOFT WORD

There are ways you can use Microsoft Access data with Microsoft Word:

  You can save the output of a datasheet, form, or report as a Rich Text Format(.rtf) file. A Rich Text Format file preserves formatting, such as fonts and styles,and can be opened with Microsoft Word and other Windows word-processing ordesktop-publishing programs.

  You can save the output of a datasheet, form, or report as a .rtf file andautomatically load the file into Microsoft Word by using the Publish It With MSWord command on the Office Links submenu of the Tools menu.

Exporting to Microsoft Excel or another spreadsheet program

Page 18: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 18/50

MICROSOFT ACCESS

Page 18

There are three ways you can use Microsoft Access data with Microsoft Excel or anotherspreadsheet program:

  You can export the datasheet as unformatted data to Microsoft Excel or anotherspreadsheet program.

  You can save the output of a datasheet, form, or report directly as an Excel (.xls)file or worksheet .

  You can save the output of a datasheet, form, or report as an Excel (.xls) file andautomatically load the file into Microsoft Excel by using the Analyze It With MS

Excel command.

In the latter two cases, you can preserve most formatting, such as fonts and colors. Reportgroup levels are saved as Microsoft Excel outline levels, and a form is saved as a table of data.

Importing data

  Importing data creates a copy of its information in a new table in your Accessdatabase or Access project. The source table or file is not altered in thisprocess.

  When importing data, you can't append data to existing tables (except whenimporting spreadsheet or text files). However, once you have imported a table, inan Access database you can perform an append query or in an Access project youcan use a stored procedure to add the table's data to another table.

  You can also import database objects other than tables, such as forms or reports,from another Access database or Access project.

Linking data

  In an Access database, linking data enables you to read and in most cases,

update data in the external data source without importing.    The external data source's format is not altered so that you can continue to use the

file with the program that originally created it, but you can add, delete, or edit its

data by using Microsoft Access as well. You can link a table only in an Accessdatabase, not an Access project.

  Microsoft Access uses different icons to represent linked tables and tables thatare stored in the current database. If you delete the icon for a linked table, youdelete the link to the table, not the external table itself.

Ways to import and link data

There are two ways to import or link data:

Page 19: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 19/50

MICROSOFT ACCESS

Page 19

  Open or create an Access database or create an Access project to contain theimported tables, or linked tables in the case of an Access database, and then use theImport or Link  Tables commands on the Get  External submenu of the File menu.

The difference between importing and linking

Microsoft Access provides two choices for using data from an external data source. Youcan:

  Import the data into a new Microsoft Access table, which is a way to convert

data from a different format and copy it into Microsoft Access . You can alsoimport database objects into the current Microsoft Access database or MicrosoftAccess project.

  Link the data, which is a way to connect to data from another application

without importing it so that you can view and edit the data in both the originalapplication and in an Access database. (In previous versions of Microsoft Access,this process was referred to as attaching.)

ABOUT JOINING TABLES

  The power of queries lies in being able to bring together or perform an action

on data from more than one table or query.  For example, you might want to view a customer's information with the orders the

customer placed. To see this information, you need data from the Customers andOrders tables.

Page 20: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 20/50

MICROSOFT ACCESS

Page 20

TYPES OF JOINS

Inner joins

  Once tables and queries are joined, and you've added fields from both tables orqueries to the design grid in query Design view, the default  join tells the query tocheck for matching values in the join fields. (This is called an inner join.)

  When it finds matches, it combines those two records and displays them as one

record in the query's results. 

Page 21: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 21/50

MICROSOFT ACCESS

Page 21

Outer joins

  If one table or query doesn't have a matching record in the other table or query,neither record appears in the query's results.

  If you want the query to select all the records from one table or query whetheror not it has matching records in the other table or query, you can change the join type to an outer join. 

Page 22: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 22/50

MICROSOFT ACCESS

Page 22

Unequal joins

  If you want the query to select records based on the value in the join field beinggreater than, less than, not equal to, greater than or equal to, or less than or equal tothe value in the other join field, you must create an SQL statement in SQL view. 

TYPES OF QUERIES YOU CAN CREATE IN MICROSOFT ACCESS

Type of query:

1.  Select queries

2. 

Parameter queries3.  Crosstab queries

4.  Action queries (make-table, delete, update, append queries)

5.  SQL queries (union, pass-through, data-definition, sub query)

What is a select query and when would you use one?

Page 23: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 23/50

MICROSOFT ACCESS

Page 23

  A select query is the most common type of query. It retrieves data from one or

more tables and displays the results in a datasheet where you can update therecords (with some restrictions).

  You can also use a select query to group records and calculate sums, counts,averages, and other types of totals.

What is a parameter query and when would you use one?

  A parameter query is a query that when run displays its own dialog boxprompting you for information, such as criteria for retrieving records or a

value you want to insert in a field.  You can design the query to prompt you for more than one piece of information;

for example, you can design it to prompt you for two dates. Microsoft Access canthen retrieve all records that fall between those two dates.

What is a crosstab query and when would you use one?

  Crosstab queries calculate a sum, average, count, or other type of total for datathat is grouped by two types of information —   one down the left side of the

datasheet and another across the top.

What is an action query and when would you use one?

Page 24: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 24/50

MICROSOFT ACCESS

Page 24

  An action query is a query that makes changes to many records in just oneoperation. There are four types of action queries: delete, update, append, andmake-table.

  This topic provides examples of:

1.  Delete query2.  Update query3.  Append query4.  Make-table query

Delete query

  Deletes a group of records from one or more tables.  For example, you could use a delete query to remove products that are

discontinued or for which there are no orders. With delete queries, you alwaysdelete entire records, not just selected fields within records.

Update query

  Makes global changes to a group of records in one or more tables.  For example, you can raise prices by 10 percent for all dairy products, or you can

raise salaries by 5 percent for the people within a certain job category. With anupdate query, you can change data in existing tables.

APPEND QUERY

  Adds a group of records from one or more tables to the end of one or more

tables.   For example, suppose that you acquire some new customers and a database

containing a table of information on those customers. To avoid typing all thisinformation in, you'd like to append it to your Customers table. Append queries arealso helpful for:

  Appending fields based on criteria.

  CONSTRAINT: structure of both the tables should be same (compatible).

  For example, you might want to append only the names and addresses of customers with outstanding orders.

  Appending records when some of the fields in one table don't exist in the othertable. For example, in the North wind sample database, the Customers table has 11fields. Suppose that you want to append records from another table that has fieldsthat match 9 of the 11 fields in the Customers table. An append query will appendthe data in the matching fields and ignore the others.

MAKE-TABLE QUERY

Page 25: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 25/50

MICROSOFT ACCESS

Page 25

  Creates a new table from all or part of the data in one or more tables.

Make-table queries are helpful for:

  Creating a table to export to other Microsoft Access databases.  For example, you might want to create a table that contains several fields from

your Employees table, and then export that table to a database used by yourpersonnel department.

1.  Making a backup copy of a table.2.  Creating a history table that contains old records. For example, you could create

a table that stores all your old orders before deleting them from your currentOrders table.

3.  Improving performance of forms, reports, and data access pages based onmultiple-table queries or SQL statements. For example, suppose you want toprint multiple reports that are based on a five-table query that includes totals.

You may be able to speed things up by first creating a make-table query thatretrieves the records you need and stores them in one table. Then you can basethe reports on this table or specify the table in an SQL statement as the recordsource for a form, report, or data access page, so you don't have to rerun thequery for each report. However, the data in the table is frozen at the time yourun the make-table query.

WHAT IS SQL?

  (SQL)Structured query language.  It is standardized language (ANSI SQL) like ANSI C.

  C is for general programming purposes, SQL is for database programming.  This language is used for interacting with database and performing database

operations: select, update, insert and delete.  MS ACCESS provides a graphical utility called Query Design View in which

you can create and modify queries. So don’t need to write queries in SQL language.  But, the queries you create in Query Design view, Access creates equivalent SQL

language statements on its own behind the scenes. You can view the SQL languagestatements by going to SQL view of the query.

What is an SQL query and when would you use one?

  An SQL query is a query you create using an SQL statement.  Examples of SQL-specific queries are the union query, data-definition query, and

sub query.

This topic provides examples of:

  Union query  Data-definition query

Page 26: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 26/50

MICROSOFT ACCESS

Page 26

  Sub query

UNION QUERY

  This type of query combines fields (columns) from one or more tables or queries

into one field or column in the query's results.  For example, Consider 2 tables: Supplier, Customer.

1.  Supplier (Sno,sname,address,rating)2.  Customer (Cno,cname,address,rating)

Query : List all the supplier, customer names with their address. 

Solution :SELECT sname, address FROM SupplierUNION

SELECT cname, address FROM Customer;

Data-definition query

  This type of query creates, deletes, alters tables, or creates indexes in adatabase , such as Microsoft Access or Microsoft FoxPro tables.

(Important)

SUBQUERY

  This type of query consists of an SQL SELECT statement inside another selectquery or action query.

E.g. Find all orders whose suppliers are from ―ahmd‖ city.

You can enter these statements in the Field row of the query design grid to define anew field, or in the Criteria row to define criteria for a field. You can use subqueries to:

  Test for the existence of some result from the sub query (using the EXISTSor NOT EXISTS reserved words).

  Find any values in the main query that are equal to, greater than, or less thanvalues returned by the sub query (using the ANY, IN, or ALL reservedwords).

  Create sub queries within sub queries (nested sub queries).

About designing a query

Page 27: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 27/50

MICROSOFT ACCESS

Page 27

  You can design a query in the design view for Query.  Design view: Interface in which you can graphically design and modify a query.  Advanced Filter/Sort window: A window in which you can create a filter from

scratch. You enter criteria expressions in the filter design grid to restrict the recordsin the open form or datasheet to a subset of records that meet the criteria.

Add or remove tables, queries, and fields

  You can add a table or query if the data you need isn't in the query, or remove atable or query if you decide you don't need them. Once you add the tables orqueries you need, you can then add the fields that you want to work with to thedesign grid, or remove them if you decide you don't need them.

Page 28: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 28/50

MICROSOFT ACCESS

Page 28

Calculate amounts

  You can add the values in a field or do other computations with the data byspecifying the type of calculation to perform.

Page 29: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 29/50

MICROSOFT ACCESS

Page 29

Limit results by using criteria

  You can limit the records that you see in the query's results or the records that areincluded in a calculation by specifying criteria.

Page 30: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 30/50

MICROSOFT ACCESS

Page 30

Sort records

You can sort the query's results by specifying a sort order in the design grid.

Page 31: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 31/50

MICROSOFT ACCESS

Page 31

Use the asterisk in the query design grid

  To include all fields from a table in a query, you can either select each fieldindividually or use the asterisk (*) wildcard character. Selecting the asterisk has anadvantage over selecting all the fields:

  When you use the asterisk, the query results automatically include any fields thatare added to the underlying table or query after the query is created, andautomatically exclude fields that are deleted.

  If you type an asterisk in the Field row rather than dragging it, you must type the

table name also. For example, type Customers.*.

ABOUT SELECT AND CROSSTAB QUERIES

  Select and Crosstab queries are the two main ways you query a Microsoft Accessdatabase to retrieve just the data you want.

SELECT QUERIES

What is a select query?A select query is the most common type of query. You use it to:

  Retrieve data from one or more tables by using criteria (CRITERIA: Conditionsyou specify to limit which records are included in the result set of a query orfilter. For example, the following criterion selects records for which the value forthe Order Amount field is greater than 30,000: Order Amount > 30000.)youspecify and then display the data in the order you want.

  Update records in the datasheet of a select query (with some restrictions).  Group records and calculate sums, counts, averages, and other types of totals.

Page 32: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 32/50

MICROSOFT ACCESS

Page 32

Creating a select query

  You create a query with a wizard or from scratch in query Design View. InDesign view, you specify the data you want to work with by adding the tables orqueries that contain the data, and then by filling in the design grid.

Page 33: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 33/50

MICROSOFT ACCESS

Page 33

What is a crosstab query?

  You use crosstab queries to calculate and restructure data for easier analysisof your data.

  Crosstab queries calculate a sum, average, count, or other type of total for datathat is grouped by two types of information —  one down the left side of thedatasheet and another across the top.

Page 34: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 34/50

MICROSOFT ACCESS

Page 34

CREATING A CROSSTAB QUERY

  You create 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 twotypes of information  —  one down the left side of the datasheet and the other

across the top.) with a wizard or from scratch in query Design view.  In the design grid, you specify which field's values will become column headings,which field's values will become row headings, and which field's values to sum,average, count, or otherwise calculate.

Page 35: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 35/50

MICROSOFT ACCESS

Page 35

CREATE A SIMPLE SELECT QUERY WITH A WIZARD

  The Simple Select Query Wizard creates queries that retrieve data from the fieldsyou specify in one or more tables or queries. If you want, the wizard can alsosum, count, and average values for groups of records or all records, and it cancalculate the minimum or maximum value in a field. However, you can't limit therecords it retrieves by setting criteria.

1.  In the Database window, click Queries under Objects, and then click New on theDatabase window toolbar.

2.  In the New Query dialog box, click Simple Query Wizard, and then click OK.3.  Follow the directions in the wizard dialog boxes. In the last dialog box, you can

choose either to run the query or to see the query's structure in Design view.  If the resulting query isn't exactly what you want, you can rerun the

wizard or change the query in Design view.

Create a select query on my own

1.  In the Database window, click Queries under Objects, and then click New on theDatabase window toolbar.

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

Page 36: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 36/50

MICROSOFT ACCESS

Page 36

3.  In the Show Table dialog box, click the tab that lists the tables or queries whosedata you want to work with.

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

5.  Add fields to the Field row in the design grid, and if you want, specify criteria

and a sort order.6.  To view the query's results, click View on the toolbar.

FIND DUPLICATE RECORDS OR FIELD VALUES IN A TABLE WITH A

WIZARD

  Using the Find Duplicates Query Wizard, you can create a select query to

determine if there are duplicate records in a table.    For example, you might search for duplicate values in an Address field to

determine if you have duplicate records for the same supplier, or you might searchfor duplicate values in a City field to see which suppliers are in the same city.

1.  In the Database window, click Queries under Objects, and then click New on theDatabase window toolbar.

2.  In the New Query dialog box, click  Find Duplicates Query Wizard, and thenclick OK.

3.  Follow the directions in the wizard dialog boxes. If you don't choose to showfields in addition to those with duplicate values, the query results will sum theinstances of each duplicate value. In the last dialog box, you can choose to run thequery or see the query's structure in Design view.

FIND UNMATCHED RECORDS BETWEEN TABLES WITH A WIZARD

  Using the Find Unmatched Query Wizard, you can create a select query to find

records in one table that don't have related records in another table.    For example, you can find customers who don't have orders.

1.  In the Database window, click Queries under Objects, and then click New on theDatabase window toolbar.

2.  In the New Query dialog box, click Find Unmatched Query Wizard, and thenclick OK.

3. 

Follow the directions in the wizard dialog boxes. In the last dialog box, you canchoose to run the query or see the query's structure in Design view.

ABOUT SUBDATASHEETS

  In a subdatasheet, you can view and edit related or joined data in a table,query, or form datasheet, or in a subform.

Page 37: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 37/50

MICROSOFT ACCESS

Page 37

  For example, in the North wind sample database, the Suppliers table has a one-to-many relationship with the Products table; so for each row of the Supplierstable in Datasheet view, you can view and edit the related rows of the Productstable in a subdatasheet.

Create a table from another table with a query 

1.  Create a query, selecting the tables or queries that contain the records you want toput in the new table.

1.  In the Database window, click  Queries under Objects, and then click New on the Database window toolbar.

2.  In the New Query dialog box, click Design View, and then click OK.3.  In the Show Table dialog box, click the tab that lists the tables or queries

whose data you want to work with.4.  Double-click the name of each object you want to add to the query, and

then click Close.

5.  Add fields to the Field row in the design grid, and if you want, specifycriteria and a sort order.

6.  To view the query's results, click View on the toolbar.2.  In query Design view, click the arrow next to Query Type on the toolbar, and

then click Make Table. The Make Table dialog box appears.3.  In the Table Name box, enter the name of the table you want to create or replace.4.  Do one of the following:

Click Current Database.

Click Another Database, and then either type the path of the database where you

want to put the new table or click Browse to locate the database.

5.  Click OK.6.  Drag from the field list to the query design grid the fields you want in the new

table.7.  In the Criteria cell for the fields that you've dragged to the grid, type the criteria.8.  To preview the new table before you create it, click  View on the toolbar. To

return to query Design view and make changes or run the query, click  View onthe toolbar again.

9.  To create the new table, click Run on the toolbar.

Create an update query 

1.  Create a query with the tables or queries that include the records you want toupdate.

1.  In the Database window, click  Queries under Objects, and then click New on the Database window toolbar.

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

Page 38: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 38/50

MICROSOFT ACCESS

Page 38

3.  In the Show Table dialog box, click the tab that lists the tables or querieswhose data you want to work with.

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

5.  Add fields to the Field row in the design grid, and if you want, specify

criteria and a sort order.6.  To view the query's results, click View on the toolbar.

2.  In query Design view, click the arrow next to Query Type on the toolbar, andthen click Update Query.

3.  Drag from the field list to the query design grid the fields you want to update oryou want to specify criteria for.

4.  In the Criteria cell, specify the criteria if necessary.5.  In the Update To cell for the fields you want to update, type the expression or

value you want to use to change the fields, as shown in the following illustration.6.  To see a list of the records that will be updated, click  View on the toolbar. This

list won't show the new values. To return to query Design view, click  View on the

toolbar again. Make any changes you want in Design view.7.  Click Run on the toolbar to update the records.

About parameter queries that prompt for criteria 

  A parameter query is a query that, when run, displays its own dialog box

prompting you for information, such as criteria for retrieving records or avalue you want to insert in a field.

  You can design the query to prompt you for more than one piece of information;for example, you can design it to prompt you for two dates. Microsoft Access canthen retrieve all records that fall between those two dates.

Create a parameter query 

Create a parameter query

1.  Create a select or crosstab query.2.  In query Design view, drag the fields from the field list to the query design grid.3.  Do one or more of the following:

Use one parameter

  In the Criteria cell for the field you want to use as a parameter, type an expressionwith a prompt enclosed in square brackets. For example, in a field that displays thecurrent number of units in stock, enter the following:

  <[Number of Units in Stock:]

Use two or more parameters

Page 39: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 39/50

MICROSOFT ACCESS

Page 39

  In the Criteria cell for each field you want to use as a parameter, type anexpression with prompts enclosed in square brackets.

  For example, in a field that displays dates, you can display the prompts "Type thebeginning date:" and "Type the ending date:" to specify a range of values:

  Between [Type the beginning date:] And [Type the ending date:]

Use parameters with wildcards

  In the Criteria cell for each field you want to use as a parameter, type anexpression with a prompt enclosed in square brackets. To prompt the user for oneor more characters to search for, and then find records that begin with or containthe characters the user specifies, create a parameter query that uses the LIKEoperator and the wildcard symbol (*).

  For example, the following statement searches for words that begin with aspecified letter:

  LIKE [Enter the first character to search by: ] & "*"

  The following statement searches for words that contain the specified character:  LIKE "*" & [Enter any character to search by: ] & "*"

EXPRESSIONS

  EXPRESSION: Any combination of mathematical or logical operators, constants,functions, and names of fields, controls, and properties that evaluates to a single

value.  Expressions can perform calculations, manipulate characters, or test data.  You use expressions in many operations in Microsoft Access, including creating

calculated controls, query and filter criteria, default values, validation rules, andmacro conditions.

EXAMPLES OF MANIPULATING AND CALCULATING DATES

The following table lists examples of expressions that you can use in calculated controlson forms, reports, and data access pages.

Expression Description

=Date()

Uses the Date function to display the current date in the form

of mm-dd-yyyy, where mm is the month (1 through 12), dd  isthe day (1 through 31), and  yyyy is the year (1980 through2099).

=Format(Now(), "ww")Uses the Format function to display the number of the week of the year the current date represents, where ww is 1 through53.

Page 40: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 40/50

MICROSOFT ACCESS

Page 40

=DatePart("yyyy",[OrderDate])

Uses the DatePart function to display the four-digit year of the value of the OrderDate field.

=DateAdd("y", 10,[PromisedDate])

Uses the DateAdd function to display a date that is 10 daysbefore the value of the PromisedDate field.

=DateDiff("d",[OrderDate],[ShippedDate])

Uses the DateDiff  function to display the variance in daysbetween the values of the OrderDate and ShippedDate fields.

Notes 

  In the ControlSource property of a calculated control, precede the expressionwith the = operator. On a data access page, you can omit the = operator, and typean alias instead; for example, type WeekNumber: Format(Now(), "ww").

  When you set the Name property of a calculated control in a form or report, or setthe ID property of a calculated control in a data access page, make sure that youuse a unique name. Don't use the name or ID of one of the controls you used inthe expression.

  In an expression on a form or report, you can use the name of a control or thename of a field in the underlying records source. In an expression on a data accesspage, you can use only the name of a field that's in the data definition of the page.

EXAMPLES OF MANIPULATING TEXT VALUES

The following table lists examples of expressions that you can use in calculated controlson forms, reports, and data access pages.

Expression Description

="N/A" Displays N/A.

=[FirstName]&" "&[Last Name]Displays the values of the FirstName and LastName fields separated by a space.

=Left([ProductName], 1)Uses the Left function to display the firstcharacter of the value of the ProductNamefield.

=Right([AssetCode], 2)Uses the Right function to display the last 2characters of the value of the AssetCode field.

=Trim([Address])Uses the Trim function to display the valueof the Address field, removing any leading ortrailing spaces.

=IIf(IsNull([Region]),[City]&" "&[PostalCode],[City]&" "&[Region]&" "&[PostalCode])

Uses the IIf function to display the values of the City and PostalCode fields if Region isNull; otherwise, it displays the values of the

Page 41: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 41/50

MICROSOFT ACCESS

Page 41

City, Region, and PostalCode fields,separated by spaces.

Notes 

  In the ControlSource property of a calculated control, precede the expressionwith the = operator. On a data access page, you can omit the = operator, and typean alias instead; for example, type FullName: [FirstName]&" "& [Last Name].

  When you set the Name property of a calculated control in a form or report, or setthe ID property of a calculated control in a data access page, make sure to use aunique name. Don't use the name or ID of one of the controls that you used in theexpression.

  In an expression on a form or report, you can use the name of a control or field inthe underlying record source. In an expression on a data access page, you can useonly the name of a field that's in the data definition of that page.

EXAMPLES OF MANIPULATING ARITHMETIC OPERATIONS

Expression Description

=[Subtotal] + [Freight] The sum of the values of the Subtotal and Freight fields.

=[RequiredDate] -[ShippedDate]

The difference between the values of the RequiredDate andShippedDate fields.

=[Price] * 1.06The product of the value of the Price field and 1.06 (adds 6percent to the Price value).

=[Quantity] * [Price] The product of the values of the Quantity and Price fields.

=[EmployeeTotal] / [CountryTotal]

The quotient of the values of the EmployeeTotal andCountryTotal fields.

Notes 

  In the ControlSource property of a calculated control, precede the expressionwith the = operator. On a data access page, you can omit the = operator, and typean alias instead; for example, type ExtendedPrice: [Quantity] * [Price].

  When you set the Name property of a calculated control in a form or report, or setthe ID property of a calculated control on a data access page, make sure to use aunique name. Don't use the name or ID of one of the controls that you used in theexpression.

  In an expression on a form or report, you can use the name of a control or thename of a field in the underlying record source. In an expression on a data accesspage, you can use only the name of a field that's in the data definition of the page.

  When you use an arithmetic operator (+, -, *, / ) in an expression, and the value of one of the controls in the expression is Null, the result of the entire expressionwill be Null. On a form or report, if some records in one of the controls that youused in the expression might have a Null value, you can convert the Null value tozero by using the Nz function; for example:

Page 42: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 42/50

MICROSOFT ACCESS

Page 42

=Msodsc.Nz([Subtotal]) + Msodsc.Nz([Freight])

EXAMPLES OF CONDITIONAL EXPRESSIONS

The following table lists examples of expressions that you can use in calculated controls

on forms, reports, and data access pages.

Expression Description

=IIf([Confirmed] = "Yes", "OrderConfirmed", "Order Not Confirmed")

Displays the message "Order Confirmed" if the value of the Confirmed field is Yes;otherwise, it displays the message "OrderNot Confirmed."

=IIf(IsNull([Country])," ", [Country])Displays an empty string if the value of theCountry field is Null; otherwise, it displaysthe value of the Country field.

=IIf(IsNull([Region]),[City]&" "&[PostalCode], [City]&" "&[Region]&" "&[PostalCode])

Display the values of the City andPostalCode fields if Region is Null;otherwise, it displays the values of the City,Region, and PostalCode fields.

=IIf(IsNull([RequiredDate] -[ShippedDate]), "Check for a missingdate", [RequiredDate] - [ShippedDate])

Display the message "Check for a missingdate" if the result of subtracting ShippedDatefrom RequiredDate is Null; otherwise, itdisplays the difference between the values of the RequiredDate and ShippedDate fields.

Notes 

  In the ControlSource property of a calculated control, precede the expressionwith the = operator. On a data access page, you can omit the = operator, and typean alias instead; for example, type DisplayCountry: IIf(IsNull([Country]),"

",[Country]).  When you set the Name property of a calculated control in a form or report, or set

the ID property of a calculated control in a data access page, make sure to use aunique name. Don't use the name or ID of one of the controls that you used in theexpression.

EXAMPLES OF EXPRESSIONS THAT USE AGGREGATE FUNCTIONS

Expression Description

=Avg([Freight]) Uses the Avg function to display the average of the values of theFreight control.

=Count([OrderID]) Uses the Count function to display the number of records in the

Page 43: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 43/50

MICROSOFT ACCESS

Page 43

OrderID control.

=Sum([Sales]) Uses the Sum function to display the sum of the values of theSales control.

=Sum([Quantity] *

[Price])

Uses the Sum function to display the sum of the product of the

values of the Quantity and Price controls.

=[Sales] / Sum([Sales])* 100

Displays the percentage of sales, determined by dividing thevalue of the Sales control by the sum of all the values of theSales control.

Note If the control's Format property is set to Percent, don'tinclude the *100.

Notes 

  In a calculated control, precede the expression with the = operator.

  When you set the Name property of a calculated control, make sure you use aunique name. Don't use the name of one of the controls you used in theexpression.

RANGES OF VALUES (>, <, >=, <=, <>, OR BETWEEN...AND)

Expression Result

> 234 For a Quantity field, numbers greater than 234

< 1200.45 For a UnitPrice field, numbers less than 1200.45

>= "Callahan"For a Last Name field, all names from Callahan throughthe end of the alphabet

Between #2/2/1999# And#12/1/1999#

For an OrderDate field, dates from 2-Feb-99 through 1-Dec-99 (ANSI-89)

Between '2/2/1999' And'12/1/1999'

For an OrderDate field, dates from 2-Feb-99 through 1-Dec-99 (ANSI-92)

Values that don't match (Not)

Expression Result

Not "USA" For a ShipCountry field, orders shipped to countries other than the USA

Not 2 For an ID field, the employee whose ID doesn't equal 2

Not T* For a Last Name field, employees whose names don't start with the letter

Page 44: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 44/50

MICROSOFT ACCESS

Page 44

"T" (ANSI-89)

Not T%For a Last Name field, employees whose names don't start with the letter"T" (ANSI-92)

Values in a list (In)

Expression Result

In("Canada", "UK") For a ShipCountry field, orders shipped to Canada or the UK

In(France, Germany,Japan)

For a CountryName field, employees living in France orGermany or Japan

Text, partial, and matching values

Expression Result

"London" For a ShipCity field, orders shipped to London

"London" Or "Hedge End" For a ShipCity field, orders shipped to London or HedgeEnd

>="N"For a CompanyName field, orders shipped to companieswhose name starts with the letters N through Z

Like "S*"For a ShipName field, orders shipped to customers whose

name starts with the letter S (ANSI-89)Like "S%" For a ShipName field, orders shipped to customers whose

name starts with the letter S (ANSI-92)

Right([OrderID], 2) = "99" For an OrderID field, orders with ID values ending in 99

Len([CompanyName]) >Val(30)

For a CompanyName field, orders for companies whosename is more than 30 characters long

Part of a field's value (Like)

Expression Result

Like "S*"For a ShipName field, orders shipped to customers whose names startwith the letter S (ANSI-89)

Like "S%" For a ShipName field, orders shipped to customers whose names startwith the letter S (ANSI-92)

Like For a ShipName field, orders shipped to customers whose names end

Page 45: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 45/50

MICROSOFT ACCESS

Page 45

"*Imports" with the word "Imports" (ANSI-89)

Like"%Imports"

For a ShipName field, orders shipped to customers whose names endwith the word "Imports" (ANSI-92)

Like "[A-D]*"

For a ShipName field, orders shipped to customers whose names start

with A through D (ANSI-89)

Like "[A-D]%"

For a ShipName field, orders shipped to customers whose names startwith A through D (ANSI-92)

Like "*ar*"For a ShipName field, orders shipped to customers whose names includethe letter sequence "ar" (ANSI-89)

Like "%ar%" For a ShipName field, orders shipped to customers whose names includethe letter sequence "ar" (ANSI-92)

Like "Maison

Dewe?"

For a ShipName field, orders shipped to the customer with "Maison" asthe 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 (ANSI-89)

Like "MaisonDewe_"

For a ShipName field, orders shipped to the customer with "Maison" asthe first part of its name and a 5-letter second name in which the first 4letters are "Dewe" and the last letter is unknown (ANSI-92)

Dates

Expression Result

#2/2/2000# For a ShippedDate field, orders shipped onFebruary 2, 2000 (ANSI-89)

'2/2/2000'For a ShippedDate field, orders shipped onFebruary 2, 2000 (ANSI-92)

Date() For a RequiredDate field, orders for today'sdate

Between Date( ) And DateAdd("M", 3,Date( ))

For a RequiredDate field, orders requiredbetween today's date and three months fromtoday's date

< Date( ) - 30 For an OrderDate field, orders more than 30days old

Year([OrderDate]) = 1999 For an OrderDate field, orders with orderdates in 1999

DatePart("q", [OrderDate]) = 4 For an OrderDate field, orders for the fourthcalendar quarter

DateSerial(Year ([OrderDate]), For an OrderDate field, orders for the last day

Page 46: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 46/50

MICROSOFT ACCESS

Page 46

Month([OrderDate]) + 1, 1) - 1 of each month

Year([OrderDate]) = Year(Now()) AndMonth([OrderDate]) = Month(Now())

For an OrderDate field, orders for the currentyear and month

A blank field's value (Null or zero-length string)

Expression Result

Is Null For a ShipRegion field, orders for customers whose ShipRegion field is Null(blank)

Is Not Null For a ShipRegion field, orders for customers whose ShipRegion fieldcontains a value

" " For a Fax field, orders for customers who don't have a fax machine,

indicated by a zero-length string (zero-length string: A string that containsno characters. You can use a zero-length string to indicate that you knowthere's no value for a field. You enter a zero-length string by typing twodouble quotation marks with no space between them (" ").)value in the Faxfield instead of a Null (blank) value

The result of a sub query as criteria

Expression Result

(SELECT [UnitPrice] FROM [Products]

WHERE [ProductName] = "AniseedSyrup")

For a UnitPrice field, products whose price is

the same as the price of Aniseed Syrup

> (SELECT AVG([UnitPrice]) FROM[Products])

For a UnitPrice field, products that have aunit price above the average

> ALL (SELECT [Salary] FROM[Employees] WHERE ([Title] LIKE"*Manager*") OR ([Title] LIKE "*VicePresident*"))

For a Salary field, the salary of every salesrepresentative whose salary is higher thanthat of all employees with "Manager" or"Vice President" in their titles

> ALL (SELECT AVG([UnitPrice] *[Quantity]) FROM [Order Details])

For an OrderTotal: [Unit Price] * [Quantity]calculated field, orders with totals that are

higher than the average order value

MANIPULATE TEXT VALUES

Expression Result

Page 47: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 47/50

MICROSOFT ACCESS

Page 47

FullName: [FirstName] & " " &[Last Name]

Displays in the FullName field the value of theFirstName and Last Name fields, separated by aspace

Address2: [City] & " " & [Region]

& " " & [PostalCode]

Displays in the Address2 field the value of the City,

Region, and PostalCode fields, separated by spacesProductInitial:Left([ProductName], 1)

Displays in the ProductInitial field the first characterof the value in the ProductName field

TypeCode: Right([AssetCode], 2) Displays in the TypeCode field the last twocharacters of the value in the AssetCode field

AreaCode: Mid([Phone], 2, 3) Displays in the AreaCode field the three charactersstarting with the second character of the value in thePhone field

PERFORM ARITHMETIC OPERATIONS

Expression Result

PrimeFreight: [Freight] *1.1

Displays in the PrimeFreight field freight charges plus 10percent

OrderAmount: [Quantity]* [UnitPrice]

Displays in the OrderAmount field the product of the valuesin the Quantity and UnitPrice fields

LeadTime:

[RequiredDate] -[ShippedDate]

Displays in the LeadTime field the difference between the

values in the RequiredDate and ShippedDate fields

TotalStock:[UnitsInStock] +[UnitsOnOrder]

Displays in the TotalStock field the sum of the values in theUnitsInStock and UnitsOnOrder fields

FreightPercentage:Sum([Freight]) / Sum([Subtotal]) * 100

Displays in the FreightPercentage field the percentage of freight charges in each subtotal, by dividing the sum of thevalues in the Freight field by the sum of the values in theSubtotal field.

The Total row in the design grid must be displayed, and theTotal cell for this field must be set to Expression.

If the Format property of the field is set to Percent, don'tinclude the *100.

SumofUnits:Nz([UnitsInStock], 0) +

Displays in the SumofUnits field the sum of all units in stock and on order.

Page 48: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 48/50

MICROSOFT ACCESS

Page 48

Nz([UnitsOnOrder], 0)When you use an arithmetic operator (+, -, *,  / ) in anexpression and the value of one of the fields in the expressionis Null, the result of the entire expression will be Null. If some records in one of the fields you used in the expression

might have a Null value, you can convert the Null value tozero using the Nz function.

MANIPULATE AND CALCULATE DATES

Expression Result

LagTime: DateDiff("d",[OrderDate], [ShippedDate])

Display in the LagTime field the number of daysbetween the order date and ship date

YearHired: DatePart("yyyy",

[HireDate])

Displays in the YearHired field the year each

employee was hiredMonthNo: DatePart("M",[OrderDate])

Displays in the MonthNo field the number of themonth

PriorDate: Date( ) - 30 Displays in the PriorDate field the date 30 daysprior to the current date

Use SQL and domain aggregate functions

Expression Result

Count(*) Uses the Count function to count the number of records inthe query, including records with Null (blank) fields

FreightPercentage:Sum([Freight]) / Sum([Subtotal]) * 100

Displays in the FreightPercentage field the percentage of freight charges in each subtotal, by dividing the sum of thevalues in the Freight field by the sum of the values in theSubtotal field.

The Total row in the design grid must be displayed, and theTotal cell for this field must be set to Expression.

If the Format property of the field is set to Percent, don'tinclude the *100.

AverageFreight:DAvg("[Freight]","[Orders]")

Displays in the AverageFreight field the average discountgiven on all orders combined in a totals query

Page 49: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 49/50

MICROSOFT ACCESS

Page 49

Work with Null values

Expression Result

CurrentCountry: IIf(IsNull([Country]), "", [Country])

Displays in the CurrentCountry field anempty string if the Country field is Null;otherwise, it displays the contents of theCountry field

LeadTime: IIf(IsNull([RequiredDate] -[ShippedDate]), "Check for a missingdate", [RequiredDate] - [ShippedDate])

Displays in the LeadTime field the message"Check for a missing date" if the value of either the RequiredDate or ShippedDatefields is Null; otherwise, it displays thedifference

SixMonthSales: Nz([Qtr1Sales], 0) +Nz([Qtr2Sales], 0)

Displays in the SixMonthSales field the totalof the values in the first-quarter and second-quarter sales fields combined, using the Nz function to convert the Null values to zerofirst

USE A SUBQUERY

Expression Result

Category: (SELECT [CategoryName] FROM[Categories] WHERE[Products].[CategoryID] =[Categories].[CategoryID])

Displays in the Category field theCategoryName if the CategoryID fromthe Categories table is the same as theCategoryID from the Products table

Examples of expressions used in update queries

Use expressions such as the following in the Update To cell in the query design grid forthe field you want to update.

Expression Result

"Salesperson" Changes a text value to Salesperson

#8/10/99# Changes a date value to 10-Aug-99

Page 50: Access Doc 1 Notes

8/2/2019 Access Doc 1 Notes

http://slidepdf.com/reader/full/access-doc-1-notes 50/50

MICROSOFT ACCESS

Yes Changes a No value in a Yes/No field to Yes

"PN" & [PartNumber] Adds PN to the beginning of each specified part number

[UnitPrice] * [Quantity] Calculates the product of UnitPrice and Quantity

[Freight] * 1.5 Increases freight charges by 50 percentDSum("[Quantity] *[UnitPrice]","Order Details","[ProductID]=" &[ProductID])

Where the Product IDs in the current table match theProduct IDs in the Order Details table, updates salestotals based on the product of Quantity and UnitPrice

Right([ShipPostalCode], 5)Truncates the leftmost characters, leaving the fiverightmost characters

IIf(IsNull([UnitPrice]), 0,[UnitPrice])

Changes a Null value to a zero (0) in the UnitPrice field

EXAMPLES OF EXPRESSIONS USED IN SQL STATEMENTS

You can use an expression in many places in an SQL statement, as the followingexamples show. Expressions are shown in bold text.

Expression Result

SELECT [FirstName], [Last Name] FROM[Employees] WHERE [Last Name] ="Davolio";

Displays the values in the FirstName andLast Name fields for employees whoselast name is Davolio.

SELECT [ProductID], [ProductName] FROM[Products] WHERE [CategoryID] =

Forms![New Products]![CategoryID];

Displays the values in the ProductID andProductName fields in the Products tablefor records in which the CategoryIDvalue matches the CategoryID valuespecified in an open New Products form.

SELECT Avg([ExtendedPrice]) AS [AverageExtended Price] FROM [Order DetailsExtended] WHERE [ExtendedPrice] > 1000;

Displays in a field named AverageExtended Price the average extendedprice of orders for which the value in theExtendedPrice field is more than 1,000.

SELECT [CategoryID],Count([ProductID]) AS [CountOfProductID]FROM [Products] GROUP BY [CategoryID]HAVING Count([ProductID]) > 10;

Displays in a field namedCountOfProductID the total number of products for categories with more than10 products.