Introduction to Relational Databases |
|
Fundamentals of a Relational Database
Introduction
A relational database is an application that contains various tables where values in a table are made available to records in another table so that data entered in one table is not entered again in another table. To have a relational database, there must be relationships created among that tables that need to exchange data.
Practical Learning: Introducing Data Relationships
CREATE TABLE Agents ( AgentCode char(12), FirstName text(20), LastName text(20), Title string(50), PayFrequency varchar(25) );
CREATE TABLE Companies ( CompanyCode char(10), Companyname text(60) );
CREATE TABLE Transactions ( TransactionID Long, TransactionDate date, AgentCode char(12), CompanyCode char(10), NumberOfShares Long, PricePerShare double, PaymentStatus string(25) );
Introduction to Relation Keys
When it comes to relational databases, a key in a table is a field or a combination of columns used to manage the flow of records from one list or table, referred to as the source, to another list or table, referred to as the target. Relational databases support the primary and the foreign keys.
A primary key in a table is a field or a combination of columns that makes sure that each record is unique in that table. This means that a primary key can use one or more fields in a table.
Primary Keys
Visually Creating a Primary
To visually create a primary key, start a table in the Design View, specify the name and data type of the new field that will be used as the primary key, or display an existing table in Design View. In the top side of the Design View window, click the field that will be used as the primary key. Although a primary key can use almost any type of data, the most common types are:
Although the other data types (floating-point numbers, Boolean values, dates, etc) are not excluded, they are not good candidates for primary keys. Once you have specified the column name and its type:
The field that is made the primary key would then appear with a key icon to its left. When you click a field that is a primary key, the Primary Key button becomes highlighted .
As mentioned above, a primary key can use more than one column. To visually create such a primary key, display the table in Design View. Select, as a group, the fields that would constitute the primary key. Then:
Each one of the fields would appear with a key icon on its left:
Practical Learning: Introducing Primary Keys
Creating a Primary Key in SQL
To programmatically create a primary key in SQL, you have many options, all of them use the PRIMARY KEY expression on the list of flags. The simplest technique is to add that expression at the end of the column creation. Here is an example:
Private Sub cmdTable_Click()
DoCmd.RunSQL "CREATE TABLE Departments(Gender varchar(20) PRIMARY KEY);"
End Sub
A Primary Key Constraint
A primary key is referred to as a constraint because it makes sure that each record is unique among the other records of its table. To re-enforce, a formula to create a primary key is:
CONSTRAINT PrimaryKeyName PRIMARY KEY(ColumnName)
In this formula, the CONSTRAINT (case-insensitive) keyword and the PRIMARY KEY (case-insensitive) expression are required. In the PrimaryKeyName placeholder, enter the name you want to give to the primary key. In the parentheses of the PRIMARY KEY expression, enter the name of the column that will be used as the primary key. Here is an example:
Private Sub cmdTable_Click()
DoCmd.RunSQL "CREATE TABLE Persons" & _
"(" & _
" PersonalIdentification char(10)," & _
" FirstName varchar(20)," & _
" LastName varchar(20) NOT NULL," & _
" CONSTRAINT PrimKeyPeople PRIMARY KEY(PersonalIdentification)" & _
");"
End Sub
By convention or tradition, the name of the primary starts with PK_ followed by the name of the table. Here is an example:
Private Sub cmdTable_Click()
DoCmd.RunSQL "CREATE TABLE Persons" & _
"(" & _
" PersonalIdentification char(10)," & _
" FirstName varchar(20)," & _
" LastName varchar(20) NOT NULL," & _
" CONSTRAINT PK_People PRIMARY KEY(PersonalIdentification)" & _
");"
MsgBox "A table named Persons has been created"
End Sub
Practical Learning: Creating Primary Key Constraint
CREATE TABLE AccountsTypes ( AccountType char(20), Description LongText, CONSTRAINT PK_AccountsTypes PRIMARY KEY(AccountType) );
CREATE TABLE TransactionsTypes ( TransactionType char(20), Description LongText, CONSTRAINT PK_TransactionsTypes PRIMARY KEY(TransactionType) );
CREATE TABLE AccountsStatus ( AccountStatus char(20), Description LongText, CONSTRAINT PK_AccountsStatus PRIMARY KEY(AccountStatus) );
CREATE TABLE ChargesReasons ( ChargeReason char(20), Description LongText, CONSTRAINT PK_ChargesReasons PRIMARY KEY(ChargeReason) );
CREATE TABLE CurrenciesTypes ( CurrencyType char(20), Description LongText, CONSTRAINT PK_CurrenciesTypes PRIMARY KEY(CurrencyType) );
CREATE TABLE Locations ( LocationCode string(10), Location string(10), Address text(50), City text(40), State char(2), ZIPCode varchar(20), Description LongText, CONSTRAINT PK_Locations PRIMARY KEY(LocationCode) );
Adding a Primary Key to an Existing Table
Consider two tables named Departments and Employees and created using the following code:
Private Sub cmdCreateTables_Click() DoCmd.RunSQL "CREATE TABLE Departments" & _ "(" & _ " DepartmentCode varchar(5)," & _ " DepartmentName Text(50)," & _ ");" DoCmd.RunSQL "INSERT INTO Departments VALUES('HMNRS', 'Human Resources');" DoCmd.RunSQL "INSERT INTO Departments VALUES('ITSUP', 'Information Technology and Support');" DoCmd.RunSQL "INSERT INTO Departments VALUES('RSDEV', 'Research & Development');" DoCmd.RunSQL "CREATE TABLE Employees" & _ "(" & _ " FirstName Text(24)," & _ " LastName Text(24)," & _ " DepartmentCode varchar(5)" & _ ");" End Sub
You may already know how to modify an existing table to add a new column. If you have a table that has a column that can be used as the primary key, create an ALTER TABLE expression. To create a primary key, add an ADD CONSTRAINT clause that uses the same formula as if you were creating a primary key. The formula to follow is:
ALTER TABLE TableName ADD CONSTRAINT Statement
Here is an example:
Private Sub cmdMakePrimaryKey_Click() DoCmd.RunSQL "ALTER TABLE Departments " & _ "ADD CONSTRAINT PK_Departments PRIMARY KEY(DepartmentCode);" End Sub
To add a new column that would be the primary key, create an ALTER TABLE ... ADD COLUMN statement. To set the new column as a primary key, add a PRIMARY KEY constraint. Here is an example:
Private Sub cmdCreatePrimaryKey_Click() DoCmd.RunSQL "ALTER TABLE Employees " & _ "ADD COLUMN EmployeeNumber varchar(10)," & _ "CONSTRAINT PK_Employees PRIMARY KEY(EmployeeNumber);" End Sub
Foreign Keys
Introduction
A foreign key is a column on a table whose data is coming from another table. That data is coming from the primary key of another table. This means that you must first create a table that has a primary key. The table that contains a primary key and that holds the information that another table would use is called the primary table or the parent table. The table that will receive the information from the other table is called the foreign table or the child table.
Visually Creating a Foreign Key
To create a foreign key in a table, display it in either the Datasheet View or the Design View. If you are working in the Design View and you are creating a new foreign key, specify the name of the new column. Whether you are working in the Datasheet View or the Design View, the only real rule you must observe is that the column must have the same data type as that of the primary key with which it will communicate. If the primary key is using a (short) string with a length or a Field Size set, the foreign key should (must) use the same type and the same maximum length.
Creating a Foreign Key in SQL
The formula to create a foreign key in the SQL is:
ColumnName DataType REFERENCES ParentTableName(ForeignKeyCcolumn)
The REFERENCES keyword is required. In the ParentTableName placeholder, enter the name of the table that holds the primary key. In the
parentheses of
CREATE TABLE Departments(Gender varchar(20) PRIMARY KEY); CREATE TABLE Persons ( PersonalIdentification char(10), FirstName varchar(20), LastName varchar(20) NOT NULL, Gender varchar(20) REFERENCES Departments(Gender), CONSTRAINT PK_Persons PRIMARY KEY(PersonalIdentification) );
A Foreign Key Constraint
The above technique allows you to ask the database engine to give a name to the foreign key you are creating. An alternative is to specify a name of your choice. To do this, after the list of columns of the table, create a foreign key constraint with an explicit name. Here is an example:
Private Sub cmdCreateForeignKey_Click() DoCmd.RunSQL "CREATE TABLE CoursesLevels" & _ "(" & _ " CourseLevel varchar(25), " & _ " Comments note, " & _ " CONSTRAINT PK_CoursesLevels PRIMARY KEY(CourseLevel) " & _ ");" DoCmd.RunSQL "CREATE TABLE Courses" & _ "( " & _ " CourseCode varchar(10) not null, " & _ " CourseName varchar(60), " & _ " CourseLevel varchar(20), " & _ " Notes note, " & _ " CONSTRAINT FK_CourseLevels Foreign Key(CourseLevel) " & _ " REFERENCES CoursesLevels(CourseLevel), " & _ " CONSTRAINT PK_Courses PRIMARY KEY(CourseCode) " & _ ");" End Sub
Practical Learning: Creating Foreign Key Constraints
CREATE TABLE Employees ( EmployeeNumber text(10), FirstName varchar(20), MiddleName varchar(20), LastName varchar(20), LocationCode string(10), Title varchar(50), CanCreateNewAccount bit, CONSTRAINT FK_EmployeesLocations FOREIGN KEY(LocationCode) REFERENCES Locations(LocationCode), CONSTRAINT PK_Employees PRIMARY KEY(EmployeeNumber) );
CREATE TABLE Customers ( AccountNumber text(10), EmployeeNumber text(10), DateCreated date, AccountType char(20), FirstName varchar(20), MiddleName varchar(20), LastName varchar(20), AccountStatus char(20), CONSTRAINT FK_AccountsCreators FOREIGN KEY(EmployeeNumber) REFERENCES Employees(EmployeeNumber), CONSTRAINT FK_AccountsTypes FOREIGN KEY(AccountType) REFERENCES AccountsTypes(AccountType), CONSTRAINT FK_AccountStatus FOREIGN KEY(AccountStatus) REFERENCES AccountsStatus(AccountStatus), CONSTRAINT PK_Customers PRIMARY KEY(AccountNumber) );
Adding a Foreign Key to an Existing Table
Consider the following table named Courses:
Private Sub cmdCreateTable_Click() DoCmd.RunSQL "CREATE TABLE CoursesLevels" & _ "(" & _ " CourseLevel varchar(25), " & _ " Comments note, " & _ " CONSTRAINT PK_CoursesLevels PRIMARY KEY(CourseLevel) " & _ ");" DoCmd.RunSQL "CREATE TABLE Courses" & _ "( " & _ " CourseCode varchar(10) not null, " & _ " CourseName varchar(60), " & _ " Notes note, " & _ " CONSTRAINT PK_Courses PRIMARY KEY(CourseCode) " & _ ");" End Sub
If you have an existing table, you can add a new column that would act as a foreign key. This is done by creating an ALTER TABLE...ADD COLUMN expression. Here is an example:
Private Sub cmdCreateForeignKey_Click() DoCmd.RunSQL "ALTER TABLE Courses " & _ "ADD COLUMN CourseLevel varchar(25) " & _ " REFERENCES CoursesLevels(CourseLevel);" End Sub
As mentioned already, this type of code lets the database engine specify the name of the foreign key. If you want to create a name of your choice, explicitly create a constraint and give it a name. Here is an example:
Private Sub cmdCreateForeignKey_Click()
DoCmd.RunSQL "ALTER TABLE Courses " & _
"ADD COLUMN CourseLevel varchar(25), " & _
"CONSTRAINT FK_CoursesLevels FOREIGN KEY(CourseLevel) " & _
" REFERENCES CoursesLevels(CourseLevel);"
End Sub
Imagine you have a table that has a column that is in fact the foreign key of a parent table but the column was not specified as such. To formally change such as a column into a foreign key, start an ALTER TABLE expression and add a foreign key that indicates the parent table and the corresponding column. Here is an example:
Private Sub cmdAddForeignKey_Click() DoCmd.RunSQL "ALTER TABLE Employees " & _ "ADD CONSTRAINT FK_Departments FOREIGN KEY(DepartmentCode) " & _ " REFERENCES Departments(DepartmentCode);" End Sub
Practical Learning: Adding Foreign Keys to a Table
ALTER TABLE AccountsHistories ADD COLUMN AccountNumber text(10), CONSTRAINT FK_CustomersHistories FOREIGN KEY(AccountNumber) REFERENCES Customers(AccountNumber);
ALTER TABLE AccountsHistories ADD COLUMN AccountStatus text(20), CONSTRAINT FK_AccountsStatus FOREIGN KEY(AccountStatus) REFERENCES AccountsStatus(AccountStatus);
Introduction
A relationship diagragram is a graphic used to visualize the relationships among the tables of a database. To assist with this visualization, Microsoft Access provides the Relationships window. To get it:
After clicking one of those, to add a table, click it, click Add, and click Close
When you are working on the relationships of your tables, the Ribbon is equipped with a tab labeled design and that includes two sections:
If the Show Table dialog box has been closed and if you want to show it:
After working with the Relationships window, you can close it by clicking its Close button . You would be asked to save it in order to keep the relationship(s) created.
Establishing a Relationship
To establish a relationship between two tables, you can drag the primary key from the parent table to the foreign key of the desired table.
Practical Learning: Establishing a Relationship
Managing Relationships
If you create primary keys and foreign keys in a database, when you open the Relationships window, the database engine will be aware of the relationships already for the tables that have the primary keys and foreign keys.
Practical Learning: Using a Relationship Diagram
|
||
Previous | Copyright © 2022, FunctionX, Inc. | Next |
|