PostgreSQL & PHP Tutorials - Database Joins - Foreign Keys

PostgreSQL »  Introduction to Database Joins
PostgreSQL »  Starting Out »  Introduction to Database Joins

Posted By Chris Smith Posted on 02 Apr 2006, 08:34 AM
Viewing page 2 of 4
« | Back | Next | »

Getting off topic again, in database terminology this is called a "foreign key" and allows the database itself to do some integrity checks. What does that mean? Well, it means the database can check that you have a valid author for each news item.

PostgreSQL supports foreign keys fully and will stop bad data from entering your system.

We need to add an author to the database first, just like this:

INSERT INTO authors(authorid, username, firstname, lastname) VALUES (1, 'Chris', 'Chris', 'Smith');

Now that we have an author, we can add a news item:

INSERT INTO newsitem(newsid, newstitle, newscontent, authorid) VALUES (1, 'Test', 'Testing News', 1);

If we try to add a newsitem for an author that doesn't exist:

INSERT INTO newsitem(newsid, newstitle, newscontent, authorid) VALUES (2, 'Test Missing Author', 'Testing News for Missing Author', 2);

... then you should get an error (this is from postgresql 8.1.1):

ERROR: insert or update on table "newsitem" violates foreign key constraint "newsitem_authorid_fkey"
DETAIL: Key (authorid)=(2) is not present in table "authors".

This stops us from adding bad data!
Viewing page 2 of 4
« | Back | Next | »

Avg Rating: 3
Vote Count: 10


              

  New Reply


good tutorial but the inner join are very slow realizzazione siti 07 Jun 2007 Reply
`-- Then you're missing an index or something. They should be quite fast. Chris Smith 16 Jun 2007 Reply


Want to post a comment? Fill in the details below.

Your Name  : 
Your Email  : 
Your Website  : 
Spam Check! Please answer this question  : 7 + 9 =
Comment