MyISAM vs. InnoDB

Before talking about MySQL performance tuning, it has to be clear which MySQL storage engine should be taken. I will talk about the two most popular storage engines: MyISAM and InnoDB.

I recommend at least basic knowledge of MySQL to understand most of the things explained in the following part.

At first it is important to mention that there is no storage engine which is best of all. Every storage engine has its advantages and disadvantages, but if you clarify your needs correctly you will find the one that fits the best.
In fact you do not have to use one storage engine for your whole database, but you are able to combine the advantages by using both of them for different tables. So probably the way to the best performance and usability is using MyISAM and InnoDB!

Description of the most important MySQL storage engines:

  • MyISAM
    1. Features
    2. This storage engine is used with simple and easy database models and purposes in general. For me the most important feature of MyISAM is full-text search.

    3. Advantages
    4. It is the default storage engine of MySQL, because its simplicity is a great advantage. You do not have to take care of any complex database models and can easily create simple table designs.
      Another important point is the full-text indexing, already mentioned as feature. You are able to use this for search engines in forums, websites or web-shops.

    5. Disadvantages
    6. Due to the simplicity there are many things which MyISAM lacks, even if it is an advantage. MyISAM is missing of data integrity features such as foreign keys.
      Also the missing transactions feature is bad, because queries can mess up your complete table content!
      Another negative point is that this storage engine does table locking. This will surely reduce performance with WRITE-heavy tables.

    7. Fields of use
    8. MyISAM is the best storage engine for beginners or simple purposes, but I do not recommend using it with WRITE-heavy tables, due to table locking and the lack of data integrity and transactions.
      All in all MyISAM is mostly considered to be used in relation with tables of websites, content management systems, blogs, small search engines and so on. As you can see, these examples are all READ-heavy and so it is mostly used in this field.
      Of course this a general statement which depends on the size of the software or on specific tables. There are some cases on which other storage engines have better performance results with SELECT-statements, but this is not the standard.

  • InnoDB
    1. Features
    2. This storage engine is used with more complex database models and purposes in general. There are three main features which InnoDB has: Relational database design with foreign keys, transactions and row-level locking.

    3. Advantages
    4. In my opinion the most important advantage of InnoDB is the transaction feature. With this you can ensure the correctness of your data, even if a data manipulation query gets interrupted.
      Besides it supports row-level locking within tables, which is very important for the performance of WRITE-heavy tables.
      Another advantage is the data integrity with the help of foreign keys. With this you can build relational database models, needed for complex use.
      Moreover InnoDB not only keeps indexes, but also frequently accessed data in memory, what is possible with the buffer pool. Of course this reduces I/O on disks and due to this increases perfomance a lot!

    5. Disadvantages
    6. In opposite to MyISAM this storage engine does not support full-text indexing, which prevents you from doing full-text searches.
      Due to the fact that InnoDB maintains data integrity, designing database concepts will be more time-consuming.
      Another thing is that it also needs much more system resources, especially RAM. Only with this it is possible to guarantee good performance.

    7. Fields of use
    8. To summarize InnoDB is a storage engine for advanced users with databases which contain sensitive data.
      It is recommend to use it with WRITE-heavy databases, because of the transaction feature and data integrity.
      Nowadays you can use InnoDB for READ-heavy databases too, because the times of slow performance are really gone. But this gets only important with huge applications or websites with huge count of visitors and changes.

I hope the differences and advantages of both MyISAM and InnoDB get clear after reading this article. If you have feedback, regards, corrections or questions please let me know and do not hesitate to comment!

Besides this was the first step to and the base of my MySQL performance tuning post, which will come soon.

HowTo: Instalar Percona Server

Como prometí en el último post, os voy a enseñar como instalar MySQL-Server con la solución Percona.

Hay dos maneras de instalar Percona: Via gestor de paquetes o desde el código.
Quizas algunos de vosotros pensais que no es necesario instalar Percona desde el código y ahí estais en lo cierto. Realmente no es necesario, pero tiene algunas ventajas que veremos mas adelante. Para que veais la diferencia, enseñare las dos formas.

Este HowTo esta basado en mis fines y necesidades personales, con lo cual también existirán mas maneras de tener Percona en funcionamiento.
Mis sistemas operativos favoritos son Debian y Ubuntu y actualmente uso Percona-Server v5.5.15-21.0, pero probablemente lo actualizare en unas semanas.

Recomiendo unos conocimientos mínimos de MySQL y UNIX para entender la mayoria de cosas que explicaré en la siguiente parte.

Las dos maneras de instalar Percona:

  1. Instalación via gestor de paquetes
  2. La unica cosa que teneis que hacer es conseguir la clave de firma de Percona y añadir sus correspondientes repositorios. Con esto será posible instalar el programa automaticamente por medio del gestor de paquetes.
    Necesitarás acceso superusuario/root para hacer lo siguiente.

    # Conseguir la firma
    $ gpg --keyserver hkp://keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
    $ gpg -a --export CD2EFD2A | sudo apt-key add -

    # Añadir los repositorios
    # Reemplaza $RELEASE con la version de tu sistema operativo
    $ echo -e "\n# Percona Server\ndeb http://repo.percona.com/apt $RELEASE main\ndeb-src http://repo.percona.com/apt $RELEASE main" >> /etc/apt/sources.list

    Despues de esto, ¡ya puedes instalar Percona!

    $ apt-get install percona-server-server-5.5

  3. Instalación via código
  4. Esta versión es mas compleja, pero tiene la posibilidad de instalar la aplicacion con fines configurables.
    Necesitarás acceso superusuario/root para hacer lo siguiente.

    # Añadir usuario mysql
    $ useradd -s /bin/false -b /opt/mysql -d /opt/mysql -m mysql

    # Instalar cliente MySQL
    $ apt-get install mysql-client-5.1

    Prefiero instalar antes el cliente, porque crea la configuración (my.cnf) en /etc/mysql/ el cual no se crea automaticamente desde este metodo. Percona ofrece diferentes versiones del archivo my.cnf para diferentes fines pero los postearé en otro tutorial.

    Empecemos con la instalación básica.

    # Instalar los paquetes requeridos
    $ apt-get install automake libtool g++ ncurses-dev bison

    # Bajar y extraer el codigo de Percona
    $ wget http://www.percona.com/redir/downloads/Percona-Server-5.5/Percona-Server-5.5.15-21.0/source/Percona-Server-5.5.15-rel21.0.tar.gz
    $ tar xvfz Percona-Server-5.5.15-rel21.0.tar.gz
    $ cd Percona-Server-5.5.15-rel21.0

    # Preparar la compilación
    $ sh BUILD/autorun.sh
    $ ./configure --without-plugin-innobase --with-plugin-innodb_plugin --prefix=/opt/mysql

    # Crear directorio para los logs
    $ mkdir /var/log/mysql
    $ chown mysql:mysql /var/log/mysql

    Prefiero instalarlo en /opt/mysql, pero puedes especificar donde instalarlo con la opción –prefix. Las otras dos opciones desencadenan el uso de XtraDB en vez de hacerlo en el motor de almacenamiento InnoDB. Escribí algo sobre esto en mi ultimo articulo de Percona Server. Para incrementar el rendimiento de InnoDB ¡es muy importante usar esto!

    # Compilando el código
    $ make -j
    $ make install

    # Instalar la base de datos básica
    $ cd /opt/mysql
    $ ./scripts/mysql_install_db --user=mysql --basedir=/opt/mysql --datadir=/opt/mysql/data --verbose --log-error=/tmp/mysql.error.log --defaults-file=/etc/mysql/my.cnf

    # Poner privilegios
    $ chown -R mysql:mysql /opt/mysql

    Si sigues estos pasos correctamente debes instalar la base de datos, casi lista para funcionar. Crearemos algunos archivos que permitiran iniciar y parar el proceso de Percona facilmente.

    # Uso de archivos de soporte de Percona
    $ echo "/opt/mysql/support-files/mysql.server start" > /etc/init.d/mysql_start
    $ echo "/opt/mysql/support-files/mysql.server stop" > /etc/init.d/mysql_stop
    $ chmod 755 /etc/init.d/mysql_*

    # Hacer acceso directo a ellos en los directorios rc
    $ ln -s ../init.d/mysql_start /etc/rc2.d/S19mysql
    $ ln -s ../init.d/mysql_stop /etc/rc0.d/K21mysql
    $ ln -s ../init.d/mysql_stop /etc/rc6.d/K21mysql

    Lo último que tienes que hacer antes de iniciarlo es hacer unos pequeños ajustes a la configuración. Necesita algunos cambios para que funcione correctamente. La ventaja del my.cnf es que tiene incluido el directorio para los archivos de configuración personalizada. Asi que lo usaremos, ya que estos archivos sobreescribirán las opciones del my.cnf.

    # Añadir directorios
    $ echo -e "[mysqld]\n\nbasedir = /opt/mysql\ndatadir = /opt/mysql/data\n" > /etc/mysql/conf.d/mysql_additon.cnf

    # Configuracion XtraDB requerida
    $ echo -e "innodb_file_per_table = 1\ninnodb_file_format = barracuda" >> /etc/mysql/conf.d/mysql_additon.cnf

    Solo he puesto el base y data-dir de MySQL, porque prefiero estas opciones. Depende de como lo vayas a manejar. ¡Las opciones de la configuración XtraDB que hice son muy importantes! La primera (innodb_file_per_table) esta puesta a 1 para reducir el acceso a los archivos y la reducción de I/O. Esto viene siendo lo mas importante si tienes discos duros lentos, pero lo recomiendo por mi de todas formas. La segunda (innodb_file_format) esta puesta en barracuda, la cual es la unica soportada por el formato de tablas para XtraDB.

    Ahora debes poder iniciar y parar tu servidor MySQL con los siguientes comandos:

    # Inciar
    $ /etc/init.d/mysql_start
    # Parar
    $ /etc/init.d/mysql_stop

Espero que este tutorial te haya ayudado a instalar y configurar tu servidor Percona. Si tienes alguna sugerencia, correcciones o preguntas, hazmelo saber y no hagas comentarios fuera de lugar.

Ten en cuenta que hay que seguir las guias de rendimiento de MySQL para ajustarlo y hacer copia de seguridad para InnoDB y MyISAM.