20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Foreign Key<br />

Foreign keys are columns that refer to primary keys in another table. Primary and foreign keys create<br />

relations between data in different tables. Chapter 1 very briefly covered foreign keys, and the Film Club<br />

database was designed with a number of tables with primary and foreign keys. When you designed the<br />

Film Club database, you didn’t set up any PRIMARY KEY constraints, but they link tables nevertheless.<br />

For example, the MemberDetails table contains all the personal data about a member, their name,<br />

address, and so on. It also has a primary key column, MemberId. Other tables, such as Attendance and<br />

FavCategory, also contain data about members, but rather than repeat personal details about the member,<br />

you created a foreign key, MemberId, that links a record in one table to a record containing a member’s<br />

personal details in the MemberDetails table. Figure 4-1 illustrates this relationship.<br />

Figure 4-1<br />

Advanced Database Design<br />

Each of the lines linking the tables represents a relationship between the tables. For example, Attendance<br />

doesn’t store all the location details; it simply stores the primary key value from the Location table for<br />

that particular location. LocationId in Attendance is therefore a foreign key, and LocationId in the<br />

Location table contains the primary key to which the foreign key refers.<br />

When discussing the primary key, you learned how important it is for it not to contain NULLs and for<br />

it to contain unique values; otherwise you lose the relationship, and queries return invalid data. The<br />

PRIMARY KEY constraint helps ensure that duplicate primary key values never occur and prevents<br />

NULLs being entered. But so far there’s nothing stopping someone from entering a value in a foreign<br />

key table that doesn’t have a matching value in the primary key table. For example, in the Film Club<br />

database, the Location table’s primary key column is LocationId. Currently the Location table holds only<br />

three records, with the values in the records’ primary key column having the values 1, 2, and 3:<br />

LocationId Street City State<br />

1 Main Street Orange Town New State<br />

2 Winding Road Windy Village Golden State<br />

3 Tiny Terrace Big City Mega State<br />

135

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!