My website displays posts by DATE even though the SQL table is ordered by ID. Since the order of the ID is not always the same as the order of the DATE, I run the query with ORDER BY 'DATE'.
SQL Table Example:
----------------------------
| ID | DATE |
----------------------------
| 1 | 2011-10-20 00:00:00 |
| 2 | 2012-10-20 00:00:00 |
| 3 | 2010-10-20 00:00:00 |
| 4 | 2011-09-20 00:00:00 |
----------------------------
To query I use: SELECT * FROM `table` ORDER BY 'DATE';
My questions:
-
Would it benefit the query performance if the cluster index or primary key of the table was the DATE column?
-
Is it possible to have the ID column auto-increment when it is not the primary key?
What I want to do is make the query as fast as possible (which I think would be possible by making the DATE the cluster index or primary key) but also allow each post to have a unique auto-increment ID. I tried to make DATE the primary key but I got an error saying “there can be only one auto column and it must be defined as a key”.
I would not define the date as a primary key, but rather add an index on the field. Unique, if needed. I believe it is possible to have an autoincrement on a non primary key field, but trying it yourself will give you the best answer!
<– EDIT –>
To answer your comment question, I can’t say its a BAD idea, but dates are always picky. For once, you have to decide if you use UTC or local date, preview how daylight saving time affects your program, foresee if the need of a date update would be possible at some time of the application life, and things like that. I rather forget about that and just go with the unique autogenerated key.
If you do go for the date as PK, you can use timestamp and avoid the second sequence column.
I found more info about dates as primary keys at techtarget.com and made2mentor.com.