SQL Query Optimization for Faster Sites

SQL Query Optimization for Faster Sites

Identification

Query Monitor results

Understanding

MySQL is your Friend

FieldTypeNullKeyDefaultExtra
meta_idbigint(20) unsignedNOPRINULLauto_increment
post_idbigint(20) unsignedNOMUL0
meta_keyvarchar(255)YESMULNULL
meta_valuelongtextYESNULL
idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEpm2refmeta_keymeta_key576const28Using where; Using temporary; Using filesort
1SIMPLEpmrefpost_id,meta_keymeta_key576const37456Using where
1SIMPLEpeq_refPRIMARY,type_status_datePRIMARY8deliciousbrainsdev.pm.post_id1Using where
1SIMPLElrefPRIMARY,order_idorder_id8deliciousbrainsdev.pm.post_id1Using index condition; Using where
1SIMPLEseq_refPRIMARYPRIMARY8deliciousbrainsdev.l.key_id1NULL

Visual Investigation

MySQl Workbench Visual Results

Solving

Indexes

CREATE INDEX order_id ON wp_woocommerce_software_licences(order_id)
SQL results with index

Know your Query

Query results without redundant join

Cache All The Things!

class WC_Software_Subscription {

    protected static $subscriptions = array();

    public static function get_user_subscriptions( $user_id ) {
        if ( isset( static::$subscriptions[ $user_id ] ) ) {
            return static::$subscriptions[ $user_id ];
        }

        global $wpdb;

        $sql = '...';

        $results = $wpdb->get_results( $sql, ARRAY_A );

        static::$subscriptions[ $user_id ] = $results;

        return $results;
    }
}

Thinking Outside the Box

Results

Comments

Popular posts from this blog

A Tailwind CSS Preset for Laravel 5.5

Short and safe array iteration

PHPStorm's performance