I have a database that has a table that has rows with a value "ID" that changes a lot.
It may be like:
Of course the easiest answer is to use
ORDER BY when you query your table, and then you can control the order of rows in the query result set. But I assume you mean you want the "natural" order of rows to be in numeric order when you don't use
If your table uses the InnoDB storage engine, the default order when you query without using
ORDER BY is always the order of the primary key. That's because InnoDB stores tables as a clustered index by primary key. So if ID is your primary key, and you convert your table to InnoDB, then you can rely on its natural order.
mysql> ALTER TABLE MyTable ENGINE=InnoDB;
If your table is stored as MyISAM, the natural order is the order rows are physical stored in the data file, which has nothing to do with the order of the values or even the order in which you created the rows.
For these tables, you can dump your table in primary key order with:
$ mysqldump --order-by-primary databasename tablename > table.sql
Then restore the table. The data will reload in primary key order. Then subsequently the default order when you query without using
ORDER BY will be by ID. But this doesn't prevent the rows from getting out of order again as the values change.
Re your comments:
The best option would be to use
WHERE. That's efficient because it can use the clustered index to find the correct row very quickly.
SELECT * FROM MyTable WHERE ID = 6;
The alternative, which is less efficient but still better than returning all the rows, is to pick some row or rows by their position in the stream, instead of by their value.
SELECT * FROM MyTable LIMIT 1 OFFSET 5;
The first number is how many rows you want, the second number is how many rows to skip first.
Normally you'd want to use
LIMIT only after specifying an order, otherwise you could get the rows in some meaningless order, and the fifth row wouldn't be any more desirable than the first row.
SELECT * FROM MyTable ORDER BY created_at LIMIT 1 OFFSET 5;