4

Does the primary key have to be the first field in a database table?

Will the queries be slower if I put the id after the name?

CREATE TABLE users
(
    name TEXT NOT NULL,
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    site INTEGER NOT NULL,
    ... 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1
  • Just as an attempt to adjust your thinking a bit: a primary key is a logical constraint that has nothing to do with performance. However, most RDBMS's implement a unique index to enforce the Primary Key constraint; this index could impact performance, but you may use other indexes to influence queries. Primary keys need not be auto-incrementing integers (although most databases use them as such). Dec 4, 2011 at 14:56

2 Answers 2

4

Using/placing primary key as first field in database is general convention, but it does not matter if you define second field (id) as primary key, and it wont make queries slower

2

I think that will complete the previous answers :

"There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. An AUTO_INCREMENT column works properly only if it contains only positive values. Inserting a negative number is regarded as inserting a very large positive number. This is done to avoid precision problems when numbers “wrap” over from positive to negative and also to ensure that you do not accidentally get an AUTO_INCREMENT column that contains 0."

So there is no limitation regarding the position of the primary key inside a table.

Hope this help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.