All topics

MySQL interview questions

39 questions, 31 with answers. 555 open jobs in India ask for MySQL.

  1. Should I use the datetime or timestamp data type in MySQL?

    Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field.

    If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native DATETIME format. You can do calculations within MySQL that way ("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)") and it is simple to change the format of the value to a UNIX timestamp ("SELECT UNIX_TIMESTAMP(my_datetime)") when you query the record if you want to operate on it with PHP.

    Also, as of MySQL 8.0.19 the DATETIME supports time zone offsets, so there's even less reason to use TIMESTAMP now.

    From Stack Overflow: asked by Gad, answered by blivet (CC BY-SA 4.0)

  2. Which MySQL data type to use for storing boolean values?

    For MySQL 5.0.3 and higher, you can use BIT. The manual says:

    As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.

    Otherwise, according to the MySQL manual you can use BOOL or BOOLEAN, which are at the moment aliases of tinyint(1):

    Bool, Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.

    MySQL also states that:

    We intend to implement full boolean type handling, in accordance with standard SQL, in a future MySQL release.

    References: http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html

    From Stack Overflow: asked by Beat, answered by markus (CC BY-SA 4.0)

  3. What's the difference between utf8_general_ci and utf8_unicode_ci?

    For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_unicode_520_ci.

    All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

    _unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _unicode_520_ci for equivalent rules based on Unicode 5.2, or the MySQL 8.x specific _0900_ai_ci for equivalent rules based on Unicode 9.0 (and with no equivalent _general_ci variant). The are also sets of rules available for specific languages. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is still relevant to anyone considering using one of them.

    Older versions of MySQL used a flawed UTF-8 implementation. For this reason you need to use utf8mb4 instead of utf8 for the character encoding part to ensure you are getting the fixed version. The flawed version still remains available for backward compatibility reasons.

    Key differences

    • utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

    • utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

      On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.

    Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

    utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

    As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci sorting in MySQL, but there are still a few differences:

    • For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

    • Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci handles these properly.

    In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci sorting. The suitability of utf8mb4_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

    What should you use?

    There is almost certainly no reason to use utf8mb4_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

    In the past, some people recommended to use utf8mb4_general_ci except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

    Read the rest at the sourceFrom Stack Overflow: asked by KahWee Teng, answered by thomasrutter (CC BY-SA 4.0)

  4. "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

    I would recommend using INSERT...ON DUPLICATE KEY UPDATE.

    If you use INSERT IGNORE, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead. These cases include:

    • Inserting a duplicate key in columns with PRIMARY KEY or UNIQUE constraints.
    • Inserting a NULL into a column with a NOT NULL constraint.
    • Inserting a row to a partitioned table, but the values you insert don't map to a partition.

    If you use REPLACE, MySQL actually does a DELETE followed by an INSERT internally, which has some unexpected side effects:

    • A new auto-increment ID is allocated.
    • Dependent rows with foreign keys may be deleted (if you use cascading foreign keys) or else prevent the REPLACE.
    • Triggers that fire on DELETE are executed unnecessarily.
    • Side effects are propagated to replicas too.

    correction: both REPLACE and INSERT...ON DUPLICATE KEY UPDATE are non-standard, proprietary inventions specific to MySQL. ANSI SQL 2003 defines a MERGE statement that can solve the same need (and more). MySQL does not support the MERGE statement, even though this feature has been requested since 2005.

    A user tried to edit this post (the edit was rejected by moderators). The edit tried to add a claim that INSERT...ON DUPLICATE KEY UPDATE causes a new auto-increment id to be allocated. It's true that the new id is generated, but it is not used in the changed row.

    See demonstration below, tested with Percona Server 5.5.28. The configuration variable innodb_autoinc_lock_mode=1 (the default):

    mysql> create table foo (id serial primary key, u int, unique key (u));
    mysql> insert into foo (u) values (10);
    mysql> select * from foo;
    +----+------+
    | id | u    |
    +----+------+
    |  1 |   10 |
    +----+------+
    mysql> show create table foo\G
    CREATE TABLE `foo` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `u` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `u` (`u`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
    mysql> insert into foo (u) values (10) on duplicate key update u = 20;
    mysql> select * from foo;
    +----+------+
    | id | u    |
    +----+------+
    |  1 |   20 |
    +----+------+
    mysql> show create table foo\G
    CREATE TABLE `foo` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `u` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `u` (`u`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
    

    The above demonstrates that the IODKU statement detects the duplicate, and invokes the update to change the value of u. Note the AUTO_INCREMENT=3 indicates an id was generated, but not used in the row.

    Whereas REPLACE does delete the original row and inserts a new row, generating and storing a new auto-increment id:

    mysql> select * from foo;
    +----+------+
    | id | u    |
    +----+------+
    |  1 |   20 |
    +----+------+
    mysql> replace into foo (u) values (20);
    mysql> select * from foo;
    +----+------+
    | id | u    |
    +----+------+
    |  3 |   20 |
    +----+------+
    

    From Stack Overflow: asked by Thomas G Henry LLC, answered by Bill Karwin (CC BY-SA 4.0)

  5. MySQL: Large VARCHAR vs. TEXT?
    • TEXT and BLOB may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.

    • VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.

    From Stack Overflow: asked by Tom, answered by MindStalker (CC BY-SA 4.0)

  6. MyISAM versus InnoDB

    I have briefly discussed this question in a table so you can conclude whether to go with InnoDB or MyISAM.

    Here is a small overview of which db storage engine you should use in which situation:

                                                     MyISAM   InnoDB
    ----------------------------------------------------------------
    Required full-text search                        Yes      5.6.4
    ----------------------------------------------------------------
    Require transactions                                      Yes
    ----------------------------------------------------------------
    Frequent select queries                          Yes      
    ----------------------------------------------------------------
    Frequent insert, update, delete                           Yes
    ----------------------------------------------------------------
    Row locking (multi processing on single table)            Yes
    ----------------------------------------------------------------
    Relational base design                                    Yes
    

    Summary

    • In almost all circumstances, InnoDB is the best way to go
    • But, frequent reading, almost no writing, use MyISAM
    • Full-text search in MySQL <= 5.5, use MyISAM

    From Stack Overflow: asked by user2013, answered by developer99 (CC BY-SA 4.0)

  7. How can I import an SQL file using the command line in MySQL?

    Try:

    mysql -u username -p database_name < file.sql
    

    Check MySQL Options.

    Note 1: It is better to use the full path of the SQL file file.sql.

    Note 2: Use -R and --triggers with mysqldump to keep the routines and triggers of the original database. They are not copied by default.

    Note 3 You may have to create the (empty) database from MySQL if it doesn't exist already and the exported SQL doesn't contain CREATE DATABASE (exported with --no-create-db or -n option) before you can import it.

    From Stack Overflow: asked by Jaylen, answered by bansi (CC BY-SA 4.0)

  8. How to reset AUTO_INCREMENT in MySQL?

    You can reset the counter with:

    ALTER TABLE tablename AUTO_INCREMENT = 1
    

    InnoDB

    For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel):

    Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.

    Aria

    In a table with the Aria storage engine the auto_increment value can be set to any value, even lower than that of the current maximum. The next insert however will use the next available value (max + 1) ignoring the set value. If set to a higher value it will continue to use and increment from that. The documentation is not particular clear on that but this was observed with Mariadb 10.11.3

    See also

    See How can I reset an MySQL AutoIncrement using a MAX value from another table? on how to dynamically get an acceptable value.

    From Stack Overflow: asked by homerun, answered by Niels (CC BY-SA 4.0)

  9. How can I output MySQL query results in CSV format?

    From Save MySQL query results into a text or CSV file:

    SELECT order_id,product_name,qty
    FROM orders
    WHERE foo = 'bar'
    INTO OUTFILE '/var/lib/mysql-files/orders.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';
    

    Note: That syntax may need to be reordered to

    SELECT order_id,product_name,qty
    INTO OUTFILE '/var/lib/mysql-files/orders.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    FROM orders
    WHERE foo = 'bar';
    

    in more recent versions of MySQL.

    Using this command, columns names will not be exported.

    Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

    If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

    From Stack Overflow: asked by MCS, answered by Paul Tomblin (CC BY-SA 4.0)

  10. How can I get a list of user accounts using the command line in MySQL?

    Use this query:

    SELECT User FROM mysql.user;
    

    Which will output a table like this:

    +-------+
    | User  |
    +-------+
    | root  |
    +-------+
    | user2 |
    +-------+
    

    An advanced and efficient answer is the use of a stored procedure to retrieve MySQL users because it simplifies this repeated query, improves readability, and makes it easier to manage access in a secure, reusable way. You type it once, then you only need to type: CALL mysql.users(); to retrieve your mysql users.

    USE mysql;
    DELIMITER $$
    CREATE PROCEDURE users()
    BEGIN
      SELECT CONCAT(QUOTE(user), '@', QUOTE(host)) AS Users
      FROM mysql.user
      ORDER BY user, host;
    END $$
    DELIMITER ;
    CALL mysql.users();
    

    From Stack Overflow: asked by burntsugar, answered by George Claghorn (CC BY-SA 4.0)

  11. UTF-8 all the way through

    Data Storage:

    • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8.

      • Note that simply changing charset on a table (alter table test charset utf8mb4;) won't change the charset of the table columns. alter table test CONVERT TO charset utf8mb4; has to be using instead.
      • Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).
    • In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

    Data Access:

    • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

    • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

      • If you're using the PDO abstraction layer with PHP ≥ 5.3.6, you can specify charset in the DSN:

         $dbh = new PDO('mysql:charset=utf8mb4');
        
      • If you're using mysqli, you can call set_charset():

          $mysqli->set_charset('utf8mb4');       // object oriented style
          mysqli_set_charset($link, 'utf8mb4');  // procedural style
        
      • If you're stuck with plain mysql but happen to be running PHP ≥ 5.2.3, you can call mysql_set_charset.

    • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

    • The same consideration regarding utf8mb4/utf8 applies as above.

    Output:

    • UTF-8 should be set in the HTTP header, such as Content-Type: text/html; charset=utf-8. You can achieve that either by setting default_charset in php.ini (preferred), or manually using header() function.
    • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).
    • When encoding the output using json_encode(), you may want to add JSON_UNESCAPED_UNICODE as a second parameter to avoid using the JSON Unicode escaping.

    Input:

    Read the rest at the sourceFrom Stack Overflow: asked by mercutio, answered by chazomaticus (CC BY-SA 4.0)

  12. Retrieving the last record in each group - MySQL

    MySQL 8.0 now supports windowing functions, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries:

    WITH ranked_messages AS (
      SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn
      FROM messages AS m
    )
    SELECT * FROM ranked_messages WHERE rn = 1;
    

    This and other approaches to finding groupwise maximal rows are illustrated in the MySQL manual.

    Below is the original answer I wrote for this question in 2009:

    I write the solution this way:

    SELECT m1.*
    FROM messages m1 LEFT JOIN messages m2
     ON (m1.name = m2.name AND m1.id < m2.id)
    WHERE m2.id IS NULL;
    

    Regarding performance, one solution or the other can be better, depending on the nature of your data. So you should test both queries and use the one that is better at performance given your database.

    For example, I have a copy of the StackOverflow August data dump. I'll use that for benchmarking. There are 1,114,357 rows in the Posts table. This is running on MySQL 5.0.75 on my Macbook Pro 2.40GHz.

    I'll write a query to find the most recent post for a given user ID (mine).

    First using the technique shown by @Eric with the GROUP BY in a subquery:

    SELECT p1.postid
    FROM Posts p1
    INNER JOIN (SELECT pi.owneruserid, MAX(pi.postid) AS maxpostid
                FROM Posts pi GROUP BY pi.owneruserid) p2
      ON (p1.postid = p2.maxpostid)
    WHERE p1.owneruserid = 20860;
    1 row in set (1 min 17.89 sec)
    

    Even the EXPLAIN analysis takes over 16 seconds:

    +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
    | id | select_type | table      | type   | possible_keys              | key         | key_len | ref          | rows    | Extra       |
    +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
    |  1 | PRIMARY     | <derived2> | ALL    | NULL                       | NULL        | NULL    | NULL         |   76756 |             | 
    |  1 | PRIMARY     | p1         | eq_ref | PRIMARY,PostId,OwnerUserId | PRIMARY     | 8       | p2.maxpostid |       1 | Using where | 
    |  2 | DERIVED     | pi         | index  | NULL                       | OwnerUserId | 8       | NULL         | 1151268 | Using index | 
    +----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
    3 rows in set (16.09 sec)
    

    Now produce the same query result using my technique with LEFT JOIN:

    SELECT p1.postid
    FROM Posts p1 LEFT JOIN posts p2
      ON (p1.owneruserid = p2.owneruserid AND p1.postid < p2.postid)
    WHERE p2.postid IS NULL AND p1.owneruserid = 20860;
    1 row in set (0.28 sec)
    

    The EXPLAIN analysis shows that both tables are able to use their indexes:

    Read the rest at the sourceFrom Stack Overflow: asked by Vijay Dev, answered by Bill Karwin (CC BY-SA 4.0)

  13. How do I connect to a MySQL Database in Python?

    Connecting to MYSQL with Python 2 in three steps

    1 - Setting

    You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install. Please note MySQLdb only supports Python 2.

    For Windows user, you can get an exe of MySQLdb.

    For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

    For Mac, you can install MySQLdb using Macport.

    2 - Usage

    After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

    Then it is just like using any other package :

    #!/usr/bin/python
    import MySQLdb
    db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                         user="john",         # your username
                         passwd="megajonhy",  # your password
                         db="jonhydb")        # name of the data base
    # you must create a Cursor object. It will let
    #  you execute all the queries you need
    cur = db.cursor()
    # Use all the SQL you like
    cur.execute("SELECT * FROM YOUR_TABLE_NAME")
    # print all the first cell of all the rows
    for row in cur.fetchall():
        print row[0]
    db.close()
    

    Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

    3 - More advanced usage

    Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

    I strongly advise you to use it: your life is going to be much easier.

    I recently discovered another jewel in the Python world: peewee. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

    import peewee
    from peewee import *
    db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
    class Book(peewee.Model):
        author = peewee.CharField()
        title = peewee.TextField()
        class Meta:
            database = db
    Book.create_table()
    book = Book(author="me", title='Peewee is cool')
    book.save()
    for book in Book.filter(author="me"):
        print book.title
    

    This example works out of the box. Nothing other than having peewee (pip install peewee) is required.

    From Stack Overflow: asked by Marc Lincoln, answered by Bite code (CC BY-SA 4.0)

  14. How can I get the sizes of the tables of a MySQL database?

    You can use this query to show the size of a table (although you need to substitute the variables first):

    SELECT 
        table_name AS `Table`, 
        round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
    FROM information_schema.TABLES 
    WHERE table_schema = "$DB_NAME"
        AND table_name = "$TABLE_NAME";
    

    or this query to list the size of every table in every database, largest first:

    SELECT 
         table_schema as `Database`, 
         table_name AS `Table`, 
         round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
    FROM information_schema.TABLES 
    ORDER BY (data_length + index_length) DESC;
    

    From Stack Overflow: asked by JPashs, answered by ChapMic (CC BY-SA 3.0)

  15. Insert into a MySQL table or update if exists

    Use INSERT ... ON DUPLICATE KEY UPDATE

    QUERY:

    INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
    name="A", age=19
    

    From Stack Overflow: asked by Keshan, answered by Donnie (CC BY-SA 3.0)

  16. How do I rename a MySQL database (change schema name)?

    For InnoDB, the following seems to work: create the new empty database, then rename each table in turn into the new database:

    RENAME TABLE old_db.table TO new_db.table;
    

    You will need to adjust the permissions after that.

    For scripting in a shell, you can use either of the following:

    mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \ 
        do mysql -u username -ppassword -sNe "rename table old_db.$table to new_db.$table"; done
    

    OR

    for table in `mysql -u root -ppassword -s -N -e "use old_db;show tables from old_db;"`; do mysql -u root -ppassword -s -N -e "use old_db;rename table old_db.$table to new_db.$table;"; done;
    

    Notes:

    • There is no space between the option -p and the password. If your database has no password, remove the -u username -ppassword part.
    • If some table has a trigger, it cannot be moved to another database using above method (will result Trigger in wrong schema error). If that is the case, use a traditional way to clone a database and then drop the old one:

      mysqldump old_db | mysql new_db

    • If you have stored procedures, you can copy them afterwards:

      mysqldump -R old_db | mysql new_db

    From Stack Overflow: asked by deadprogrammer, answered by Thorsten (CC BY-SA 4.0)

  17. How can I do 'insert if not exists' in MySQL?

    Use INSERT IGNORE INTO table.

    There's also INSERT … ON DUPLICATE KEY UPDATE syntax, and you can find explanations in 13.2.6.2 INSERT ... ON DUPLICATE KEY UPDATE Statement.

    Post from bogdan.org.ua according to Google's webcache:

    18th October 2007

    To start: as of the latest MySQL, syntax presented in the title is not possible. But there are several very easy ways to accomplish what is expected using existing functionality.

    There are 3 possible solutions: using INSERT IGNORE, REPLACE, or INSERT … ON DUPLICATE KEY UPDATE.

    Imagine we have a table:

    CREATE TABLE `transcripts` (
    `ensembl_transcript_id` varchar(20) NOT NULL,
    `transcript_chrom_start` int(10) unsigned NOT NULL,
    `transcript_chrom_end` int(10) unsigned NOT NULL,
    PRIMARY KEY (`ensembl_transcript_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    Now imagine that we have an automatic pipeline importing transcripts meta-data from Ensembl, and that due to various reasons the pipeline might be broken at any step of execution. Thus, we need to ensure two things:

    1. repeated executions of the pipeline will not destroy our > database
    1. repeated executions will not die due to ‘duplicate > primary key’ errors.

    Method 1: using REPLACE

    It’s very simple:

    REPLACE INTO `transcripts`
    SET `ensembl_transcript_id` = 'ENSORGT00000000001',
    `transcript_chrom_start` = 12345,
    `transcript_chrom_end` = 12678;
    

    If the record exists, it will be overwritten; if it does not yet exist, it will be created. However, using this method isn’t efficient for our case: we do not need to overwrite existing records, it’s fine just to skip them.

    Method 2: using INSERT IGNORE Also very simple:

    INSERT IGNORE INTO `transcripts`
    SET `ensembl_transcript_id` = 'ENSORGT00000000001',
    `transcript_chrom_start` = 12345,
    `transcript_chrom_end` = 12678;
    

    Here, if the ‘ensembl_transcript_id’ is already present in the database, it will be silently skipped (ignored). (To be more precise, here’s a quote from MySQL reference manual: “If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted.”.) If the record doesn’t yet exist, it will be created.

    This second method has several potential weaknesses, including non-abortion of the query in case any other problem occurs (see the manual). Thus it should be used if previously tested without the IGNORE keyword.

    Method 3: using INSERT … ON DUPLICATE KEY UPDATE:

    Third option is to use INSERT … ON DUPLICATE KEY UPDATE syntax, and in the UPDATE part just do nothing do some meaningless (empty) operation, like calculating 0+0 (Geoffray suggests doing the id=id assignment for the MySQL optimization engine to ignore this operation). Advantage of this method is that it only ignores duplicate key events, and still aborts on other errors.

    As a final notice: this post was inspired by Xaprb. I’d also advise to consult his other post on writing flexible SQL queries.

    From Stack Overflow: asked by warren, answered by knittl (CC BY-SA 4.0)

  18. Storing vs calculating aggregate values

    It depends. Pre-calculating aggregate values places a larger load on writes, deriving them makes reads more difficult

    If you are frequently accessing a derived value, pre-calculation is a valid de-normalization step. However, in this instance, I recommend using a Materialized View (a view, written to disk, linked by trigger to the parent tables). The materialized view is designed to store frequently asked but tedious-to-derive data, and is useful for high numbers of writes and low numbers of reads.

    In a high-write, high-read scenario, consider having a task in the background which mimics the effects of a materialized view, but in less than real-time. This will present a "good enough" average while preserving write and read performance.

    In no circumstances, should you treat the derived column like a "normal" column: make sure the data presented in the Widgets "view" is present elsewhere in the table, such that the entire tuple can be derived by whatever processes you emplace. This question is also strongly database (and database-version) specific, so I recommend performance testing of the aggregate (with appropriate indexes) against a normal-sized data set and the materialized view.

    From Database Administrators Stack Exchange: asked by BenV, answered by Brian Ballsun-Stanton (CC BY-SA 2.5)

  19. What is the default order of records for a SELECT statement in MySQL?

    Reposting my answer to a similar question regarding SQL Server:

    In the SQL world, order is not an inherent property of a set of data. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order -- or even in a consistent order -- unless you query your data with an ORDER BY clause.

    So, to answer your question:

    • MySQL sorts the records however it wants without any guarantee of consistency.
    • If you intend to rely on this order for anything, you must specify your desired order using ORDER BY. To do anything else is to set yourself up for unwelcome surprises.

    This is a property of all SQL, not just MySQL. The relevant text in the SQL-92 spec is:

    If an <order by clause> is not specified, then the ordering of the rows of Q is implementation-dependent.

    There are similar bits of text in the spec for cursors.

    From Database Administrators Stack Exchange: asked by daisy, answered by Nick Chammas (CC BY-SA 3.0)

  20. Difference between On Delete Cascade & On Update Cascade in mysql

    A very good thread on this subject is to be found here and also here. The definitive guide for MySQL is, of course, the documentation, to be found here.

    In the SQL 2003 standard there are 5 different referential actions:

    1. CASCADE
    2. RESTRICT
    3. NO ACTION
    4. SET NULL
    5. SET DEFAULT

    To answer the question:

    1. CASCADE

      • ON DELETE CASCADE means that if the parent record is deleted, any child records are also deleted. This is not a good idea in my opinion. You should keep track of all data that's ever been in a database, although this can be done using TRIGGERs. (However, see caveat in comments below).

      • ON UPDATE CASCADE means that if the parent primary key is changed, the child value will also change to reflect that. Again in my opinion, not a great idea. If you're changing PRIMARY KEYs with any regularity (or even at all!), there is something wrong with your design. Again, see comments.

      • ON UPDATE CASCADE ON DELETE CASCADE means that if you UPDATE OR DELETE the parent, the change is cascaded to the child. This is the equivalent of ANDing the outcomes of first two statements.

    2. RESTRICT

      • RESTRICT means that any attempt to delete and/or update the parent will fail throwing an error. This is the default behaviour in the event that a referential action is not explicitly specified.

        For an ON DELETE or ON UPDATE that is not specified, the default action is always RESTRICT`.

    3. NO ACTION

      • NO ACTION: From the manual. A keyword from standard SQL. In MySQL, equivalent to RESTRICT. The MySQL Server rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.
    4. SET NULL

      • SET NULL - again from the manual. Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL. This is not the best of ideas IMHO, primarily because there is no way of "time-travelling" - i.e. looking back into the child tables and associating records with NULLs with the relevant parent record - either CASCADE or use TRIGGERs to populate logging tables to track changes (but, see comments).
    5. SET DEFAULT

      • SET DEFAULT. Yet another (potentially very useful) part of the SQL standard that MySQL hasn't bothered implementing! Allows the developer to specify a value to which to set the foreign key column(s) on an UPDATE or a DELETE. InnoDB and NDB will reject table definitions with a SET DEFAULT clause.

    As mentioned above, you should spend some time looking at the documentation, here.

    From Database Administrators Stack Exchange: asked by Smokey, answered by Vérace (CC BY-SA 3.0)

  21. What is the best way to reduce the size of ibdata in mysql?

    Keep in mind the busiest file in the InnoDB infrastructure is /var/lib/mysql/ibdata1

    This file normally houses many classes of information (when innodb_file_per_table is 0)

    • Table Data
    • Table Indexes
    • MVCC (Multiversioning Concurrency Control) Data
      • Rollbacks Segments
      • Undo Tablespace
    • Table Metadata
    • See Pictorial Representation

    Many people create multiple ibdata files hoping for better diskspace management and performance. It does not help.

    Unfortunately, OPTIMIZE TABLE against an InnoDB table stored in ibdata1 does two things:

    • Makes the table's data and indexes contiguous inside ibdata1
    • It makes ibdata1 grow because the contiguous data is appended to ibdata1

    You can segregate Table Data and Table Indexes from ibdata1 and manage them independently using innodb_file_per_table. To shrink ibdata1 once and for all you must do the following

    Step 01) MySQLDump all databases into a SQL text file (call it SQLData.sql) (More details here)

    Step 02) Drop all databases (except mysql, performance_schema, and information_schema)

    Step 03) Shutdown mysql

    Step 04) Add the following lines to /etc/my.cnf

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Step 05) Delete ibdata1, ib_logfile0 and ib_logfile1

    At this point, there should only be the mysql schema in /var/lib/mysql

    Step 06) Restart mysql

    This will recreate ibdata1 at 10MB, ib_logfile0 and ib_logfile1 at 1G each

    Step 07) Reload SQLData.sql into mysql

    ibdata1 will grow but only contain table metadata

    Each InnoDB table will exist outside of ibdata1

    Suppose you have an InnoDB table named mydb.mytable. If you go into /var/lib/mysql/mydb, you will see two files representing the table

    • mytable.frm (Storage Engine Header)
    • mytable.ibd (Home of Table Data and Table Indexes for mydb.mytable)

    ibdata1 will never contain InnoDB data and Indexes anymore.

    With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

    I have done this many times in my career as a MySQL DBA

    In fact, the first time I did this, I collapsed a 50GB ibdata1 file into 500MB.

    Give it a try. If you have further questions on this, email me. Trust me. This will work in the short term and over the long haul. !!!

    If you would like to see how much actual data is stored in MyISAM and InnoDB, please run this query:

    SELECT IFNULL(B.engine,'Total') "Storage Engine",
    CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',
    SUBSTR(' KMGTP',pw+1,1),'B') "Data Size", CONCAT(LPAD(REPLACE(
    FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',
    SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(REPLACE(
    FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',
    SUBSTR(' KMGTP',pw+1,1),'B') "Table Size"
    FROM (SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize,
    SUM(data_length+index_length) TSize FROM information_schema.tables
    WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')
    AND engine IS NOT NULL GROUP BY engine WITH ROLLUP) B,
    (SELECT 3 pw) A ORDER BY TSize;
    

    From Database Administrators Stack Exchange: asked by Abdul Manaf, answered by RolandoMySQLDBA (CC BY-SA 3.0)

  22. Is it safe to use innodb_flush_log_at_trx_commit = 2

    You can lose up to one second's worth of transactions. The default value is 1, which helps keep InnoDB ACID Compliant.

    According to the MySQL Documentation on innodb_flush_log_at_trx_commit

    If the value of innodb_flush_log_at_trx_commit is 0, the log buffer is written out to the log file once per second and the flush to disk operation is performed on the log file, but nothing is done at a transaction commit. When the value is 1 (the default), the log buffer is written out to the log file at each transaction commit and the flush to disk operation is performed on the log file. When the value is 2, the log buffer is written out to the file at each commit, but the flush to disk operation is not performed on it. However, the flushing on the log file takes place once per second also when the value is 2. Note that the once-per-second flushing is not 100% guaranteed to happen every second, due to process scheduling issues.

    The default value of 1 is required for full ACID compliance. You can achieve better performance by setting the value different from 1, but then you can lose up to one second worth of transactions in a crash. With a value of 0, any mysqld process crash can erase the last second of transactions. With a value of 2, only an operating system crash or a power outage can erase the last second of transactions. InnoDB's crash recovery works regardless of the value.

    For the greatest possible durability and consistency in a replication setup using InnoDB with transactions, use innodb_flush_log_at_trx_commit=1 and sync_binlog=1 in your master server my.cnf file.

    Caution

    Many operating systems and some disk hardware fool the flush-to-disk operation. They may tell mysqld that the flush has taken place, even though it has not. Then the durability of transactions is not guaranteed even with the setting 1, and in the worst case a power outage can even corrupt the InnoDB database. Using a battery-backed disk cache in the SCSI disk controller or in the disk itself speeds up file flushes, and makes the operation safer. You can also try using the Unix command hdparm to disable the caching of disk writes in hardware caches, or use some other command specific to the hardware vendor.

    Based on this, values other than 1 put InnoDB at risk of losing 1 second's worth of transactions, or a transaction commit's worth of data.

    The documentation also says use sync_binlog=1.

    According to the MySQL Documentation on sync_binlog

    A value of 1 is the safest choice because in the event of a crash you lose at most one statement or transaction from the binary log. However, it is also the slowest choice (unless the disk has a battery-backed cache, which makes synchronization very fast).

    Your safest choice is

    [mysqld]
    innodb_flush_log_at_trx_commit=1
    sync_binlog=1
    

    If you do not mind possible data loss (up to 1 second's worth) then you can use either 0 or 2 at your own risk if the rewards (faster write speed) are worth it.

    From Database Administrators Stack Exchange: asked by Bruce Dou, answered by RolandoMySQLDBA (CC BY-SA 3.0)

  23. What is the performance impact of using CHAR vs VARCHAR on a fixed-size field?

    A similar question was asked before

    Performance implications of MySQL VARCHAR sizes

    Here is the excerpt of my answer

    You must realize the tradeoffs of using CHAR vs VARCHAR

    With CHAR fields, what you allocate is exactly what you get. For example, CHAR(15) allocates and stores 15 bytes, no matter how characters you place in the field. String manipulation is simple and straightforward since the size of the data field is totally predictable.

    With VARCHAR fields, you get a completely different story. For example VARCHAR(15) actually allocates dynamically up to 16 bytes, up to 15 for data and, at least, 1 additional byte to store the the length of the data. If you have the string 'hello' to store that will take 6 bytes, not 5. String manipulation must always perform some form of length checking in all cases.

    The tradeoff is more evident when you do two things: 1. Storing millions or billions of rows 2. Indexing columns that are either CHAR or VARCHAR

    TRADEOFF #1 Obviously, VARCHAR holds the advantage since variable-length data would produce smaller rows and, thus, smaller physical files.

    TRADEOFF #2 Since CHAR fields require less string manipulation because of fixed field widths, index lookups against CHAR field are on average 20% faster than that of VARCHAR fields. This is not any conjecture on my part. The book MySQL Database Design and Tuning performed something marvelous on a MyISAM table to prove this. The example in the book did something like the following:

    ALTER TABLE tblname ROW_FORMAT=FIXED;
    

    This directive forces all VARCHARs to behave as CHARs. I did this at my previous job back in 2007 and took a 300GB table and sped up index lookups by 20%, without changing anything else. It worked as published. However, it did produce a table almost double in size, but that simply goes back to tradeoff #1.

    You could analyze the data being stored to see what MySQL recommends for column definition. Just run the following against any table:

    SELECT * FROM tblname PROCEDURE ANALYSE();
    

    This will traverse the entire table and recommend column definitions for every column based on the data it contains, the minimum field values, maximum field values, and so forth. Sometimes, you just have to use common sense with planning CHAR vs VARCHAR. Here is a good example:

    If you are storing IP addresses, the mask for such a column is at most 15 characters (xxx.xxx.xxx.xxx). I would jump right at CHAR(15) in a heartbeat because the lengths of IP addresses will not vary all that much and the added complexity of string manipulation controlled by an additional byte. You could still do a PROCEDURE ANALYSE() against such a column. It may even recommend VARCHAR. My money would still be on CHAR over VARCHAR in this instance.

    CHAR vs VARCHAR issues can be resolved only through proper planning. With great power comes great responsibility (cliche but true).

    UPDATE

    When it comes to MD5, the computation of strlen internally should be eliminated when switching the entire row format. There would be no need to change the field definition.

    If the MD5 key is the only VARCHAR present, I would go for it and convert the table row format to fixed. If there is a signifcant number of other VARCHAR fields present, they would benefit as well. In exchange, the table would expand to about twice its size. But queries should accelerate about 20% more without additional tuning.

    From Database Administrators Stack Exchange: asked by Jason Baker, answered by RolandoMySQLDBA (CC BY-SA 3.0)

  24. Find highest level of a hierarchical field: with vs without CTEs

    You definitely have to script this via MySQL Stored Procedure Language

    Here is a Stored Function called GetParentIDByIDto Retrieve a ParentID given an ID to Search For

    DELIMITER $$
    DROP FUNCTION IF EXISTS `junk`.`GetParentIDByID` $$
    CREATE FUNCTION `junk`.`GetParentIDByID` (GivenID INT) RETURNS INT
    DETERMINISTIC
    BEGIN
        DECLARE rv INT;
        SELECT IFNULL(parent_id,-1) INTO rv FROM
        (SELECT parent_id FROM pctable WHERE id = GivenID) A;
        RETURN rv;
    END $$
    DELIMITER ;
    

    Here is a Stored Function called GetAncestryto Retrieve a List of ParentIDs starting from the First Generation all the up the hierarchy given an ID to start with:

    DELIMITER $$
    DROP FUNCTION IF EXISTS `junk`.`GetAncestry` $$
    CREATE FUNCTION `junk`.`GetAncestry` (GivenID INT) RETURNS VARCHAR(1024)
    DETERMINISTIC
    BEGIN
        DECLARE rv VARCHAR(1024);
        DECLARE cm CHAR(1);
        DECLARE ch INT;
        SET rv = '';
        SET cm = '';
        SET ch = GivenID;
        WHILE ch > 0 DO
            SELECT IFNULL(parent_id,-1) INTO ch FROM
            (SELECT parent_id FROM pctable WHERE id = ch) A;
            IF ch > 0 THEN
                SET rv = CONCAT(rv,cm,ch);
                SET cm = ',';
            END IF;
        END WHILE;
        RETURN rv;
    END $$
    DELIMITER ;
    

    Here is something to generate sample data:

    USE junk
    DROP TABLE IF EXISTS pctable;
    CREATE TABLE pctable
    (
        id INT NOT NULL AUTO_INCREMENT,
        parent_id INT,
        PRIMARY KEY (id)
    ) ENGINE=MyISAM;
    INSERT INTO pctable (parent_id) VALUES (0);
    INSERT INTO pctable (parent_id) SELECT parent_id+1 FROM pctable;
    INSERT INTO pctable (parent_id) SELECT parent_id+2 FROM pctable;
    INSERT INTO pctable (parent_id) SELECT parent_id+3 FROM pctable;
    INSERT INTO pctable (parent_id) SELECT parent_id+4 FROM pctable;
    INSERT INTO pctable (parent_id) SELECT parent_id+5 FROM pctable;
    SELECT * FROM pctable;
    

    Here is what it generates:

    mysql> USE junk
    Database changed
    mysql> DROP TABLE IF EXISTS pctable;
    Query OK, 0 rows affected (0.00 sec)
    mysql> CREATE TABLE pctable
        -> (
        ->     id INT NOT NULL AUTO_INCREMENT,
        ->     parent_id INT,
        ->     PRIMARY KEY (id)
        -> ) ENGINE=MyISAM;
    Query OK, 0 rows affected (0.05 sec)
    mysql> INSERT INTO pctable (parent_id) VALUES (0);
    Query OK, 1 row affected (0.00 sec)
    mysql> INSERT INTO pctable (parent_id) SELECT parent_id+1 FROM pctable;
    Query OK, 1 row affected (0.00 sec)
    Records: 1  Duplicates: 0  Warnings: 0
    mysql> INSERT INTO pctable (parent_id) SELECT parent_id+2 FROM pctable;
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    mysql> INSERT INTO pctable (parent_id) SELECT parent_id+3 FROM pctable;
    Query OK, 4 rows affected (0.00 sec)
    Records: 4  Duplicates: 0  Warnings: 0
    mysql> INSERT INTO pctable (parent_id) SELECT parent_id+4 FROM pctable;
    Query OK, 8 rows affected (0.01 sec)
    Records: 8  Duplicates: 0  Warnings: 0
    mysql> INSERT INTO pctable (parent_id) SELECT parent_id+5 FROM pctable;
    Query OK, 16 rows affected (0.00 sec)
    Records: 16  Duplicates: 0  Warnings: 0
    mysql> SELECT * FROM pctable;
    +----+-----------+
    | id | parent_id |
    +----+-----------+
    |  1 |         0 |
    |  2 |         1 |
    |  3 |         2 |
    |  4 |         3 |
    |  5 |         3 |
    |  6 |         4 |
    |  7 |         5 |
    |  8 |         6 |
    |  9 |         4 |
    | 10 |         5 |
    | 11 |         6 |
    | 12 |         7 |
    | 13 |         7 |
    | 14 |         8 |
    | 15 |         9 |
    | 16 |        10 |
    | 17 |         5 |
    | 18 |         6 |
    | 19 |         7 |
    | 20 |         8 |
    | 21 |         8 |
    | 22 |         9 |
    | 23 |        10 |
    | 24 |        11 |
    | 25 |         9 |
    | 26 |        10 |
    | 27 |        11 |
    | 28 |        12 |
    | 29 |        12 |
    | 30 |        13 |
    | 31 |        14 |
    | 32 |        15 |
    +----+-----------+
    32 rows in set (0.00 sec)
    

    Here are what the functions generate for each value:

    Read the rest at the sourceFrom Database Administrators Stack Exchange: asked by David LeBauer, answered by RolandoMySQLDBA (CC BY-SA 3.0)

  25. How does ORDER BY FIELD() in MySQL work internally?

    For the record

    SELECT * FROM mytable WHERE id IN (1,2,3,4) ORDER BY FIELD(id,3,2,1,4);
    

    should work as well because you do not have to order the list in the WHERE clause

    As for how it works,

    • FIELD() is a function that returns the index position of a comma-delimited list if the value you are searching for exists.

    • The ORDER BY values are evaluated by what FIELD() returns

    You can create all sorts of fancy orders

    For example, using the IF() function

    SELECT * FROM mytable
    WHERE id IN (1,2,3,4)
    ORDER BY IF(FIELD(id,3,2,1,4)=0,1,0),FIELD(id,3,2,1,4);
    

    This will cause the first 4 ids to appear at the top of the list, Otherwise, it appears at the bottom. Why?

    In the ORDER BY, you either get 0 or 1.

    • If the first column is 0, make any of the first 4 ids appear
    • If the first column is 1, make it appear afterwards

    Let's flip it with DESC in the first column

    SELECT * FROM mytable
    WHERE id IN (1,2,3,4)
    ORDER BY IF(FIELD(id,3,2,1,4)=0,1,0) DESC,FIELD(id,3,2,1,4);
    

    In the ORDER BY, you still either get 0 or 1.

    • If the first column is 1, make anything but the first 4 ids appear.
    • If the first column is 0, make the first 4 ids appear in the original order

    YOUR ACTUAL QUESTION

    If you seriously want internals on this, goto pages 189 and 192 of the Book

    for a real deep dive.

    In essence, there is a C++ class called ORDER *order (The ORDER BY expression tree). In JOIN::prepare, *order is used in a function called setup_order(). Why in the middle of the JOIN class? Every query, even a query against a single table is always processed as a JOIN (See my post Is there an execution difference between a JOIN condition and a WHERE condition?)

    The source code for all this is sql/sql_select.cc

    Evidently, the ORDER BY tree is going to hold the evaluation of FIELD(id,3,2,1,4). Thus, the numbers 0,1,2,3,4 are the values being sorted while carrying a reference to the row involved.

    From Database Administrators Stack Exchange: asked by itz_nsn, answered by RolandoMySQLDBA (CC BY-SA 3.0)

  26. When to use views in MySQL?

    Views in MySQL are handled using one of two different algorithms: MERGE or TEMPTABLE. MERGE is simply a query expansion with appropriate aliases. TEMPTABLE is just what it sounds like, the view puts the results into a temporary table before running the WHERE clause, and there are no indexes on it.

    The 'third' option is UNDEFINED, which tells MySQL to select the appropriate algorithm. MySQL will attempt to use MERGE because it is more efficient. Main Caveat:

    If the MERGE algorithm cannot be used, a temporary table must be used instead. MERGE cannot be used if the view contains any of the following constructs:

    • Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)

    • DISTINCT

    • GROUP BY

    • HAVING

    • LIMIT

    • UNION or UNION ALL

    • Subquery in the select list

    • Refers only to literal values (in this case, there is no underlying table)

    [src]

    I would venture to guess your VIEWS are requiring the TEMPTABLE algorithm, causing performance issues.

    Here is a really old blog post on the performance of views in MySQL and it doesn't seem to have gotten better.

    There might, however, be some light at the end of the tunnel on this issue of temporary tables not containing indexes (causing full table scans). In 5.6:

    For cases when materialization is required for a subquery in the FROM clause, the optimizer may speed up access to the result by adding an index to the materialized table. ... After adding the index, the optimizer can treat the materialized derived table the same as a usual table with an index, and it benefits similarly from the generated index. The overhead of index creation is negligible compared to the cost of query execution without the index.

    As @ypercube points out, MariaDB 5.3 has added the same optimization. This article has an interesting overview of the process:

    The optimization is applied then the derived table could not be merged into its parent SELECT which happens when the derived table doesn't meet criteria for mergeable VIEW

    From Database Administrators Stack Exchange: asked by David LeBauer, answered by Derek Downey (CC BY-SA 4.0)

  27. Which is faster, InnoDB or MyISAM?

    The only way MyISAM can be faster that InnoDB would be under this unique circumstance

    MyISAM

    When read, a MyISAM table's indexes can be read once from the .MYI file and loaded in the MyISAM Key Cache (as sized by key_buffer_size). How can you make a MyISAM table's .MYD faster to read? With this:

    ALTER TABLE mytable ROW_FORMAT=Fixed;
    

    I wrote about this in my past posts

    InnoDB

    OK, what about InnoDB? Does InnoDB do any disk I/O for queries? Surprisingly, yes it does !! You are probably thinking I am crazy for saying that, but it is absolutely true, even for SELECT queries. At this point, you are probably wondering "How in the world is InnoDB doing disk I/O for queries?"

    It all goes back to InnoDB being an ACID-complaint Transactional Storage Engine. In order for InnoDB to be Transactional, it has to support the I in ACID, which is Isolation. The technique for maintaining isolation for transactions is done via MVCC, Multiversion Concurrency Control. In simple terms, InnoDB records what data looks like before transactions attempt to change them. Where does that get recorded? In the system tablespace file, better known as ibdata1. That requires disk I/O.

    COMPARISON

    Since both InnoDB and MyISAM do disk I/O, what random factors dictate who is faster?

    • Size of Columns
    • Column Format
    • Character Sets
    • Range of Numeric Values (requiring large enough INTs)
    • Rows Being Split Across Blocks (Row Chaining)
    • Data Fragmentation caused by DELETEs and UPDATEs
    • Size of Primary Key (InnoDB has a Clustered Index, requiring two key lookups)
    • Size of Index Entries
    • the list goes on...

    Thus, in a heavy-read environment, it is possible for a MyISAM table with a Fixed Row Format to outperform InnoDB reads out of the InnoDB Buffer Pool if there is enough data being written into the undo logs contained within ibdata1 to support the transactional behavior imposed on the InnoDB data.

    CONCLUSION

    Plan your data types, queries, and storage engine real carefully. Once the data grows, it might become very difficult to move data around. Just ask Facebook...

    From Database Administrators Stack Exchange: asked by jcho360, answered by RolandoMySQLDBA (CC BY-SA 4.0)

  28. What is the meaning of filtered in MySQL explain?

    To filter here means to apply a condition on a set of rows that were selected by a type-search as potential rows, and to only keep rows that fulfill the condition:

    MySQL will first try to use an index, e.g. do a range scan on your table a using the search-key. It estimates to get 174 rows out of using that index, which is the number in rows. This step is not yet called filtering.

    After that, these 174 rows have to be checked against additional conditions (usually in your where-clause). MySQL now estimated that only 32 rows, so 18% of these 174 rows, will remain after that filter has been applied. This 18% is the value in filtered.

    While it is obviously better to have 32 rows instead of 174 (if you e.g. have to later join them with another table), a "perfect" index would have given you these 32 rows directly from the initial search, saving you the time to look at and filter out 82% of all potential rows.

    So a low value might indicate that there could be a better index: e.g. a full table scan with rows=1000 and filtered=0.1% could become an index lookup with rows=1 and filtered=100% if you add a good index.

    On the other hand, you can very well completely ignore this filtered-value (which is in most cases a really bad estimate anyway), and focus on the other more important columns (especially type, key and extra) to optimize your query. It can e.g. be better to get rid of a filesort (e.g. by using an index that satisfies the order by), even if it results in a lower filtered value. And a better type can result in a huge performance improvement, even if it might not change or even lower filtered. In the example above with filtered=0.1%, type=all would have already be enough to indicate that you might be able to improve that query by adding an index, without looking at filtered at all.

    So don't take that value too seriously: neither does 100 mean your indexes are good, nor does a lower value necessarily indicate bad indexes. type is a much better indicator for that.

    From Database Administrators Stack Exchange: asked by Iman Tumorang, answered by Solarflare (CC BY-SA 3.0)

  29. Why aren't primary key / foreign key matches used for joins?

    In many cases, there are more than one way to join two tables; See the other answers for lots of examples. Of course, one could say that it would be an error to use the 'automatic join' in those cases. Then only a handfull of simple cases where it can be used would be left.

    However, there is a severe drawback! Queries that are correct today, might become an error tomorrow just by adding a second FK to the same table!

    Let me say that again: by adding columns, queries that do not use those columns could turn from 'correct' into 'error'!

    That is such a maintenance nightmare, that any sane style guide would prohibit to use this feature. Most already prohibit select * for the same reason!

    All this would be acceptable, if performance would be enhanced. However, that's not the case.

    Summarizing, this feature could be used in only a limited set of simple cases, does not increase performance, and most style guides would prohibit its usage anyway.

    Therefor it is not supprising that most database vendors choose to spend their time on more important things.

    From Database Administrators Stack Exchange: asked by Tiddo, answered by Sjoerd (CC BY-SA 3.0)

  30. How can I monitor the progress of an import of a large .sql file?

    If you're just importing from a dump file from the CLI on *nix, e.g.

    mysql -uxxx -pxxx dbname < /sqlfile.sql
    

    then first install pipe viewer on your OS then try something like this:

    pv sqlfile.sql | mysql -uxxx -pxxxx dbname
    

    which will show a progress bar as the program runs.

    It's very useful and you can also use it to get an estimate for mysqldump progress.

    pv dumps the sqlfile.sql and passes them to mysql (because of the pipe operator). While it is dumping, it shows the progress. The cool thing is that mysql takes the data only as fast as it can progress it, so pv can show the progress of the import. I do not have any proof. But it seems so. I guess there is some buffer used, but at some point I think mysql does not read any more data when it is still busy processing.

    From Database Administrators Stack Exchange: asked by qazwsx, answered by Rob (CC BY-SA 3.0)

After the last page: 8 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.