Change a Tables Default Sort Order in MySQL
When I say "default" what I mean is the order that rows will be returned if you provide no other explicit ordering via your SQL. Usually this order is just by when a row was inserted into the table. If INSERT
's and DELETE
's have jumbled a nicely ordered table you can clean things up like this:
ALTER TABLE tablename ORDER BY columnname;
Next time you SELECT
rows from this table they'll already be in the order you specified above. The ORDER
clause works like any other, you can order by multible columns in order of precedence, ascending and descending, etc.
ALTER TABLE tablename ORDER BY column1 ASC, column2 DESC;
Like I said at the beginning, the sort will begin to drift after additional INSERT
's and DELETE
's. Rows that will sorted will remain in their order, but new rows will be placed at the end.