views:

110

answers:

5

What are primary keys used aside from identifying a unique column in a table? Couldn't this be done by simply using an autoincrement constraint on a column? I understand that PK and FK are used to relate different tables, but can't this be done by just using join?

Basically what is the database doing to improve performance when joining using primary keys?

+4  A: 

Mostly for referential integrity with foreign keys,, When you have a PK it will also create an index behind the scenes and this way you don't need table scans when looking up values

SQLMenace
Surely you'll still need table scans if you're not using the PK in the where clause.
ScaryAardvark
Yes..you are right...and so I am :-) .....if you have a PK (which by default creates a clustered index) you will never get a table scan (since a clustered Index holds all the data of table itself)...you will however get index scans if your WHERE clause is not covered
SQLMenace
+1  A: 

Some PKs are simply an auto-incremented column. Also, you typically join USING the PK and FK. There has to be some relationship to do a join. Additionally, most DBMS automatically index PKs by default, which improves join performance as well as querying for a particular record based on ID.

Michael Krauklis
+2  A: 

RDBMS providers are usually optimized to work with tables that have primary keys. Most store statistics which helps optimize query plans. These statistics are very important to performance especially on larger tables and they are not going to work the same without primary keys, and you end up getting unpredictable query response times.

Most database best practices books suggest creating all tables with a primary key with no exceptions, it would be wise to follow this practice. Not many things say junior software dev more than one who builds a database without referential integrity!

James
+1  A: 

You can join without a primary key within a query, however, you must have a primary key defined to enforce data integrity constraints, at least with SQL Server. (Foreign Keys, etc..)

Also, here is an interesting read for you on Primary Keys.

Mitchel Sellers
+1  A: 

In Microsoft Access, if you have a linked table to, say, SQL Server, the source table must have a primary key in order for the linked table to be writeable. At least, that was the case with Access 2000 and SQL Server 6.5. It may be different with later versions.

GenericMeatUnit

related questions