Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of columns in a query matter?

When selecting columns from a MySQL table, is performance affected by the order that you select the columns as compared to their order in the table (not considering indexes that may cover the columns)?

For example, you have a table with rows uid, name, bday, and you have the following query.

SELECT uid, name, bday FROM table

Does MySQL see the following query any differently and thus cause any sort of performance hit?

SELECT uid, bday, name FROM table
like image 941
James Simpson Avatar asked Jan 03 '11 05:01

James Simpson


People also ask

Does order of column matter in SQL?

Column order does not matter while creating a table. We can arrange the columns while retrieving the data from the database. Primary key can be set to any column or combination of columns.

Does order matter in query?

Answer. No, the order of query parameters should not matter.

Does order of columns in group by matter SQL?

No, the order doesn't matter for the GROUP BY clause. MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.

Does database column order matter?

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.


2 Answers

The order doesn't matter, actually, so you are free to order them however you'd like.

edit: I guess a bit more background is helpful: As far as I know, the process of optimizing any query happens prior to determining exactly what subset of the row data is being pulled. So the query optimizer breaks it down into first what table to look at, joins to perform, indexes to use, aggregates to apply, etc., and then retrieves that dataset. The column ordering happens between the data pull and the formation of the result set, so the data actually "arrives" as ordered by the database, and is then reordered as it is returned to your application.

like image 66
futureal Avatar answered Oct 02 '22 23:10

futureal


In practice, I suspect it might.

With a decent query optimiser: it shouldn't.

You can only tell for your cases by measuring. And the measurements will likely change as the distribution of data changes in the database.

with regards

Wazzy

like image 35
Wazy Avatar answered Oct 03 '22 01:10

Wazy