In SQL, what are the differences between primary, foreign, and unique keys?


Warning: include(../adsense.php) [function.include]: failed to open stream: No such file or directory in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 117

Warning: include(../adsense.php) [function.include]: failed to open stream: No such file or directory in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 117

Warning: include() [function.include]: Failed opening '../adsense.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 117

Both primary and unique keys can span multiple columns within a table. Two differences exist:

1. A table may have more than one unique key. This depends on the design of the table. But, a table can have only one primary key.

2. The values in the unique key columns may or may not be NULL. The values in primary key columns, however, can not be NULL.

While unique and primary keys both enforce uniqueness on the columns of one table, foreign keys define a relationship between 2 tables. A foreign key identifies a column or group of columns in one (referencing) table that refers to a column or group of columns in another (referenced) table.

Both unique and primary keys can be referenced by foreign keys.

Join our mailing list to receive more questions from actual programmer interviews!


Warning: include(../adsense2.php) [function.include]: failed to open stream: No such file or directory in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 177

Warning: include(../adsense2.php) [function.include]: failed to open stream: No such file or directory in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 177

Warning: include() [function.include]: Failed opening '../adsense2.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/varoon10/public_html/programmerinterview.com/sql/primary-foreign-keys-differences.php on line 177