MySQL: Does the order of the fields in a table make a difference in performance

performance

Specifically I am wondering if I should place all my fixed length fields like int, timestamp, char at the beginning of the CREATE TABLE and place all the variable length like varchar at the end.

Also, I am wondering if TEXT fields are treated differently.

Best Answer

Depending on the RDBMS storage engine, it may reorder the fields internally for storage and display anyway. If we look at this question from the angle of a C program, a table in a database is like a C struct. E.g. A table in a c program might look like:

typedef struct _Table {
  char type,      /* 1 byte   */
  int id,         /* 4 bytes  */
  char *name;     /* 4 bytes  */
  char city[25];  /* 25 bytes */ 
} Table;          /* 34 bytes total */

You can see that in your program, you will expect that your first struct element is at the first pointer location, then one byte over will be your second element location, etc... These are called offsets.

Your RDBMS will likely store the file data structure in a c style struct so that it can understand what the offsets (memory locations) of data will be for each row. Then indexes will be applied to make searching amongst like groups of rows. An index location is simply a pointer to the first byte of each matching row (or struct).

As a software engineer type, you'd probably want to pack the struct so that the smallest data types are at the beginning of the struct so that as your pointer arithmetic scans over them you'll find conclusions faster, however this is a design decision.

Bottom line, best practice says to design your model smallest to largest, but it's probably being re-organized by the storage engine requirements anyway.