Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does column order matter in your MySQL tables?

Tags:

database

mysql

While learning mysql, I read that you can perform the following statement when adding a column to a mysql table:

ALTER TABLE contacts ADD email VARCHAR(60) AFTER name; 

or

ALTER TABLE contacts ADD email VARCHAR(60) FIRST; 

When would you want to do this? Can column order be utilized for query optimization purposes? Should longblobs be the last column to optimize space consumption? Or do these commands exist for some other reason?

like image 333
Baa Avatar asked Jan 21 '10 18:01

Baa


People also ask

Does order of columns matter in MySQL?

Yes, column order does matter.

Does column order matter in table?

OK, for years I've been saying that SQL Server doesn't care about the order in which you define the columns of your table because internally SQL Server will re-arrange your columns to store all of the fixed width columns first and the variable columns last.

Does the order of columns matter in a relation?

In a relation, the order of the columns does not matter.

Does the order of table matter?

Generally, no, the order of the tables in the JOIN will not affect the overall results of the query. As long as you specify what columns to select, the results should appear essentially the same, just that the rows will be ordered according to the appearance in the first table.


2 Answers

The question has nothing to do with the relational model or SQL. It is a performance question.

In some databases, it is more efficient to order the columns in a specific manner because of the way the disk access is performed. Whether there is significant advantage is platform specific, as well. It is a low-level i/o issue related to the way the underlying storage is designed and the way it is accessed by the engine. Proprietary engine providers generally provide this information via their education and training departments.

I think you would have to talk to someone who knows the nitty gritty details of the storage model and i/o methods for MySQL on your specific platform or someone who has bench-marked this on your platform in order to get an answer.

It's entirely possible they lay it down on disk in an optimized manner and hide that column ordering from you.

like image 60
Kaycee Avatar answered Sep 21 '22 08:09

Kaycee


This will however impact the order of the result in select * from mytable.

This is why you should always name the column in the select statement, e.g. select col1, col2 from mytable. But if you know that the app is using *, then you must take care when you add a column.

Otherwise, order the column so that it's the most logical to understand. If it affects the perf, then it means you are already on the dark side of database performance tuning and you have probably a problem somewhere else.

like image 33
ewernli Avatar answered Sep 20 '22 08:09

ewernli