
MySQL Cheat Sheet
Two MySQL™ table types are MyISAM and INNODB. MyISAM type tables are most often used for website development. INNODB type tables are more complex because they support transactions and cascading used by advanced web applications which are typically not utilized by the average web developer. MySQL™ web development often involves using PHP scripting language. MySQL™ Naming ConventionsWhile the hyphen (-) may be a valid character in the names of databases, tables, and columns, don't use a hyphen when naming anything. Use of hyphens in the name of a database, table, or column may cause problems. If a hyphenated resource name appears in a double-quoted ("...") string of PHP code, the hyphen will be interpreted as a minus sign and crash the script. Varied system configurations may cause portability issues if upper case letters are used when naming MySQL™ resources. Use lower case letters to ensure portability to other system configurations. Lower case letters a-z, numeric digits 0-9, and the underscore character are preferred by most users. If using upper case letters, your code might not be portable to a different server, most notably when migrating from Linux to Windows. Avoid using Reserved Words when naming columns, tables, and databases. Consider using the underscore character in your column names, e.g. first_name and not FirstName or firstname. Subsequently in PHP scripts the underscore can be easily replaced with a space when displaying the column name in reports. Prefix the names of your tables with your initials and the underscore character, or another arbitrary prefix. Later on, if you install a different web application in the same database, the possibility of table name conflict is significantly reduced. Upgrade MySQL™ Version on WindowsI have more than 100 MySQL™ databases and thousands of tables installed on several Windows PC's. Each client's website is mirrored locally on my Windows PC so that testing can be easily accomplished without interfering with the production server. My experience is that on a Windows PC, there isn't an upgrade option for MySQL™ . You should always export your databases prior to installing a new version of MySQL™ preferably using a MySQL™ utility such as MySQL™ Workbench. And then import the data files after the new MySQL™ version is installed on Windows. When moving from 32-bit Windows XP to 64-bit Windows 7, if the so-called old password format is in effect, the best thing to do is export your data, verify the export files are readable, backup them up, uninstall MySQL™ , rename the old installation directory, reboot, install the current 64-bit version of MySQL and import data which was exported earlier. Do not import tables `mysql` and `information_schema`. Manually re-enter all the user names, passwords, and privileges using MySQL™ Administrator or MySQL™ Workbench. See OK packet 6 bytes shorter than expected. Storing NULL instead of an empty stringPerhaps I'm missing something, but the only time I've found it practical to actually store a NULL value in MySQL™ is when the entry of a date field is optional. Otherwise, it makes no sense to me to store NULL when storing an empty string (nothing) conserves resources and avoids adding complexity to queries related to that field. Assign the field attribute NOT NULL unless you have a specific reason for inserting NULL's. UTF8 Collation and Connection with MySQL™Specifying a database collation as utf8_generic_ci, using appropriate META tags, and issuing queries for SET NAMES UTF8 and SET COLLATION_CONNECTION=UTF8_GENERAL_CI after the database connection seems to work well for web pages which may contain accented characters. $cfg['hn'] = 'localhost';
If using UTF-8, LATIN2 (ISO-8859-2), or CP1250 (WINDOWS-1250) character sets, after connecting to MySQL, and after selecting database, but before querying a table, you may need to execute the appropriate query below. // UTF8 connection // ISO-8859-2 connection // WINDOWS-1250 connection Forcing UTF-8 Connections in MySQL 5.x or higher can potentially be accomplished using a statement in the my.cnf file calling init_connect. With UTF8, you also need to be sure to apply the appropriate HTML META tags to your document. <meta http-equiv="charset" content="UTF-8"> Other HeadachesYou might upgrade your MySQL™ version to 4.1 or 5.x on your Windows PC, and when you try to connect to the database you are greeted with Client does not support authentication protocol requested by server; consider upgrading MySQL™ client. Be sure to clear your browser cache after following the instructions in the above link. Sometimes browsers won't let go of old content. You may want to close your browser after dumping the cache, to avoid time wasting browser bugs. It may be that all you need to do is add "old-passwords" to your my.ini file and restart MySQL™. [mysqld] See also this page. If you have MySQL™ 3.x or MySQL™ 4.0.x on your PC's development environment and you want to upgrade, be aware there is no upgrade available. You have to back up all your databases, uninstall the lesser version, install the new version, and then import the data that you backed up. You should check out your backup files before you uninstall the old version of MySQL™. MySQL™ Schema TipsIf you're looking for MySQL™ data to experiment with, download the Sakila schema. Conserve MySQL™ resources and optimize your table schema. Using INT(10) to store a number which will never exceed 32,767 is wasteful and should be avoided to conserve storage space and maximize efficiency. If a numeric field is going to contain values between 0 and 32,767 then define the column as UNSIGNED SMALLINT(5). Apply an INDEX to any column which often appears in a WHERE clause or in an ORDER BY clause. Prefix your Index Name / Keyname with a few characters such as 'idx_' to avoid potential problems with ambiguity. The name of the index should be different from the name of the column. When created using phpMyAdmin, the Index Name often defaults to that of the column name, however the Index Name / Keyname should be altered so that it is different from that of the column. IMHO, always make an "id" field as the first column (MySQL™ column 0) and make it an auto_increment primary key field. Vary the name of the primary key column so that you don't end up with a field named "id" in every table. Using "id" as the name of the key column in every table may cause confusion when working with SQL queries involving more than one table. Assign the field attribute NOT NULL unless you have a specific reason for inserting NULL's. MySQL™ Date and Time Column Storage Requirements>
See also: MySQL™ Date and Time Types TIMESTAMP usage conserves storage space (as compared with using both a DATE and TIME field). Note that the formatting of TIMESTAMP columns is handled differently across different versions of MySQL™, with respect to hyphens and colons used to separate elements. MySQL™ TIMESTAMP observationsSeveral years ago, I had MySQL™ v4.0 on my PC and my web host upgraded to 4.1x, certain queries are returning unexpected results when run on the web. The TIMESTAMP column is handled differently between version 4.0 and 4.1 or 5.0, leaving me to conclude that as regards portability, storing PHP's TIME() value in a VARCHAR(10) column makes more sense than using TIMESTAMP columns. Hyphens are used to separate elements of the TIMESTAMP beginning with 4.1. Whole Numbers (Integers)The smallest suitable column type should be employed whenever possible. Do not use a TINYINT column as the auto_increment primary key field unless you're sure the table will contain fewer than 128 records. Do not use an INT column as the auto_increment primary key field unless the table is actually going to hold a billion records. Using SMALLINT(5) whenever possible will help reduce the amount of storage space required. Refer to the chart on this page that reflects the impact of defining a column as UNSIGNED. I am guessing that most auto_increment primary key fields should be SMALLINT() UNSIGNED NOT NULL DEFAULT '0' ... or possibly MEDIUMINT() UNSIGNED NOT NULL DEFAULT '0'.
DecimalsFLOAT(8,2) is good for currency, etc., and requires half the storage capacity of DECIMAL or DOUBLE.
MySQL Text Column Types and Storage Requirements
See also MySQL String Types An ENUM is a string object whose value normally is chosen from a list of allowed values that are enumerated explicitly in the column specification at table creation time. ENUM('X','Y','Z') up to 65,535 values entered can be entered from the list X,Y,Z. A blank value appears to be prepended to the list in phpMyAdmin but does not appear in phpMyEdit files. Usage might include a list of 2-digit U.S. states, where a single value is chosen. SET is a string object that can have zero or more values, each of which must be chosen from a list of allowed values specified when the table is created. SET column values that consist of multiple set members are specified with members separated by commas (`,'). A consequence of this is that SET member values cannot themselves contain commas. SET('','X','Y','Z') up ~ 64 members can be entered from the list X,Y,Z. Blank value must manually be set at the top of the list. Multiple values can (optionally) be selected from SET's. Usage of SET and ENUM fields is tricky when writing PHP scripts, but once mastered, works really well. INFORMATION_SCHEMA and MySQL™ Improved ExtensionMySQL™ version 5+ offers an INFORMATION_SCHEMA database containing extensive information on the configured databases, tables, and fields. However, if you have a lot of databases configured, the response time is horrible unless using the *Improved* connection methods, making it essentially unusable under certain configurations. See the Bug Report. MySQL™ Improved ExtensionIt appears INFORMATION_SCHEMA works well only with the MySQL™ Improved Extension. Converting PHP code from the original MySQL™ functions to the Improved functions requires some study and syntax alteration. There are a few functions which were discontinued (there is no mysqli_field_len() function). Two projects which I upgraded to the Improved connection appear to have noticeably faster performance. Good old SELECT COUNT(*) fails to work as planned. Under mysqli_num_rows() the return value is always 1 even though there may be thousands of records in the table. A workaround to resolve SELECT COUNT(*) appears below. It has something to do with buffered vs. un-buffered queries, anyway: $res = mysqli_query ($link, 'SELECT COUNT(*) FROM `my_table`',
MYSQLI_STORE_RESULT);
Database connections are also made in a different fashion when migrating to MySQL™ Improved Extension. After converting one project to the Improved extensions, I felt the effort was worth it since minor performance gains were achieved. Some additional diagnostics are available, e.g. mysqli_warning_count() which uncovered minor issues which would otherwise have gone un-noticed. Utilities and Personal ObservationsFor those of you who intend to create a development environment on a Windows PC, WAMP5 will quickly install Apache 2, MySQL™ 5, and PHP 5 (users can optionally select a document root that matches your web server). Fookes Software offers several terrific Windows software applications including NoteTab (a programmable text editor). Popular utilities for working with MySQL™ include MySQL™ Workbench, phpMyAdmin, and phpMyEdit Adminer is a great MySQL™ interface which offers much the same functionality as phpMyAdmin using only 1 script. dBug.php is a great debugging script for PHP. Related information at sitepoint.com: Top 10 MySQL Mistakes Made By PHP Developers. WAMP ConfigurationsIn my humble opininon, Apache 2.2 cannot be installed on 64-bit Windows 7 *and* play well with PHP and MySQL™ . My recommendation if creating a WAMP environment on 64-bit Windows is to use Apache 2.0 and not version 2.2. Either version is installable and works perfectly well independently ... but 2.2 won't play well with PHP and MySQL™ and you'll waste 2-3 days trying to figure out why things aren't working as they should. Some of PHP's DLL files for Windows will not work as intended with Apache 2.2. Installing MySQL™ , PHP, and Apache individually on Windows will expand your knowledge of how these applications work together. You might want to start here. MySQL™ MEMORY Table or HEAP TableConsider using a modified version of this to sort populate a MEMORY table with a multi-dimensional array. It might be easier to populate and query a MEMORY table than it is to use PHP to sort certain multi-dimensional arrays. The following was used to process a client list downloaded from a cPanel WHM interface.
<?php
PHP Form Generator for MySQL™ MyISAM type tables |