Why do we need to use Foreign Keys?

foreign-keys, mysql, primary-key, sql

Solution

When you use foreign keys you get:

- Data integrity

- faster queries.

users: user id:

- 1

- 2

- 3

Comments: user:

- 1

- 2

- 4 XXX invalid as 4 isn't in the users table.

Read Wikipedia please for more details about Data integrity

Problem

Possible Duplicate: Should I use foreign keys? Ok, let's assume we have two tables, `users` and `comments`. In comments we have a column `comment_made_by_user_id` and it means which user typed that particular comment. Why do we need to specify it as a foreign key? If we don't do that, it will still work. We specify primary keys, because it makes queries faster as far as I know (we need to search only for one row while when we don't have a primary key/index, we have to go through all rows). Is it just a good coding practise?

Original source

Related problems