Download presentation
Presentation is loading. Please wait.
1
ACCESS Tables Chapter 3
2
Michael alexander, dick kusleika: access 2016 bible
Study Objectives Creating new tables Modifying the design of a table Working with field properties Specifying a primary key Adding indexes Documenting a table’s design Saving a new table Working with tables Adding data to a table Using attachment fields Michael alexander, dick kusleika: access 2016 bible
3
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
4
Michael alexander, dick kusleika: access 2016 bible
Naming Tables 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 Michael alexander, dick kusleika: access 2016 bible
5
5 Steps to Creating a Table
Create a new empty table Add fields (with their datatypes and properties) Se 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 Michael alexander, dick kusleika: access 2016 bible
6
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 ion the right Michael alexander, dick kusleika: access 2016 bible
7
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 Michael alexander, dick kusleika: access 2016 bible
8
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 Michael alexander, dick kusleika: access 2016 bible
9
Michael alexander, dick kusleika: access 2016 bible
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 The other tools will be discussed later Michael alexander, dick kusleika: access 2016 bible
10
Michael alexander, dick kusleika: access 2016 bible
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! Michael alexander, dick kusleika: access 2016 bible
11
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
12
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
13
Michael alexander, dick kusleika: access 2016 bible
Data Types - Cont’d Date/Time 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 Michael alexander, dick kusleika: access 2016 bible
14
Michael alexander, dick kusleika: access 2016 bible
Data Types - Cont’d AutoNumber 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 Michael alexander, dick kusleika: access 2016 bible
15
Michael alexander, dick kusleika: access 2016 bible
Data Types - Cont’d Hyperlink 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 Michael alexander, dick kusleika: access 2016 bible
16
Michael alexander, dick kusleika: access 2016 bible
Practice Let’s create the tblCustomers as defined by Table 3.1 The Collectible Mini Cars Customer Table on page 40 Michael alexander, dick kusleika: access 2016 bible
17
Changing a Table Design
You can change the design of a table at any time by: Adding, removing or renaming fields Changing field properties You must be careful with changes once data is present in the tables Changing the size of a field to make it smaller might truncate values already present Changing field names might affect many other DB objects making reference to that field Inserting a field Place cursor on the field after which you would like to insert Click the Insert Rows button in the ribbon Continue editing the field as usual Field order does not matter in a DB Michael alexander, dick kusleika: access 2016 bible
18
Changing a Table Design – cont’d
Deleting a field Click the row selector for the field you would like to delete (the grey square at its left) Click the Delete Row button in the ribbon If there is data in that field already, you will get a warning that data will be lost If the field is part of a relationship, the relationship must be deleted first If the field was used in queries, forms, reports, etc. all those have to be fixed If at all possible, stay away from deleting fields Rearranging fields Functionally speaking, the order of fields does not matter In the datasheet view, fields are shown left to right in the order they were entered in the design view You may want to change the order of fields to make the most frequently used fields visible in the datasheet view without scrolling To move a field click on the field selector (the field name) and drag it where you want it Michael alexander, dick kusleika: access 2016 bible
19
Changing a Table Design – cont’d
Changing a field name Click on the field name in the Design View and type a new name No issue when the table is new All warning for deleting a field apply to renaming (after all, renaming a field is like deleting the old one and adding a new one with a different name) If at all possible, stay away from renaming fields Changing field sizes Select the field in Design View and edit in the property table Size increases are easy and safe Size decreases will truncate existing data if data items larger than the new size already exist Michael alexander, dick kusleika: access 2016 bible
20
Michael alexander, dick kusleika: access 2016 bible
Changing Data Types Specific data types are associated with specific ways of storing the data If you wish to change the data type, a conversion must take place, but not all conversions are safe (or even possible) Any type -> AutoNumber: can’t be done Short Text -> Number, Currency, Date/Time or Yes/No As long as the syntax of the Short Text is consistent with the new type, conversion is OK Data with the wrong syntax is deleted E.g., a Short Text field containing the text “January 28, 2016” will convert correctly to a Date/Time, but will be deleted if converted to a Yes/No field Long Text -> Short Text: OK, but any field with more than 255 characters will be truncated Number -> Short Text: OK Number -> Currency: may lose precision, because Currency uses fixed decimal precision Date/Time -> Short Text: OK Michael alexander, dick kusleika: access 2016 bible
21
Changing Data Types – cont’d
Currency -> Short Text: OK (conversion is done without currency symbol) Currency -> Number: OK, as long as the Number specifies precision and size bigger than for Currency Auto Number -> Short Text: OK, as long as you specify enough characters to hold the largest number present in the table AutoNumber -> Number: OK, as long as you chose a big enough number size E.g., if you make the new field an integer and you have more records than 32,767 the values will be truncated, and you will have multiple records with the same (low) number Yes/No -> Short Text: OK Michael alexander, dick kusleika: access 2016 bible
22
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
23
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) More details later 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. Michael alexander, dick kusleika: access 2016 bible
24
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. More details later Michael alexander, dick kusleika: access 2016 bible
25
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. More details later 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 Michael alexander, dick kusleika: access 2016 bible
26
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 More details later Michael alexander, dick kusleika: access 2016 bible
27
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
28
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 Michael alexander, dick kusleika: access 2016 bible
29
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 Michael alexander, dick kusleika: access 2016 bible
30
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 Michael alexander, dick kusleika: access 2016 bible
31
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
32
Michael alexander, dick kusleika: access 2016 bible
Other Formats Yes/No 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# Michael alexander, dick kusleika: access 2016 bible
33
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
34
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
35
Michael alexander, dick kusleika: access 2016 bible
Input Mask Examples Canadian Postal Code >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 paranthesis 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 Michael alexander, dick kusleika: access 2016 bible
36
Michael alexander, dick kusleika: access 2016 bible
Input Mask Wizard When you place the cursor in the field’s Input Mask box, an ellipsis appears at the far right Click on the ellipsis to start the Input Mask Wizard, a tool to help build input masks You can select pre-existing masks You can specify if you need to store the special characters or not You can specify what the placeholder should be The wizard completes the input mask string for you You can edit it further at a later time Michael alexander, dick kusleika: access 2016 bible
37
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
38
Michael alexander, dick kusleika: access 2016 bible
Indexing Indexes are additional data structures created for specific fields that allow fast searching The Indexed property has three values No (default) - field not indexed Yes (Duplicates OK) - field is indexed and duplicate values are allowed Yes (No Duplicates) - field is indexed, and the values in this field must be unique Indexing is trading data entry time against search time A primary key field is always indexed Tip: index only fields used very often in very large tables Michael alexander, dick kusleika: access 2016 bible
39
Michael alexander, dick kusleika: access 2016 bible
AutoIndex option Access has an option (File – Options – Object Designer) that can set up automatic indexing for any field with a name that contains certain strings In the example below, all fields containing ID, key, code or num in their name will be indexed automatically Michael alexander, dick kusleika: access 2016 bible
40
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
41
Michael alexander, dick kusleika: access 2016 bible
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 Michael alexander, dick kusleika: access 2016 bible
42
Michael alexander, dick kusleika: access 2016 bible
Manipulating Tables To save a table: Click File, then Save Click the Save button on the Quick Access Toolbar You can also use Save As… to create a new table When you go to another object, or switch the view, Access asks you to save the table To rename a table, right click its name in the navigation panel and select Rename To delete a table, right click its name in the navigation panel and select Delete To add data into a table, open the table by double clicking its name in the Navigation pane) and start typing; move to the next field by clicking Enter An alternate way is to use a form… more about that in the Forms part of the course Michael alexander, dick kusleika: access 2016 bible
43
Manipulating Tables – cont’d
To copy a table, you have three options Copy the structure only – creates a new table with the same structure but no data Copy Structure and Data – creates an identical copy of the first table Append data to an existing table; of course, the structure of the two tables must be the same E.g.: you may have a monthly transaction table, and a yearly archive table for the same transactions; at the end of each month you might want to copy the first table by adding it to the second one To execute the copy: Select the table Click Copy on the ribbon (Home tab) Click Paste on the ribbon (Home tab) A dialogue appears to allow you to: Pick one of the three options above Enter the name of the new table Click OK to complete the process You can use the same mechanism to copy a table from one DB to another Michael alexander, dick kusleika: access 2016 bible
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.