Selecting MySQL Table Storage Engines

MySQL supports many different storage engines for its tables, each with its own advantages and disadvantages. While all of MySQL’s storage engines are reasonably efficient, using the wrong storage engine can hinder your application from achieving its maximum possible performance. For example, using the ARCHIVE engine for a table that will see frequent reads and writes will produce significantly slower performance than using the MYISAM engine for the same table. To help you choose the most appropriate engine for your table, the following sections discuss each of these engines in greater detail.



The MyISAM Storage Engine
The MyISAM storage engine extends the base ISAM type with a number of additional optimizations and enhancements, and is MySQL’s default table type. MyISAM tables are optimized for compression and speed, and are immediately portable between different OSs and platforms (for example, the same MyISAM table can be used on both Windows and UNIX OSs). The MyISAM format supports large table files (up to 256TB in size) and allows indexing of BLOB and TEXT columns. Tables and table indexes can be compressed to save space, a feature that comes in handy when storing large BLOB or TEXT fields. VARCHAR fields can either be constrained to a specific length or adjusted dynamically as per the data within them, and the format supports searching for records using any key prefix, as well as using the entire key.

Because MyISAM tables are optimized for MySQL, it’s no surprise that the developers added a fair amount of intelligence to them. MyISAM tables can be either fixed-length or dynamic-length. MySQL automatically checks MyISAM tables for corruption on startup and can even repair them in case of errors. Table data and table index files can be stored in different locations, or even on different file systems. And intelligent defragmentation logic ensures a high-performance coefficient, even for tables with a large number of inserts, updates, and deletions. Large MyISAM tables can also be compressed, or “packed,” into smaller read-only tables that take up less disk space, with MySQL’s myisampack utility.



The InnoDB Storage Engine
The InnoDB storage engine has been a part of MySQL since MySQL 4.0. InnoDB is a fully ACID-compliant and efficient table format that provides full support for transactions in MySQL without compromising speed or performance. Fine-grained (row- and table-level) locks improve the fidelity of MySQL transactions, and InnoDB also supports nonlocking reads and multiversioning (features previously only available in the Oracle RDBMS). InnoDB tables can grow up to 64TB in size.

Asynchronous I/O and a sequential read-ahead buffer improve data retrieval speed, and a “buddy algorithm” and Oracle-type tablespaces result in optimized file and memory management. InnoDB also supports automatic creation of hash indexes in memory on an as-needed basis to improve performance, and it uses buffering to improve the reliability and speed of database operations. As a result, InnoDB tables match (and, sometimes, exceed) the performance of MyISAM tables. InnoDB tables are fully portable between different OSs and architectures, and, because of their transactional nature, they’re always in a consistent state (MySQL makes them even more robust by checking them for corruption and repairing them on startup). Support for foreign keys and commit, rollback, and roll-forward operations complete the picture, making this one of the most full featured table formats available in MySQL.



The Archive Storage Engine
The Archive storage engine provides a way to store large recordsets that see infrequent reads into a smaller, compressed format. The key feature of this storage engine is its ability to compress records as they are inserted and decompress them as they are retrieved using the zlib library. These tables are ideally suited for storage of historical data, typically to meet auditing or compliance norms.

Given that this storage engine is not designed for frequent reads, it lacks many of the bells and whistles of the InnoDB and MyISAM engines: Archive tables only support INSERT and SELECT operations, do not allow indexes (and, therefore, perform full table scans during reads), ignore BLOB fields in read operations, and, by virtue of their on-the-fly compression system, necessarily display lower performance. That said, Archive tables are still superior to packed MyISAM tables because they support both read and write operations and produce a smaller disk footprint.



The Federated Storage Engine
The Federated storage engine implements a “stub” table that merely contains a table definition; this table definition is mirrored on a remote MySQL server, which also holds the table data. A Federated table itself contains no data; rather, it is accompanied by connection parameters that tell MySQL where to look for the actual table records. Federated tables thus make it possible to access MySQL tables on a remote server from a local server without the need for replication or clustering.

Federated “stub” tables can point to source tables that use any of MySQL’s standard storage engines, including InnoDB and MyISAM. However, in and of themselves, they are fairly limited; they lack transactional support and indexes, cannot use MySQL’s query cache, and are less than impressive performance-wise.



The Memory Storage Engine
The Memory storage engine, as the name suggests, implements in-memory tables that use hash indexes, making them at least 30 percent faster than regular MyISAM tables. They are accessed and used in exactly the same manner as regular MyISAM or ISAM tables. However, the data stored within them is available only for the lifetime of the MySQL server and is erased if the MySQL server crashes or shuts down. Although these tables can offer a performance benefit, their temporary nature makes them unsuitable for uses more sophisticated than temporary data storage and management.



The CSV Storage Engine
The CSV storage engine provides a convenient way to merge the portability of text files with the power of SQL queries. CSV tables are essentially plain ASCII files, with commas separating each field of a record. This format is easily understood by non-SQL applications, such as Microsoft Excel, and thus allows data to be easily transferred between SQL and non-SQL environments. A fairly obvious limitation, however, is that CSV tables don’t support indexing and SELECT operations must, therefore, perform a full table scan, with the attendant impact on performance. CSV tables also don’t support the NULL data type.



The MERGE Storage Engine
A MERGE table is a virtual table created by combining multiple MyISAM tables into a single table. Such a combination of tables is only possible if the tables involved have completely identical table structures. Any difference in field types or indexes won’t permit a successful union. A MERGE table uses the indexes of its component tables and doesn’t maintain any indexes of its own, which can improve its speed in certain situations. MERGE tables permit SELECT, DELETE, and UPDATE operations, and can come in handy when you need to pull together data from different tables or to speed up performance in joins or searches between a series of tables.



The ISAM Storage Engine
ISAM tables are similar to MyISAM tables, although they lack many of the performance enhancements of the MyISAM format and, therefore, don’t offer the optimization and performance efficiency of that type. Because ISAM indexes cannot be compressed, they use fewer system resources than their MyISAM counterparts. ISAM indexes also require more disk space, however, which can be a problem in small-footprint environments.

Like MyISAM, ISAM tables can be either fixed-length or dynamic-length, though maximum key lengths are smaller with the ISAM format. The format cannot handle tables greater than 4GB, and the tables aren’t immediately portable across different platforms. In addition, the ISAM table format is more prone to fragmentation, which can reduce query speed, and has limited support for data/index compression.



The NDB Storage Engine
The NDB storage engine implements a high-availability, in-memory table type designed only for use in clustered MySQL server environments. The NDB format supports large table files (up to 384EB in size), variable-length fields, and replication. However, NDB tables don’t support foreign keys, savepoints, or statement-based replication, and limit the number of fields and indexes per table to 128.



Storage Engine Selection Checklist
To decide the most appropriate storage engine for a table, take into account the following factors:
• Frequency of reads versus writes
• Whether transactional support is needed
• Whether foreign key support is needed
• Indexing requirements
• Table size and speed at which it will grow
• OS/architecture portability
• Future extendibility requirements and adaptability to changing data requirements

It’s worth noting, also, that MySQL lets you mix and match storage engines within a database. So you could use the MyISAM engine for tables that see frequent SELECTs and use InnoDB tables for tables that see frequent INSERTs or transactions. This ability to select storage engines on a per-table basis is unique to MySQL and plays a key role in helping it achieve its blazing performance.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

Selecting MYSQL Field Data Types

Every field of a MySQL table incorporates a data type as one of its primary attributes. This data type plays an important role in enforcing the integrity of the data in a MySQL database and in making this data easier to use and manipulate.

Intelligent use of data typing can result in smaller databases and tables, efficient indexing, and quicker query execution; indifferent, ham-handed use of types can result in bloated tables, wasted storage space, inefficient indexing, and a gradual deterioration in performance. For example, using a VARCHAR type on a field that is meant for numeric or date values could result in unexpected behavior when you perform calculations on it, just as using a large TEXT field for small string values could lead to a waste of space and inefficient indexing. Wise database architects, therefore, make it a point to be fully aware of the various data types available in a system, together with the limitations and benefits of each, prior to implementing a database-driven application; the alternative can be costly in terms of both time and money.



Numeric Types
For integer values, MySQL offers you a choice of the TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT types, which differ from each other only in the size of values they can store. Use the TINYINT and SMALLINT types for small integer values, the INT type for larger integer values, and the BIGINT type for extremely large values. For floatingpoint values, use the FLOAT and DOUBLE types for single-precision and double-precision floating point values, respectively. And, finally, for decimal values, use the DECIMAL data type.

When defining an integer field, you can include a width specifier in parentheses. This width specifier controls the padding MySQL applies to the field when retrieving it from the database. For a field defined as BIGINT (20), MySQL will automatically pad the value to 20 characters before displaying it.

When defining floating-point and decimal fields, MySQL enables you to include both a width specifier and a precision specifier. For example, the declaration FLOAT (7,4) specifies that displayed values will not contain more than seven digits, with four digits after the decimal point. You can also add the ZEROFILL attribute to pad values with leading zeroes, and the UNSIGNED attribute to force a field to only accept positive values.



Character and String Types
MySQL lets you store strings up to 255 characters in length as either a CHAR or VARCHAR type. The difference between these two types is simple: CHAR fields are fixed to the length specified at the time of definition, while VARCHAR fields can grow and shrink dynamically, based on the data entered into them. This makes VARCHAR fields more suitable for fields that accept variable-length data, and CHAR fields better for fields that always contain values of the same length. Both CHAR and VARCHAR type definitions must include a width specifier in parentheses, as with numeric type definitions. Thus, the definition CHAR (10) creates a field whose length remains exactly 10 characters, regardless of what is entered into it, while the definition VARCHAR (10) creates a field whose length can range anywhere between 0 and 10 characters, depending on what is entered into it.



Text and Binary Types
MySQL enables you to store strings greater than 255 characters in length as either a TEXT or BLOB type. The difference between TEXT and BLOB types is minimal at best:
TEXT types are compared in a case-insensitive manner, while BLOB types are compared in a case-sensitive manner. For this reason, BLOBs are usually used to store binary data, while TEXT fields are used to store ASCII data. Depending on the size of the string you’re trying to store, MySQL offers you a choice of the TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT types (for ASCII text blocks) and the TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB types (for binary data).



Date and Time Types
For simple date and time values, MySQL offers the intelligently named DATE and TIME data types. The DATE type is used to store date values consisting of year, month, and day components, while the TIME type is used for time values or durations consisting of hour, minute, and second components. Both DATE and TIME types can be used for values in either numeric (YYYYMMDD and HHMMSS) or string (‘YYYY-MM-DD’ and ‘HH:MM:SS’) format.

If what you need is a combination of the two, consider using the DATETIME or TIMESTAMP types, both of which let you specify both date and time values in a single field. The difference between the two lies in how the values are stored: DATETIME fields are stored in the form ‘YYYY-MM-DD HH:MM:SS’, and TIMESTAMP fields are stored in the form YYYYMMDDHHMMSS.

Finally, for simple applications that only need to store the year, MySQL offers the special YEAR type, which accepts a four-digit year value. It’s worthwhile to use this value if your application deals mostly with the year component of a date value, because a field marked as YEAR occupies 1 byte on disk (as compared to a DATETIME or DATE field, which can occupy up to 8 bytes). MySQL YEAR fields can accept any value in the range 1901 to 2155.

When inserting records into a table containing a TIMESTAMP field, MySQL automatically fills that field with the current date and time if no other value was specified. To accomplish the same thing with other date/time fields, use the NOW() function.



Enumerations
For situations where a field value must be selected from a predefined list of values, MySQL offers the ENUM and SET data types. For both these types, a list of predefined values must be included as part of the type definition. An ENUM field definition can contain up to 65,536 elements, while a SET field definition can hold up to 64 elements. For a field marked as an ENUM field, only one of the predefined values may be selected, whereas for a field marked as a SET field, zero, one, or more than one of the pre-defined values may be selected. ENUM fields are best suited for mutually exclusive values, while SET fields are best suited for independent values. As an example, the definition ENUM (‘red’, ‘green’, ‘yellow’) forces entry of any one of the three values, while the definition SET (‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’) allows entry of none, one, or all of the five values. In addition, SET values are stored as bits, making it possible to perform bitwise comparison and sorting operations on them.



Data Type Selection Checklist
To decide the data type for a field, take into account the following factors:
• The range and type of values that the field will hold
• The types of calculations you expect to perform on those values
• The manner in which the data is to be formatted for display purposes
• The manner in which the data is to be sorted and compared against other fields
• The available subtypes for each field and their storage efficiencies

By taking all of these factors into consideration when designing your database, you reduce the chance of incompatibilities and storage inefficiencies.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MySQL also comes with a full-featured list of SHOW statements to obtain information about all aspects of the server, its databases, and its tables. Here’s a quick list:

• The SHOW DATABASES statement displays a list of databases on the server.

• The SHOW TABLES statement displays a list of tables in a database.

• The DESCRIBE statement displays the structure of a table.

• The SHOW CREATE TABLE statement retrieves the SQL statements originally used to create the table.

• The SHOW INDEX statement displays a list of table indexes.

• The SHOW ENGINES statement retrieves a list of available storage engines.

• The SHOW PROCESSLIST statement displays a list of active connections to the server, as well as what each one is doing.

• The SHOW ERRORS and SHOW WARNINGS statements display a list of errors and warnings generated by the server.

• The SHOW STATUS statement displays live server status (including information on server uptime, number of queries processed, and number of connections).

• The SHOW TABLE STATUS statement displays detailed information on the tables in a database (including information on the table type, the number of rows, the date and time of the last table update, and the lengths of indexes and rows).

• The SHOW CHARACTER SET statement displays a list of available character sets.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MYSQL - Modifying SELECT Behavior

A number of other keywords can be added to the SELECT statement to modify its behavior.

• The SQL_CACHE and SQL_NO_CACHE keywords tell MySQL whether the query results should be cached.

• The SQL_BUFFER_RESULT keyword forces MySQL to store query results in a temporary table. This result buffer eliminates the need for MySQL to lock the tables used by the query while the results are being transmitted to the client, thus ensuring they can be used by other processes in the interim.

• The SQL_BIG_RESULT and SQL_SMALL_RESULT keywords can be used to indicate the expected size of the result set to MySQL and, thereby, help it identify the most optimal way to sort and store the returned records (disk-based or inmemory temporary tables, respectively).

• The SQL_HIGH_PRIORITY keyword raises the priority of the query over competing UPDATE, INSERT, or DELETE statements, thereby resulting in (slightly) faster query execution on busy database servers.

• The SQL_CALC_FOUND_ROWS keyword tells MySQL to calculate the total number of rows matching the query, without taking into account any LIMIT that might have been set. This total number can then be retrieved via a call to the FOUND_ROWS()function.

Appropriate usage of the SQL_CACHE, SQL_BUFFER_RESULT, SQL_BIG_RESULT, SQL_SMALL_RESULT, and SQL_HIGH_PRIORITY keywords can significantly improve the speed of your transactions with the MySQL server.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MYSQL - Using Other Table Modifiers

The TYPE attribute isn’t the only option available to control the behavior of the table being created. A number of other MySQL-specific attributes are also available. Here’s a list of the more interesting ones.

• The AUTO_INCREMENT modifier specifies the starting value to use for AUTO_ INCREMENT fields in the table.

• The CHARACTER SET and COLLATE modifiers specify the table character set and collation.

• The CHECKSUM modifier controls whether table checksums should be calculated and stored.

• The COMMENT modifier saves a descriptive label for the table.

• The MAX_ROWS and MIN_ROWS modifiers specify the maximum and minimum number of rows the table is likely to have.

• The PACK_KEYS modifier controls whether table indexes are compressed. Compressing indexes reduces the table’s size on disk, but can affect performance (as indexes need to be uncompressed every time they are updated).

• The DELAY_KEY_WRITE modifier controls whether table indexes are updated only after all writes to the table are complete. This can improve performance for tables that see a high frequency of writes.

• The UNION modifier specifies a list of tables to be merged (only useful with the
MERGE storage engine).

• The DATA DIRECTORY and INDEX DIRECTORY modifiers specify custom paths for the table data and index files.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MYSQL - Selecting a Storage Engine

Following the field definitions and modifiers come one or more table modifiers, which specify table-level attributes. Of these, the most frequently used one is the ENGINE modifier, which tells MySQL which storage engine, or table type, to use. A number of such engines are available, each with different advantages.

MySQL Storage Engines
ISAM : Legacy engine
MYISAM : Revision of ISAM engine with support for dynamic-length fields
INNODB : ACID-compliant transactional engine with support for foreign keys
MEMORY : Memory-based engine with support for hash indexes
CSV : Text-based engine for CSV recordsets
ARCHIVE : Engine with compression features for large recordsets
FEDERATED : Engine for remote tables
NDB : Engine for clustered tables
MERGE : Engine for merged tables
BLACKHOLE : Bitbucket engine

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner