Download presentation
Presentation is loading. Please wait.
1
MS Access 2016 Concepts
2
Why do we need databases
There are many ways to store and analyze data (documents, spreadsheets, text files, images, Instagram, social media feeds, etc.) More structure => more powerful ways to use the data E.g., you can do much more with data in a spreadsheet compared to data in a document There are many things you cannot do any other way than using a database: Have multiple views of the data for different uses Ensure data is consistent and error free Easily select subsets of data as needed for a particular purpose Understand and visualize relationships between data Avoid data duplication … and many, many more AP/ITEC 1010 – Information and Organizations January 8, 2017
3
Databases & DBMS Formally, a "database" refers to a set of related data and the way it is organized. Access to this data is usually provided by a “DataBase Management System" (DBMS) which is an integrated set of computer software that allows users to interact with the databases, provides access to all of the data contained in the databases, and the tools required to work with them. Relational databases are databases that define and manage relationships between entities (tables of columns and rows, with a unique key identifying each row). AP/ITEC 1010 – Information and Organizations January 8, 2017
4
Tables and Entities Generally, each table/relation represents one "entity type" E.g., Products The rows represent instances of that type of entity Also referred to as a record E.g., CoffeeMaker The columns represent values attributed to that instance Also referred to as a field E.g., ProductCode (key), Make, Model, Price, etc. Tables are usually viewed as a datasheet (much like a spreadsheet) A value is the intersection of a row and a column E.g., Nespresso might be the value of the Make field for the CoffeeMaker record in the Products table AP/ITEC 1010 – Information and Organizations January 8, 2017
5
Queries A query is a request for information from the database
Based on a certain set of criteria for selecting the relevant information Usually specified in a query language SQL - Structured Query Language DBM systems usually have tools for building a query visually The data returned by the query is presented in a table format AP/ITEC 1010 – Information and Organizations January 8, 2017
6
Forms and Reports A form is a window or screen that contains numerous fields, or spaces to enter data. Each field holds a field label so that any user who views the form gets an idea of its contents. A form is more user friendly than generating queries to create tables and insert data into fields A database report is the formatted result of database queries and contains useful data for decision-making and analysis. AP/ITEC 1010 – Information and Organizations January 8, 2017
7
Creating a DB The first step is to design the various DB objects (tables, queries, forms, reports, etc.) The better your design is, the better your DB and its usage will be Good design will be beneficial later, when you need to expand, enhance and upgrade Principles of good design: Never duplicate data Build in as many safeguards against bad data entry as possible Understand as best you can how the DB will be used Understand how the job is done now, and what are the issues with the current approach AP/ITEC 1010 – Information and Organizations January 8, 2017
8
The Welcome Screen When you start Access 2016 you will see a screen like this You can: Open any of the DB files you have worked with recently listed (top left) Search your computer for other DB files (just below) Create a new empty database (click on top leftmost icon in the right pane) Create a new DB file using a template from the right pane (click the relevant icon in the right pane) Templates are pre-designed databases which you can modify later to suit your specific needs Search for a template on the web (top middle) AP/ITEC 1010 – Information and Organizations January 8, 2017
9
Creating a Blank DB Most often, we start with an empty DB
When you click on the Blank DB icon, you will get a screen like this It shows the Access interface, with: one table (named Table1) with a default primary key named ID (a sequential integer) opened in datasheet view AP/ITEC 1010 – Information and Organizations January 8, 2017
10
Access Interface – The Ribbon
At the top of the screen we have the ribbon, consisting of: A row of icons, containing the most frequently used tools (Quick Access Toolbar) You can customize this row by clicking on the rightmost icon A row of tabs for navigating to all other tools Clicking on each tab brings out all corresponding tools right below the menu Over and above the 5 tabs in the images to the right, contextual tabs appear when appropriate Greyed out icons are for tools that are not applicable in the current context AP/ITEC 1010 – Information and Organizations January 8, 2017
11
Access Interface – The Navigation Pane
At the left of the screen we have the navigation pane (first image to the right) It contains a list of all DB objects, grouped by type: Tables, Queries, Reports, Forms, etc. Each category has a double arrow icon pointed up when the category is expanded or down when it is hidden On the top right we have two more icons: A double arrow pointing left, for shrinking the navigation pane; when shrunk, the navigation pane looks like the second image on the right, and the icon changes to a double arrow pointing right, for expanding it again A circle containing a triangle pointing down, for organizing the navigation pane differently By date of creation By date of modification, Filtered by group Custom AP/ITEC 1010 – Information and Organizations January 8, 2017
12
Tabbed Windows As you open different objects all information about those objects is displayed in the main pane Each object cases the creation of a tab on the main pane, so you can easily navigate between objects The contents of the main pane is different depending on: What type of object it is What view was selected for that object We will detail these as we go through the details of creating each type of object AP/ITEC 1010 – Information and Organizations January 8, 2017
13
Table (Entity) Relationships
Table (entity) relationships become important in order to sort out what belongs where When entities are related, we need a simple way for one of them to refer to the other E.g., Customers and Orders – each order must have a customer Customer data lives in the Customer table and Order data lives in the Order table A specific order (a row in the Order table) must be able to refer to a specific customer Therefore, Customers must have a unique identifier, say Customer_ID; this is called a primary key Orders on the other hand, must have a data item (say Ordering_Customer) which will contain the unique identifier of the customer whose order this is; this is called a foreign key It is not unusual to use the same field name for both primary key and foreign key in the two tables, because this helps us identify the relationship AP/ITEC 1010 – Information and Organizations January 8, 2017
14
Relationship Cardinality
When entities are related, there are several types of relationships, depending on how many instances of each entity are involved in the relationship; this is called cardinality One-to-one relationships are relationships where exactly one instance of each entity is involved E.g.: Person and Passport (a person can have only one passport, and a passport belongs to one person – ignoring dual citizenship) In this cases, we want to instinctively treat them as one entity (i.e., put all the passport info such as date of issue, expiry, passport number, etc. as fields in the Person table). Don’t do that. These are different entities logically, and we may need (now or later) to work with them separately. It would be hard to generate a list of passports expiring next month, if that data is in the Person table One-to-many relationships are relationships where one instance of one entity can be associated with multiple instances of the other; these are the most frequent relationships E.g.: Customer and Order (an order has exactly one customer, but a Customer can have many orders Placing a CustomerId field as a foreign key in the Order table allows this relationship to be used in the DB Many-to-many relationships are relationships where several instances of one entity can be associated with several instances of the other E.g.: Book and Author (A book can have multiple authors, and an author can write multiple books) This relationship requires the creation of a special table, called junction (join) table AP/ITEC 1010 – Information and Organizations January 8, 2017
15
Relationships Example
AP/ITEC 1010 – Information and Organizations January 8, 2017
16
Referential Integrity
When relationships exist between tables, it is important that certain rules be followed for the data to make sense In a payroll application, any check must refer to an employee; it is essential that such an employee exists (as in the employee id referenced in the check record must exist in the employee table) You cannot delete an employee record while check records exist referring to that employee If for some reason the id of an employee changes, all checks issued to that employee have to also change to use the new id Referential integrity rules ensure that operations that would result in corrupted or meaningless data cannot occur AP/ITEC 1010 – Information and Organizations January 8, 2017
17
Referential Integrity Rules
Referential integrity operates based on key fields RI Rule #1: No Primary Key can contain a null value (i.e.: you must provide a unique value for the Primary Key of each record RI Rule #2: All Foreign Key values must be matched by a corresponding Primary Key value More specifically: Rows cannot be added to the “many side” table if a corresponding record does not exist in the “one side” table The Primary Key value on the “one side” cannot be changed if the “many side” already contains records containing that value; A record on the “one side” cannot be deleted if the “many side” already contains records containing the Primary Key value of that record Benefits of Primary Keys: Primary Keys are always indexed, so searches in keyed tables are faster Access forces you to enter a unique value in a Primary Key field, ensuring integrity AP/ITEC 1010 – Information and Organizations January 8, 2017
18
Creating Relationships in Access
Select Database Tools tab and click the Relationships tool You will see the list of tables to the right Click Add to add tables to the relationship window Drag the Primary Key from the “one side” to the Foreign Key of the “many side” to open the Edit Relationship window below Select the Integrity Rules you want Click Create AP/ITEC 1010 – Information and Organizations January 8, 2017
19
Types of Tables While in Access tables are created, managed, updated, etc. the same way, we can classify them into three categories based on their use: Object tables are the most common, and they are tables that hold information about a real world object A Customer is a real world concept, and a table like tblCustomer holds all the relevant information about each customer A special subtype of object tables are Lookup tables; they are very simple tables, usually containing some reference data, such as a list of provinces, list of countries, list of currencies, list of locations, etc. Transaction tables are tables that hold information about an event Placing an order for a book, is an event. A table like tblBookOrder will hold all the details about an order. Typical fields in a transaction table are date/time stamps, and one or more references to records in other (object) tables, identifying entities that are party to this transaction (such as customer id, book id, etc. Join tables are tables that implement many-to-many-relationships E.g.: a book may have many authors, and an author may have written many books You can’t put author names in the book table, because you don’t know how many fields to allocate for that; Conversely, you cannot put a book title field in the authors table, because of the same reason A join table resolves this issue; it usually has a name that explains the association (e.g., tblAuthorBook) and three fields: A unique identifier for one book-author association (primary key) A unique identifier for each side of the relationship (author and book) – two foreign keys AP/ITEC 1010 – Information and Organizations January 8, 2017
20
Naming Conventions It is important to have a good approach to naming DB content As the DB grows, names that are simple, clear, and descriptive are more and more important Choosing the right name upfront is very important, because if you change it later, it will break almost every object based on that table It is typical to use a three letter prefix to designate the type of object tbl for tables frm for forms rpt for reports qry for queries Names should be descriptive for the entity the tables represents (up to 64 characters) So called “Camel Case” is used (prefix starts with lower case, every English word in the name is uppercase Spaces are allowed in a name, but avoid them; some special characters are also allowed Join tables usually refer to both entities involved AP/ITEC 1010 – Information and Organizations January 8, 2017
21
5 Steps to Creating a Table
Create a new empty table Add fields (with their datatypes and properties) Set the primary key (if needed) Create indexes for the appropriate fields (if needed) Save the table design Tip: pay attention to field names: Like table names, they should be descriptive, clear, and follow a naming convention Adding fields later is almost never a problem, but changing field names is always a big headache Because of that, Access provides an Auto Correct function; most developers turn it off, because it adversely affect performance, and its ability to correct is still limited To turn it off, click File, Options, Current Database and scroll down to “Perform name AutoCorrect” and clear the checkmark AP/ITEC 1010 – Information and Organizations January 8, 2017
22
Creating a New Empty Table
Click the Create tab to bring up the relevant tools Clicking the Table button adds a table with a default id and no fields and opens it in datasheet view looking like this: Clicking the Table Design button adds a table with no fields that looks like the image on the right AP/ITEC 1010 – Information and Organizations January 8, 2017
23
Adding Fields in the Datasheet View
Type data in the space under “Click to Add” Hit the Enter (or Tab) key The text in the field name changes to Field1, Field2, etc. and a new column is created, also headed as “Click to Add” Right click on Field1, Field2, etc. and select “Rename Field” to provide the correct field name As data is entered, you will notice various greyed out tools “coming to life” allowing you to select data types and properties for the field More about that later AP/ITEC 1010 – Information and Organizations January 8, 2017
24
Adding Fields in the Design View
In Design view, you do not actually add any data Instead, you add the field name, its data type, and its description As your cursor is in a specific field, the table below provides a list of properties The contents of the properties table changes by data type You set up the properties by editing the lines in the properties table Most people prefer the design view for creating tables, because it allows you to focus on the design of the table (as opposed to the data content). When you are in the Design View, a new tab is added to the ribbon, the Design Tab AP/ITEC 1010 – Information and Organizations January 8, 2017
25
The Design Tab One or more rows are selected by clicking (and dragging) on the grey box in front of each row Tools in the ribbon act on the selected row(s) Primary Key sets the selected field(s) as the primary key (more about that later) Insert Rows inserts a row in the design view to allow you to place a new field between two existing fields Many people prefer to have a specific order of fields, although it does not matter to the DB Delete Rows deletes the fields in the selected rows Property Sheet opens the property sheet for the entire table (as opposed to property sheet for each field AP/ITEC 1010 – Information and Organizations January 8, 2017
26
Field Name Rules Up to 64 characters
Letters, numbers and special characters, except ! ` [] () . and control characters Cannot start with a space “Camel Case” is commonly used Make names significant and descriptive Remember: if you have to change field names later, after reports, forms and queries have been created, you are in for a long and tedious effort, so chose well upfront! AP/ITEC 1010 – Information and Organizations January 8, 2017
27
Data Types Data Types are a shorthand for describing what kind of data is going to be stored in a field and what kind of operations will be performed with that data Additional properties will be set using the properties table Short Text Up to 255 characters, but you can set a lower size Access uses variable length fields to store data if you set the limit to say 25, but use 5 in a given record, only 5 characters are saved Good practice to set field sizes correctly Long Text Variable amount of data up to 1GB Only actual needed space is used You do not specify a size for these AP/ITEC 1010 – Information and Organizations January 8, 2017
28
Data Types - Number Number
Used for numeric data (as in data to be used in calculations, as opposed to data consisting of digits) Quantity is numeric data Phone number and SIN are not Design your tables taking a very conservative view about large values If you don’t, and eventually the database needs larger values, the DB application will fail On the other hand, use the most economical reasonable size, because storing small values in large size fields impacts performance AP/ITEC 1010 – Information and Organizations January 8, 2017
29
Data Types - Cont’d Date/Time Currency
Specialized for storing date and time (together) Easy to do specialized calculations Don’t separate date and time Currency Specialized number No rounding 15 digits of precision to the left of the decimal point 4 digits of precision to the right of the decimal point Faster than regular numeric Interacts with Windows regional settings AP/ITEC 1010 – Information and Organizations January 8, 2017
30
Data Types - Cont’d AutoNumber Yes/No
Another specialized number field, limited to one per table Inserts a long integer starting with 1 and incremented by one every time a new record is added Can be used as a default primary key, but cannot be edited Yes/No Another specialized number field, stores -1 for Yes, 0 for No Uses one bit of storage, and is used for binary values yes/no, true/false, on/off, etc. Shows as check box in datasheet view OLE (Object Linking and Embedding) Object Stores entire objects created in other OLE enabled applications such as Word, Excel, etc. Beyond our scope AP/ITEC 1010 – Information and Organizations January 8, 2017
31
Data Types - Cont’d Hyperlink Attachment Calculated Lookup Wizard
Most often used to link to a web resource (such as a web page) Attachment A more generic way of placing an entire file in a DB field Even though the source file is usually on your computer, a copy of the file is stored within the DB, so the size of the DB grows fast with attachments… so use sparingly Calculated A number field whose value is calculated (as a formula) based on other fields (such as [quantity]*[unitPrice] Lookup Wizard A mechanism for setting up a field whose values can only be selected from entries in another table (called lookup table) such as a list of Provinces in an address Actual type end up being Short Text, with Lookup property filled out AP/ITEC 1010 – Information and Organizations January 8, 2017
32
Field Properties Field properties are a very powerful feature of Access They help maintain correctness, consistency, etc. They are enforced by the DB engine Each data type has its own set of properties Number fields have Decimal Places property Text fields have Text Align Property values can be: Free format, where the values are typed in (perhaps with constraints) E.g.: Field Size for Short Text is a value between 1 and 255 Fixed values, usually represented by keywords You cycle through possible values by double clicking the value E.g.: A Number can have a Field Size of: Byte, Integer, Long Integer, Single, Double, ReplicationID, and Decimal AP/ITEC 1010 – Information and Organizations January 8, 2017
33
Commonly Used Field Properties
Field Size Applicable to: AutoNumber, Short Text, and Number (although specified in different ways) Number between 1 and 255 for Short Text, expressing the maximum number of characters allowed in the field Various values for Number fields Format Applicable to: every data type except Attachment Describes ways of presenting the data after being entered (in views, reports and forms Does not change the actual data (it affects only the presentation) Input Mask Applicable to: Short Text, Number, Date/Time and Currency Forces data to be entered in a predefined format Useful for data items like ZIP codes, phone numbers, etc. AP/ITEC 1010 – Information and Organizations January 8, 2017
34
Commonly Used Field Properties – cont’d
Decimal Places Applicable to: Number (depending on Field Size setting) and Currency Specifies the number of decimal positions after the decimal point Caption Applicable to: all data types Specifies a label to be used to identify the field in forms and reports If not present, the field name is used instead Useful when field names are not very user friendly Default Value Applicable to: all data types except AutoNumber, Attachment and Calculated Specifies a value to be pre-filled during data entry Useful for data items like ZIP codes, phone numbers, etc. AP/ITEC 1010 – Information and Organizations January 8, 2017
35
Commonly Used Field Properties – cont’d
Validation Rule Applicable to: all data types except AutoNumber, Attachment and Calculated Specifies business rules that limit the values entered in the field E.g.: date must be past a certain date, value must be at least 100, etc. Validation Text Error message to be displayed when data entry fails the validation Usually explains the user what the validation criteria is Required Applicable to: all data types except AutoNumber, Yes/No and Calculated If set to Yes, forces users to enter some data in this field AP/ITEC 1010 – Information and Organizations January 8, 2017
36
Commonly Used Field Properties – cont’d
Allow Zero Length Applicable to: Short Text and Long Text Specifies if an empty string is allowed as input A string with no characters in it (empty string) is logically different from not entering a value at all (null value) Indexed Applicable to: all data types except Attachment and Calculated If specified creates a mechanism that speeds up searching this table on this field AP/ITEC 1010 – Information and Organizations January 8, 2017
37
Format Access provides built-in formats related to the Region and Language setting in Windows (or similar Operating System settings in other Operating Systems) Formatting options vary by data type; E.g.: Date/Time has a general format (complete) and then Long, Medium and Short Date and the same for Time Yes/No has formatting options to show as Yes/No, True/False or On/Off Numbers can be formatted as general, currency, scientific notation, percentage, etc. You can create custom formats Important: formatting does not change data, it only affects how data is displayed AP/ITEC 1010 – Information and Organizations January 8, 2017
38
Custom Numeric Formats
Custom numeric formats are created using the following symbols . (period) for the location of the decimal point , (comma) for the thousands separator 0 for a digit, which if not present will be replaced by a 0 # for a digit, which if not present will be replaced by a space $ for the dollar sign % multiplies the value by 100 and adds the % sign E- or e- uses the scientific notation and shows a minus sign for negative exponents E+ or e+ uses the scientific notation and shows a plus sign for positive exponents You can specify a format for each of: positive values, negative values, zero values, null values, in this order, separated by a semicolon; you can also insert a color for each section E.g.: 0, [Green]; (0,000.00) [Red]; “Zero”; “-” Will show all numbers with exactly 6 digits, padded with 0’s as need, in green if positive, or in red and in parenthesis if negative; If zero, no numbers are shown, the text “Zero” is entered instead; if no value was entered, a dash is shown AP/ITEC 1010 – Information and Organizations January 8, 2017
39
Standard Numeric Formats
General: equivalent to #.### Currency: equivalent to $#,##0.00;($#.##0.00) Euro: equivalent to € #,##0.00;(€ #.##0.00) Fixed: equivalent to #.## Standard: equivalent to #,##0.00 Percent: equivalent to #.##% Scientific: equivalent to 0.00E+00 AP/ITEC 1010 – Information and Organizations January 8, 2017
40
Standard Date/Time Formats
General Date: Displays only date, if no time specified in the data, and the other way around Date is displayed in Short Date format Time is displayed in Long Time format Long Date: Tuesday, November 1, 2016 Medium Date: 1-Nov-16 Short Date: 11/1/2016 Long Time: 6:30:00 PM Medium Time: 6:30 PM Short Time: 18:30 These options are more than enough, but you can customize further (see text for codes) Use upper or lower case for AM / PM, leading zeros, and combinations of the formats above AP/ITEC 1010 – Information and Organizations January 8, 2017
41
Custom Text Formats You can use the following format codes:
< to force all text to lower case > to force all text to upper case @ to indicate a mandatory position (a position where either provided input or a space is displayed) & to indicate an optional character (a position where if no input is present, nothing is displayed) Any text you type appears as typed, in the appropriate spot You can specify three format strings separated by semicolon, for strings, zero- length strings, and no content respectively, in that order would: Keep the text as typed if any Display “None” if you type an empty string Display “Unknown” if nothing was entered AP/ITEC 1010 – Information and Organizations January 8, 2017
42
Other Formats Yes/No data type Hyperlink data type Yes/No True/False
On/Off ;”Text for Yes values”;”Text for No values” E.g.: ;”Training completed”;”Must attend training” Any format you chose, the data stored is still -1 for Yes (or equivalent) and 0 for No (or equivalent) Hyperlink data type Display text#URL E.g.: Prof. Pateanu’s Website# AP/ITEC 1010 – Information and Organizations January 8, 2017
43
Input Mask An Input Mask is used to force users to enter data in a prescribed way to help avoid errors Enter SIN numbers as exactly 9 digits Enter phone numbers as 10 digits Enter Canadian postal codes as a sequence of letter, digit repeated three times, separated by a dash in the middle and with upper case letters only Input masks have three parts, separated by semicolons: The mask itself The digit 0 or 1, indicating whether special characters in the mask are to be stored with the data (0) or not (1) A character to be used as placeholder for the content until actual data is entered Placeholders provide a visual clue as to how many characters are expected They are replaced by actual content as you type # or * is used most often AP/ITEC 1010 – Information and Organizations January 8, 2017
44
Input Mask Codes Codes used:
Separators: . , : ; - / (depend on system setting for Region and Language) < and > to force lower and upper case respectively ! To start entering data from left to right \ to show the following character as is “text” to insert the text as typed Codes in the table below: Input Required Code if Mandatory Code if Optional Digit without sign 9 Letter L ? Letter or digit A a Any character or space & C AP/ITEC 1010 – Information and Organizations January 8, 2017
45
Input Mask Examples Canadian Postal Code Canadian SIN
>L0L\-0L0;1;# Canadian SIN 000\-000\-000;0;# International standard phone number \+990\(990\)9000\-0000;1;# Allows 1-3 digit country codes Allows 1-3 digit area codes in parenthesis Allows 7 or 8 digits in the phone number, with the last 4 digits preceded by a dash Note: Formats take precedence over input masks; typically one or the other is used AP/ITEC 1010 – Information and Organizations January 8, 2017
46
Validation Rules Setting up validation rules can create sophisticated formulae for making sure data is logically valid for the designed purpose Validation can involve macros and other coded functions, which are out of our scope Here are some simple examples of validation rules: Is “M” OR “F” allows only the upper case M or upper case F as input – might be good for gender field Is IN (“ON”,”QC”,”AB”) would allow only ON, QC or AB as entries – might be good for province codes Is Like would allow at least one character followed followed by at least one character followed by . Followed by at least one character – might be good for an >=0 allows only positive numbers Between 0000 and 9999 allows only 4 digit numbers Is Like ????? Accepts exactly 5 characters Is Not Like “*[!a-z]*” accepts only letters Is Not Like “*[!0-9]*] accepts only digits < #1/1/2019# requires a date no later than 2018 Don’t forget to set up a Validation Text to let the user know what is expected AP/ITEC 1010 – Information and Organizations January 8, 2017
47
Validation Rules - Examples
AP/ITEC 1010 – Information and Organizations January 8, 2017
48
Validation Rules - Examples
AP/ITEC 1010 – Information and Organizations January 8, 2017
49
Lookup Property The Property table has a second tab labelled Lookup
It allows you to select different visual controls associated with field The usual visual control for entering data is Text Box – a box where you type data Yes/No fields have another visual control, the check box Text fields can also have Combo Box or List Box as visual controls (known as drop down) The two are similar; the differences are beyond our scope, so use Combo Box as default Additional properties on the Lookup tab allow you to specify: The source of data, typically another table, or a list of values (when short) How many rows to display in the drop down How wide the drop down should be Whether the user must chose from the list provided, or can add new values Whether multiple choices are allowed or not You can also do multiple column lists, but that is out of our scope Lookup is very useful for keeping data consistent and correct AP/ITEC 1010 – Information and Organizations January 8, 2017
50
Primary Keys Often we need to uniquely identify every record in a table To do so, a field in the table (or a combination of fields) must hold unique values across the entire table Such a field is called a Primary key AutoNumber type fields are an automatic way of creating a primary key, but often other fields are more appropriate (e.g.: student number, SIN, Driver’s License, etc.) To create a primary key Select the field(s) and click the Primary Key icon in the ribbon, or Right click on the field and select the Primary Key option (only works for single field key) Save the table, and when asked allow Access to create an AutoNumber primary key AP/ITEC 1010 – Information and Organizations January 8, 2017
51
What Can Queries Do? Chose one table, or combine data from several tables Chose specific fields needed for a purpose, while omitting fields that are not needed Select only certain records in the table(s) based on specific criteria Sort the selected records in some specific order Perform calculations (over and above calculated fields in a table) E.g.: averages, totals, counts, etc. Create new tables based on their output Feed their output to a form or report Use the output of another query as a data source for a new query Modify data in a table based on their results (these queries are called action queries) AP/ITEC 1010 – Information and Organizations January 8, 2017
52
How Queries Work The data output of a query is called a recordset
By default, recordsets are displayed in the datasheet view You cannot tell a table from a recordset just by looking at the output Recordsets are dynamic Only the defining structure of the query is stored in the query object The actual data is collected anew every time the query runs So if you run a query, then change data in tables and run the same query again, your table changes will be reflected in the recordset When the recordset is bound to a form or report, the query is re-run every time the form or report is opened Recordsets can be also used in macros and VBA procedures (out of scope) AP/ITEC 1010 – Information and Organizations January 8, 2017
53
Using the Query Wizard For a few basic kinds of queries you can use the Query Wizard Select the Create tab and click the Query Wizard icon to get to the screen on the top right Click OK to get to the screen at the bottom right Select the tables you want, successively, using the Tables/Queries dropdown For each table select the fields you want by clicking on a filed in the Available Fields box and then on the right arrow in the middle AP/ITEC 1010 – Information and Organizations January 8, 2017
54
Using the Query Wizard – cont’d
… Click Next when you are done, to get to the screen at the right Enter the name of your query at the top Decide if you want to run the query first or go straight to modifying the design Note that you did not have an opportunity to put in criteria, sorting, show, etc. so in most cases further design work is needed Click Finish to complete the process While it can be a modestly faster way to put together a query, since most of the time additional design is needed the wizard is not all that useful AP/ITEC 1010 – Information and Organizations January 8, 2017
55
Working with Fields in the QBE
Select a field by clicking in any place in its column, or the field selector (the grey box above the field’s name in the QBE) Reorder fields by dragging the field selector to a new location Resize the column of a field by positioning the cursor on the vertical line between field columns until the cursor becomes a double arrow and drag the separating line to where you want it Remove a field by: Selecting the field and clicking the Delete Column icon Right clicking in the field selector and selecting Cut Insert a field by: Clicking in an existing field, and clicking the Insert Column tool (empty column inserted at the left of the existing field, then you drag a field to that column) Drag a field name over a column already in use; the new field is inserted before the field you dropped it on AP/ITEC 1010 – Information and Organizations January 8, 2017
56
Criteria for Text Fields
Record selection criteria for text fields fall into three kinds: Equality, where records selected contain in that field the text specified in the Criteria row E.g.: Entering the text “car” in the criteria for a Category field of a Product table will select only the cars from that table Inequality, where records selected contain in that field any text but the text specified in the Criteria row E.g.: Entering the text “not car” in the criteria for a Category field of a Product table will select only the records for items that are not cars from that table List of values, which works like equality, but with multiple values Each subsequent value is entered in a a new row in the or section of the QBE, or Use In(“a”, “b”, “c”) You can use Like and Not Like with strings containing the * symbol * is called a wild card, and it “matches” any string Like *ina selects any record that has a text value ending in “ina” Like [A-D]* selects any record that has a text value starting with the letter A, B, C, D You can use < or > before a string, to select records containing text lexically “less” or “more” then the following string AP/ITEC 1010 – Information and Organizations January 8, 2017
57
Criteria for other fields
Criteria for Number, Currency and AutoNumber fields Pretty much the same as for text fields, except that strings here must be numbers Criteria for Date/Time fields Pretty much like numbers, but the date must be in the #mm/dd/yyyy# format You can use the Date() function which return today’s date E.g.: Between Date() and Date()-6 returns all records dated in the last week You can use Year(), Month() and Day() with any date field as an argument to select based on that respective portion of a date E.g.: Year([SalesDate]) = Year(Date()) selects records with the date in the current year Use Is Null to find all records that have no value in a field AP/ITEC 1010 – Information and Organizations January 8, 2017
58
Parameter Queries Sometimes we need to design queries that are very similar E.g.: A sales database selling across Canada may want to determine at different times how many customers they have in a given province Sometimes that would be Ontario, some other times Quebec, etc. Dilemma: Do I need to design a query for every province? Solution: design a parameter query To transform a query into a parameter query you do this: In the Criteria for the field in question (in the example above the Province field) enter a text in square brackets containing the prompt to the user indicating what to provide as a parameter E.g.: [Enter province name: ] Now when you run the query, a pop up shows the text you entered and provides a space for the user to enter a value, say Ontario The effect is the same as if you entered Ontario in the criteria field instead of the prompt Now the query can be used to find customers in any one province AP/ITEC 1010 – Information and Organizations January 8, 2017
59
Why We Need Forms Forms allow us to view a record at a time showing all fields on a single page Forms provide the ability to enhance the user experience with explanations, help, controls, etc. Forms allow selective access to certain fields and protect others Forms are usually the access control mechanism (users get to see only forms, not underlying tables or queries) Forms can be used to navigate the application Forms can provide calculations AP/ITEC 1010 – Information and Organizations January 8, 2017
60
Create Form Ribbon Click on the Create tab
The Form section of the ribbon looks like this: Use the Form tool to create a form for entering all fields in a table one record at a time The form is created for the table currently highlighted in the navigation pane Use the Form Design tool to create a form from scratch in the design view Use the Blank Form tool to create a form from scratch in the layout view Layout view and design view are very similar, and most tasks can be performed in either (but not all) Design view shows more details related to the looks of the form, but no data, while the layout view shows the underlying data Use the Form Wizard tool to guide you through the creation of a simple form Unlike the Form tool, you can select only some fields in a table, you can chose from a few standard layouts, etc. Use the Navigation tool to create a form for navigating through the application A navigation form is essentially a tabbed sheet, each tab being further associated with another form The options you see when you click this tool refer to the arrangements of the tabs AP/ITEC 1010 – Information and Organizations January 8, 2017
61
Controls Forms are essentially a collection of controls
Some controls are bound, meaning they are tied to a field in a table The data in the field is displayed in the control Text boxes, list boxes, combo boxes, check boxes, etc. Other controls are unbound, meaning they help the user understand how to use the form Labels, lines, boxes, graphics, calculated controls, etc. When you start the creation of a form in design view, the ribbon will contain a collection of tools for creating the controls (see image below) Arrow tool is for selecting items, not a control These tools are located in the Design tab AP/ITEC 1010 – Information and Organizations January 8, 2017
62
Frequently Used Controls - 1
Text Box: bound control used to edit text data Label: unbound control for displaying text that does not change Button: unbound control usually used for running a VBA or macro Tab: unbound control for organizing the form’s controls into a tabbed style interface Hyperlink: unbound control for accessing another resource Opens up dialogue screen (see top right) for selecting the resource Resource is viewed in a separate window Web Browser: unbound control for a mini browser window Opens up dialogue screen (see bottom right) for selecting the page to display Resource is viewed right there on the form Control is bound to URL, not field in a table AP/ITEC 1010 – Information and Organizations January 8, 2017
63
Frequently Used Controls – 2
Navigation: bound control used to lay out multiple forms into a tabbed style interface Looks like the tab control, but it holds different objects Option Group: a control for a group of radio buttons, check boxes or toggle buttons Can be bound, but the entire group is bound, not each individual button or box In this case, each individual button has an associated value, and the field gets the selected value Can be unbound, in which case the content is used for dialogue with the user that drives further action Clicking the tool launches a wizard for construction the group AP/ITEC 1010 – Information and Organizations January 8, 2017
64
Frequently Used Controls – 3
Page Break: unbound control used to break long forms into multiple pages Used as an alternative to scrolling Requires setting up buttons or links to move between pages Tabbed forms are simpler Combo Box: bound control showing text fields with their Lookup property set to Combo Box Much like a lookup for datasheet view Clicking the tool launches a wizard for construction the control AP/ITEC 1010 – Information and Organizations January 8, 2017
65
Frequently Used Controls – 4
Chart: bound control used to display information in graphical format Clicking the tool launches a wizard for constructing the graph (see below) Line: unbound control used for esthetics (separating sections of the form) Toggle Button: bound control for showing Yes/No fields as a button that can be depressed or not List Box: bound control showing text fields with their Lookup property set to List Box As discussed when data properties were studied, we will use Combo Boxes only Rectangle: unbound control used for esthetics (separating sections of the form) AP/ITEC 1010 – Information and Organizations January 8, 2017
66
Frequently Used Controls – 5
Check Box: bound control for showing Yes/No fields as a checkmark Option Button: bound control for showing Yes/No fields as a radio button Image: bound control for displaying an image on the form In this case the binding is to an image file on your computer Usually used for esthetic reasons, such as logos, etc. AP/ITEC 1010 – Information and Organizations January 8, 2017
67
Adding Controls By clicking a tool icon in the Controls section of the Design ribbon Creates unbound control; if the control needs to be bound, do so using the property sheet By dragging a field from the field list – preferred option because it is most efficient Click the Add Existing Fields button on the ribbon to show a window for navigating to a field The control created is bound to the field MS Access choses a type of control that is consistent with the field data type By double clicking a field from the field list Same as by dragging a field, except MS Access decides where to put it (you can, of course, move it later) By right clicking a field in the field list and choosing Add Field to View Same as double clicking By copying and pasting an existing control Of course, you need to edit properties, otherwise you have useless duplication AP/ITEC 1010 – Information and Organizations January 8, 2017
68
Editing Controls To edit a control you must first select it
Click anywhere in the control to select it Hold down the shift key and click successive controls to select multiple controls Access handles appear on selected controls Image to the right shows controls both selected and not selected Resize controls by dragging handles Cursor changes in standard Windows fashion Move the control by dragging and dropping, or by selecting it and using the arrow keys Use the Arrange tab on the ribbon to show a wide assortment of tools that help with esthetics Sizing, alignment, spacing, etc. Use the Format tab on the ribbon to change the look of controls Colors, fonts, backgrounds, etc. AP/ITEC 1010 – Information and Organizations January 8, 2017
69
Why We Need Reports Reports present not just data from the tables, but also additional data, like: Subtotals and totals Statistics, like averages, median values, etc. Graphics that can help visualize the data Reports are designed to be printed, so they can be distributed (in paper or PDF format) to audiences who are not direct users of the DB system Comparing reports to forms They are very similar in many ways, and except data entry anything you can do with a form can be done with a report (forms can even be saved as a report) Generally, forms are aimed at data entry and user interactions, while reports are aimed at data visualization AP/ITEC 1010 – Information and Organizations January 8, 2017
70
Steps to Creating a Report
Define the report layout Decide on the report type, what information will be included and where each bit of information goes Decide data organization such as grouping and sorting Decide on the calculations, summaries, graphs, etc. to be included, and where they go Decide on additional information such as headers, footers, legends, instructions, paging, etc. Assemble the data From a single database table From a query that can combine data from many sources Create the report with the report wizard or from scratch Print or view the report Save the report AP/ITEC 1010 – Information and Organizations January 8, 2017
71
Using the Report Wizard
The first dialogue screen of the report wizard allows you to select the data that goes into the report Drop down on top allows you to select a table or a query The fields in the selected source appear in the window on the left Select fields you want in the report and click the single right arrow to add them Click the double right arrow to move all fields into the report Once fields are selected, the left arrows become available to reverse a selection AP/ITEC 1010 – Information and Organizations January 8, 2017
72
Report Wizard - Grouping
The second dialogue screen of the report wizard (image top right) allows you to select grouping levels When you select a field to group by: That filed becomes a heading That field is no longer listed in every record Remaining records are grouped under that heading, as long as they share the same value for the grouping field If you select a second grouping field The selected field becomes a subheading Grouping occurs for records with the same value for both fields Grouping Options (image bottom right) allows grouping on: The full field content, or The first 1-5 letters in the field Other options for numeric or date fields AP/ITEC 1010 – Information and Organizations January 8, 2017
73
Report Wizard - Sorting
The third dialogue screen of the report wizard allows you to specify sorting Groups are automatically sorted based on their data type Sorting options are provided for the rest of the data You can sort by up to four fields Sorting is done on a precedence basis In the example on the right, sorting is done on LastName, and if several records have the same last name, they will be further sorted based on FirstName AP/ITEC 1010 – Information and Organizations January 8, 2017
74
Report Wizard - Summaries
If numeric fields are present in your report, the sorting screen also displays a Summary Options button When you click this button, you get the screen on the right It shows all numeric fields, and checkmarks for selecting standard arithmetic calculations based on that field Show options: Default is Detail and Summary, to show both the actual data and the calculated values Summary Only option creates a so called Summary Report (where the underlying data is hidden) You can also add calculation of the percentage each sum represents out of the total of the relevant numbers AP/ITEC 1010 – Information and Organizations January 8, 2017
75
Report Wizard - Layout The fourth dialogue screen of the report wizard allows you to specify a layout for the report and its orientation Stepped Layout: First grouping filed value is on one line Second grouping field value is on the second line, indented Records are on the 3rd, 4th, etc. line, further indented Block Layout: Records are laid out one per row Grouping field values are listed only on the first row Outline Layout Similar to stepped, but column heading are repeated for each subgroup Orientation is the way the paper is positioned when printing Fields can be adjusted to fit to page AP/ITEC 1010 – Information and Organizations January 8, 2017
76
Report Layout Comparison
AP/ITEC 1010 – Information and Organizations January 8, 2017
77
Banded Report Design Concepts
The concept of grouping (and related possible calculations) and the fact that reports are also naturally divided into pages, leads to thinking about and designing reports in sections (bands) Hierarchy of sections: Report Page Group (and subgroups) Detail (records) Each section except detail has a header and a footer containing relevant information AP/ITEC 1010 – Information and Organizations January 8, 2017
78
Headers The Report Header prints at the beginning of the report and might contain: The name of the report Cover page with a summary of information describing the report and its use Might be enhanced with an image, and printed on a separate page Select the Report Header in the design view, click the Property Sheet icon and select After Section for the Force New Page property The Page Header prints at the top of every page and might contain: The name of the report (so unstapled pages can be organized correctly) Column headings Page number (can be in the footer) Graphics (such as a line) to separate from the rest of the page The Group Header prints at the top of each group and normally contains: The field value defining the group Graphics to visually distinguish the group AP/ITEC 1010 – Information and Organizations January 8, 2017
79
Footers The Report Footer prints at the end of the report and might contain: Grand totals and other report level statistics Note: when a page footer is present, it is printed after the report footer The Page Footer prints at the bottom of every page and might contain: Page numbers (best to use Page x of y format) Date and time of report printing Page level control totals The Group Footer prints at the bottom of each group and normally contains: Statistics for the group Graphics to visually distinguish the group Note: be careful with group calculations vs. page calculations… they can get confusing AP/ITEC 1010 – Information and Organizations January 8, 2017
80
Report Sections AP/ITEC 1010 – Information and Organizations
January 8, 2017
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.