|
Data Entry on Related Tables
|
|
|
Data Entry on a Primary Key
|
|
As mentioned already, when creating the records of a
table, assign the appropriate value for the primary key. Each value must be
unique.
|
Data Entry on a Foreign Key
|
|
The value of a foreign key column must exist in the
primary key of the table it represents. If the value cannot be found in the
parent table, you would receive an error. If you need to use a value that is
not in the parent table, first created it there, and then return to the
child table to create the record.
|
Practical
Learning: Creating Values for Foreign Keys
|
|
- Click inside the Query Editor and press Ctrl + A
- To create a few records and add values for foreign keys, type the
following code:
USE RealEstate1;
GO
INSERT INTO Listing.Properties
VALUES(N'52408180', N'1640 Lombardo Ave', N'Silver Spring', N'MD', N'20904', N'Single Family', 4, 2.5, 3, 1, 2, 1995, N'Good', 495880.00, N'Ready For Sale'),
(N'68830614', N'10315 North Hacht Rd', N'College Park', N'MD', N'20747', N'Single Family', 4, 3.5, 3, 1, 2, 2000, N'Excellent', 620724.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, Condition, FinishedBasement, Stories, MarketValue, SaleStatus)
VALUES(N'96114604', N'6366 Lolita Drive', N'Laurel', N'MD', N'20707', N'Good', 1, 2, 422625.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, PropertyType, Bedrooms, IndoorGarage, MarketValue)
VALUES(N'39485797', N'9002 Palasko Hwy', N'Tysons Corner', N'Condominium', 2, 2, 422895.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [State], ZIPCode, Bedrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'42081159', N'DC', N'20011', 2, 1982, 312555, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, PropertyType, Bedrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'97172037', N'Alexandria', N'22024', N'Single Family', 3, 1965, 345660.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State], PropertyType, Condition, Bedrooms, Bathrooms, MarketValue)
VALUES(N'20880417', N'4140 Holisto Crt', N'Germantown', N'MD', N'Condominium', N'Excellent', 2, 1, 215495.00);
GO
INSERT INTO Listing.Properties
VALUES(N'92747400', N'9522 Lockwood Rd', N'Chevy Chase', N'MD', N'20852', N'Townhouse', 3, 2.5, 3, 0, 1, 1992, N'Bad Shape', 415665.00, N'Ready For Sale'),
(N'20708150', N'14250 Parkdoll Rd', N'Rockville', N'MD', N'20854', N'Townhouse', 3, 2.5, 2, 1, 0, 1988, N'Good', 325995.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, PropertyType, Bedrooms, YearBuilt, MarketValue)
VALUES(N'29304857', N'Washington', N'Townhouse', 4, 1975, 366775.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, PropertyType, Condition, Bedrooms, Bathrooms, YearBuilt, MarketValue)
VALUES(N'28085040', N'10340 Helmes Street #408', N'Silver Spring', N'MD', N'20906', N'Condominium', N'Good', 1, 1, 2000, 242775.00);
GO
INSERT INTO Listing.Properties
VALUES(N'24747299', N'1008 Coppen Street', N'Silver Spring', N'MD', N'20906', N'Single Family', 3, 3, 3, 1, 3, 1996, N'Excellent', 625450.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, PropertyType, Stories, YearBuilt, MarketValue)
VALUES(N'39485070', N'Chevy Chase', N'20956', N'Single Family', 3, 2001, 525450.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State], PropertyType, Condition, Bedrooms, MarketValue, SaleStatus)
VALUES(N'29380597', N'686 Herod Ave #D04', N'Takoma Park', N'MD', N'Condominium', N'Excellent', 2, 360885.00, N'Sold');
GO
INSERT INTO Listing.Properties
VALUES(N'29744618', N'14005 Sniders Blvd', N'Laurel', N'MD', N'20707', N'Townhouse', 4, 1.5, 3, 1, 0, 2002, N'Needs Repair', 412885.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, Condition, Bedrooms, Stories, YearBuilt)
VALUES(N'28074085', N'Silver Spring', N'20905', N'Good', 4, 2, 1965);
GO
INSERT INTO Listing.Properties
VALUES(N'92417926', N'680 Prushia Rd NE', N'Washington', N'DC', N'20008', N'Single Family', 5, 3.5, 3, 0, 3, 2000, N'Good', 555885.00, N'Ready For Sale'),
(N'29407906', N'14688 Parrison Street', N'College Park', N'MD', N'20742', N'Single Family', 5, 2.5, 2, 1, 2, 1995, N'Excellent', 485995.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, PropertyType, Condition, Bedrooms, Bathrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'81115599', N'10340 Helmes Street #1012', N'Silver Spring',
N'MD', N'20906', N'Condominium', N'Good', 1, 1, 2000, 252775.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties
VALUES(N'44759760', N'4201 Vilamar Ave', N'Hyattsville', N'MD', N'20782', N'Townhouse', 3, 2, 2, 1, 2, 1992, N'Excellent', 365880.00, N'Ready For Sale');
GO
- To formally create the database, on the main menu, click Query ->
Execute
NULL should be avoided in any column that is
involved in a relationship. When creating the records of a table that has a
primary key, if you know that the child table will have records that do not
have a value in the parent table, in the parent table, create a "dummy"
record that has a value such as N/A, Not Available, Unknown,
or something like that.
|
Practical
Learning: Dealing With NULL Foreign Values
|
|
- Click inside the Query Editor and press Ctrl + A
- To show the listing of the properties, type the following code:
USE RealEstate1;
GO
SELECT PropertyNumber [Property #], City, [State],
PropertyType [Type], Bedrooms Beds,
Bathrooms Baths, YearBuilt [Year],
Condition, MarketValue "Market Value", SaleStatus "Status"
FROM Listing.Properties;
GO
- To execute, on the main menu, click Query -> Execute.
Notice that
you get 20 records. Also notice that a few properties have NULL as their
status

- To set a condition, such as to see only properties that are
currently listed as being on sale, change the statement as follows:
USE RealEstate1;
GO
SELECT props.PropertyNumber [Property #],
props.City, props.[State],
props.PropertyType [Type],
props.Bedrooms Beds,
props.Bathrooms Baths,
props.YearBuilt [Year],
props.Condition,
props.MarketValue "Market Value",
props.SaleStatus "Status"
FROM Listing.Properties props
WHERE props.SaleStatus = N'Ready For Sale';
GO
- To execute, press F5
Notice that you get 10 records of properties
that are ready for sale:

- To see properties that are not listed as being on sale, change the
statement as follows:
USE RealEstate1;
GO
SELECT props.PropertyNumber [Property #],
props.City, props.[State],
props.PropertyType [Type],
props.Bedrooms Beds,
props.Bathrooms Baths,
props.YearBuilt [Year],
props.Condition,
props.MarketValue "Market Value",
props.SaleStatus "Status"
FROM Listing.Properties props
WHERE NOT(props.SaleStatus = N'Ready For Sale');
GO
- To execute, press F5
Notice that you get 3 records

- Click inside the Query Editor and press Ctrl + A
- Remember that we don't know the status of properties whose sale
status is NULL: we don't know if those properties are ready for sale, if
they have been sold, or else. But, we want to see all properties that
are not currently listed as being on sale, even, or including, those
whose sale status is not known. To take care of this, type the following
code (we could have UPDATEd the table and the records, especially
if we were working in a production or commercial environ, but we are
choosing the easier way, which consists of recreating this small
database):
CREATE DATABASE RealEstate2;
GO
USE RealEstate2;
GO
CREATE SCHEMA Listing;
GO
CREATE TABLE Listing.PropertiesTypes
(
PropertyType nvarchar(20) PRIMARY KEY not null,
[Description] nvarchar(max),
);
GO
CREATE TABLE Listing.PropertiesConditions
(
Condition nvarchar(20),
[Description] nvarchar(max),
CONSTRAINT PK_PropertiesConditions PRIMARY KEY(Condition)
);
GO
CREATE TABLE Listing.SalesStatus
(
SaleStatus nvarchar(20),
[Description] nvarchar(max),
CONSTRAINT PK_SalesStatus PRIMARY KEY(SaleStatus)
);
GO
INSERT INTO Listing.PropertiesTypes
VALUES(N'Unknown', N'The property type was not specified or was not known'),
(N'Condominium', N'A condominium, also called condo, is a unit built in a small, medium, or large building. It ressembles an apartment. It may have one, two, or more bedrooms.'),
(N'Townhouse', N'A townhouse, sometimes called a town house or town home, is a relatively small house attached to at least another house.'),
(N'Single Family', N'A single family is a stand-alone house. It may have one, two or three levels, also called stories.');
GO
INSERT INTO Listing.PropertiesConditions
VALUES(N'Unknown', N'Unknown property condition'),
(N'Excellent', N'An excellent property is one that has everything perfect or almost. There are no major repairs to be made.'),
(N'Good', N'A property is good if it is good enough to be sold. It may be less than perfect but it is wholly acceptable.'),
(N'Needs Repair', N'This type of condition indicates that one or more repairs are necessairy. The property in this condition is not ready for sale.'),
(N'Bad Shape', N'A property is in bad shape if it requires a mojor or many repairs.');
GO
INSERT Listing.SalesStatus
VALUES(N'N/A', N'The sale status of this property is not definitely spaecified'),
(N'Ready For Sale', N'The property is currently available for sale.'),
(N'Sold', N'The property has been sold.');
GO
CREATE TABLE Listing.Properties
(
PropertyNumber nvarchar(12),
[Address] nvarchar(60),
City nvarchar(50),
[State] nchar(2),
ZIPCode nvarchar(12),
PropertyType nvarchar(20) default N'Unknown',
Bedrooms smallint,
Bathrooms float,
Stories smallint,
FinishedBasement bit,
IndoorGarage tinyint,
YearBuilt smallint,
Condition nvarchar(20) default N'Unknown',
MarketValue money,
SaleStatus nvarchar(20) default N'N/A',
CONSTRAINT PK_Properties PRIMARY KEY(PropertyNumber),
CONSTRAINT FK_PropertiesTypes FOREIGN KEY(PropertyType) REFERENCES Listing.PropertiesTypes(PropertyType),
CONSTRAINT FK_PropertiesConditions FOREIGN KEY(Condition) REFERENCES Listing.PropertiesConditions(Condition),
CONSTRAINT FK_SalesStatus FOREIGN KEY(SaleStatus) REFERENCES Listing.SalesStatus(SaleStatus)
);
GO
INSERT INTO Listing.Properties
VALUES(N'52408180', N'1640 Lombardo Ave', N'Silver Spring', N'MD', N'20904', N'Single Family', 4, 2.5, 3, 1, 2, 1995, N'Good', 495880.00, N'Ready For Sale'),
(N'68830614', N'10315 North Hacht Rd', N'College Park', N'MD', N'20747', N'Single Family', 4, 3.5, 3, 1, 2, 2000, N'Excellent', 620724.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, Condition, FinishedBasement, Stories, MarketValue, SaleStatus)
VALUES(N'96114604', N'6366 Lolita Drive', N'Laurel', N'MD', N'20707', N'Good', 1, 2, 422625.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, PropertyType, Bedrooms, IndoorGarage, MarketValue)
VALUES(N'39485797', N'9002 Palasko Hwy', N'Tysons Corner', N'Condominium', 2, 2, 422895.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [State], ZIPCode, Bedrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'42081159', N'DC', N'20011', 2, 1982, 312555, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, PropertyType, Bedrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'97172037', N'Alexandria', N'22024', N'Single Family', 3, 1965, 345660.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State], PropertyType, Condition, Bedrooms, Bathrooms, MarketValue)
VALUES(N'20880417', N'4140 Holisto Crt', N'Germantown', N'MD', N'Condominium', N'Excellent', 2, 1, 215495.00);
GO
INSERT INTO Listing.Properties
VALUES(N'92747400', N'9522 Lockwood Rd', N'Chevy Chase', N'MD', N'20852', N'Townhouse', 3, 2.5, 3, 0, 1, 1992, N'Bad Shape', 415665.00, N'Ready For Sale'),
(N'20708150', N'14250 Parkdoll Rd', N'Rockville', N'MD', N'20854', N'Townhouse', 3, 2.5, 2, 1, 0, 1988, N'Good', 325995.00, N'Sold');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, PropertyType, Bedrooms, YearBuilt, MarketValue)
VALUES(N'29304857', N'Washington', N'Townhouse', 4, 1975, 366775.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, PropertyType, Condition, Bedrooms, Bathrooms, YearBuilt, MarketValue)
VALUES(N'28085040', N'10340 Helmes Street #408', N'Silver Spring', N'MD', N'20906', N'Condominium', N'Good', 1, 1, 2000, 242775.00);
GO
INSERT INTO Listing.Properties
VALUES(N'24747299', N'1008 Coppen Street', N'Silver Spring', N'MD', N'20906', N'Single Family', 3, 3, 3, 1, 3, 1996, N'Excellent', 625450.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, PropertyType, Stories, YearBuilt, MarketValue)
VALUES(N'39485070', N'Chevy Chase', N'20956', N'Single Family', 3, 2001, 525450.00);
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State], PropertyType, Condition, Bedrooms, MarketValue, SaleStatus)
VALUES(N'29380597', N'686 Herod Ave #D04', N'Takoma Park', N'MD', N'Condominium', N'Excellent', 2, 360885.00, N'Sold');
GO
INSERT INTO Listing.Properties
VALUES(N'29744618', N'14005 Sniders Blvd', N'Laurel', N'MD', N'20707', N'Townhouse', 4, 1.5, 3, 1, 0, 2002, N'Needs Repair', 412885.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, City, ZIPCode, Condition, Bedrooms, Stories, YearBuilt)
VALUES(N'28074085', N'Silver Spring', N'20905', N'Good', 4, 2, 1965);
GO
INSERT INTO Listing.Properties
VALUES(N'92417926', N'680 Prushia Rd NE', N'Washington', N'DC', N'20008', N'Single Family', 5, 3.5, 3, 0, 3, 2000, N'Good', 555885.00, N'Ready For Sale'),
(N'29407906', N'14688 Parrison Street', N'College Park', N'MD', N'20742', N'Single Family', 5, 2.5, 2, 1, 2, 1995, N'Excellent', 485995.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties(PropertyNumber, [Address], City, [State],
ZIPCode, PropertyType, Condition, Bedrooms, Bathrooms, YearBuilt, MarketValue, SaleStatus)
VALUES(N'81115599', N'10340 Helmes Street #1012', N'Silver Spring',
N'MD', N'20906', N'Condominium', N'Good', 1, 1, 2000, 252775.00, N'Ready For Sale');
GO
INSERT INTO Listing.Properties
VALUES(N'44759760', N'4201 Vilamar Ave', N'Hyattsville', N'MD', N'20782', N'Townhouse', 3, 2, 2, 1, 2, 1992, N'Excellent', 365880.00, N'Ready For Sale');
GO
- To execute, press F5
- Click inside the Query Editor and press Ctrl + A
- To show the listing of the properties, type the following code:
USE RealEstate2;
GO
SELECT PropertyNumber [Property #], City, [State],
PropertyType [Type], Bedrooms Beds,
Bathrooms Baths, YearBuilt [Year],
Condition, MarketValue "Market Value", SaleStatus "Status"
FROM Listing.Properties;
GO
- To execute, on the main menu, click Query -> Execute.
Notice that
there are no more NULL fields in the properties types, the conditions,
and the status:

- Click inside the Query Editor and press Ctrl + A
- To show only properties ready for sale, change the statement as
follows:
USE RealEstate2;
GO
SELECT props.PropertyNumber [Property #],
props.City, props.[State],
props.PropertyType [Type],
props.Bedrooms Beds,
props.Bathrooms Baths,
props.YearBuilt [Year],
props.Condition,
props.MarketValue "Market Value",
props.SaleStatus "Status"
FROM Listing.Properties props
WHERE props.SaleStatus = N'Ready For Sale';
GO
- To execute, press F5
Notice that you get 10 records of properties
that are listed as ready to be sold:

- To see properties that are not listed as being on sale, change the
statement as follows:
USE RealEstate2;
GO
SELECT props.PropertyNumber [Property #],
props.City, props.[State],
props.PropertyType [Type],
props.Bedrooms Beds,
props.Bathrooms Baths,
props.YearBuilt [Year],
props.Condition,
props.MarketValue "Market Value",
props.SaleStatus "Status"
FROM Listing.Properties props
WHERE NOT(props.SaleStatus = N'Ready For Sale');
GO
- To execute, press F5
Notice that, this time, you get all
properties that are not ready to be sold, including properties whose
availability status is not known:
Conclusion: On foreign keys, avoid using leaving their values empty
and avoid setting them NULL
There are many issues you need to be concerned about in
a relational database. Some issues are related to the columns of tables and
some issues have to do with records. This means that you should always think
about structures of tables when you decide to either add new columns or
delete records.
If you decide to delete a table, first check if it is
involved in a relationship. If so, is it the parent (is it providing its
records to another table?) or the child (is one of its columns receiving
values from a parent table?)? If a table is a child, you can easily delete
it using any of the
techniques we know already. If a table is a parent, you will receive an
error.
|
After creating a table or when inheriting a
table created by someone else, you may find out that it lacks a
primary key. You can add it, of course following some rules. You
have two options.
Imagine you have the following table:
CREATE TABLE Employees
(
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
GO
You can add the PRIMARY KEY
expresion after defining the new column. Here is an example:
ALTER TABLE Employees
ADD EmployeeNumber int not null PRIMARY KEY;
GO
|
 |
As an alternative, you can add a column, and then use
the CONSTRAINT formula to define the primary key. Here is
an example:
ALTER TABLE Employees
ADD EmployeeNumber int not null
CONSTRAINT PK_Employees PRIMARY KEY(EmployeeNumber);
GO
Just as you add a primary key to an already created
table, you can also add a new column that is a foreign key. Consider the
following table named Persons:
CREATE TABLE Genders
(
GenderID int not null PRIMARY KEY,
Gender nvarchar(20)
);
GO
CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL
);
GO
The formula to add a foreign key to an existing table
is:
ALTER TABLE TableName
ADD NewColumnName DataType Options
FOREIGN KEY REFERENCES ParentTableName(ColumnNameOfOtherTable);
GO
Here is an example of adding a foreign key to the above
Persons table:
ALTER TABLE Persons
ADD GenderID int NULL FOREIGN KEY REFERENCES Genders(GenderID);
GO
So far, we have used primary keys made of only one
column. Sometimes, that one column is not enough to uniquely identify a
record. An alternative is to use more than one column. A composite key is a
primary key that uses more than one column.
To visually create a composite key, while the table is
being designed, click the row header of one of the columns. Press and hold
Ctrl (or Shift, if the columns are in a range). Then click the row header of
each of the columns that will be members of the primary key (or the row
header of the column at the end of the range). After making the selections,
release Ctrl (or Shift). Then:
- Right-click the selection and click Set Primary Key

- On the Table Designer toolbar, click the Set Primary Key button

In both cases each of the columns that participate in
the primary key would display the icon on its row header:

In the same way, you can involve as many columns as you
want. One of the ways to create a composite key is to use the foreign keys
that represent the primary keys of other tables.
To create a composite primary key in SQL, in the
parentheses of the primary key, include the names of the columns separated
by commas. Here is an example:
CREATE DATABASE InformationTechnologyJournal;
GO
USE InformationTechnologyJournal;
GO
CREATE SCHEMA Publishing;
GO
CREATE SCHEMA Authorship;
GO
CREATE TABLE Authorship.Reviewers
(
ReviewerNumber nchar(6) not null,
FirstName nvarchar(24),
MiddleName nvarchar(24),
LastName nvarchar(24),
Citizenship nvarchar(40),
Constraint PK_Reviewers Primary Key(ReviewerNumber)
);
GO
CREATE TABLE Publishing.Affiliations
(
AffiliationCode nchar(5) not null,
AffiliationName nvarchar(60),
Constraint PK_Affiliations Primary Key(AffiliationCode)
);
GO
CREATE TABLE Authorship.ReviewersAffiliations
(
ReviewerNumber nchar(6) not null,
AffiliationCode nchar(5) not null,
Constraint PK_ReviewersAffiliations Primary Key(ReviewerNumber, AffiliationCode)
);
GO
A candidate key is a column that participates in a
primary key. If the primary key contains only one column, that column is a
candidate key. If the primary key is made of more than one column, each one
of the columns is a candidate key.
|
|