[Solved] Codeigniter sessions class w/ database storage option not optimized?

EverSQL Database Performance Knowledge Base

Codeigniter sessions class w/ database storage option not optimized?

I use codeigniter's session class with the option to store session data in a database. This is an example of the select query that runs for every user request to retrieve a session:

SELECT *
FROM (`ci_sessions`)
WHERE `session_id` = 'f7fd61f08a229kdu3093130a3da17e14'
AND `user_agent` = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.'

Here is the table structure for session data as defined in the user guide:

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text DEFAULT '' NOT NULL,
PRIMARY KEY (session_id)
);

It's my understanding that whenever you have a query that's intended to return a single result it's good practice to use LIMIT 0, 1 so that when the database engine finds the desired row it simply returns rather than continuing to scan the entire table for more matches. Therefore would it be more efficient for this query to be written as:

SELECT *
FROM (`ci_sessions`)
WHERE `session_id` = 'f7fd61f08a229kdu3093130a3da17e14'
AND `user_agent` = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.'
LIMIT 0, 1

Is there any reason it isn't already written this way?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `ci_sessions` ADD INDEX `ci_sessions_idx_session_id_user_agent` (`session_id`,`user_agent`);
The optimized query:
SELECT
        * 
    FROM
        (`ci_sessions`) 
    WHERE
        `ci_sessions`.`session_id` = 'f7fd61f08a229kdu3093130a3da17e14' 
        AND `ci_sessions`.`user_agent` = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.'

Related Articles



* original question posted on StackOverflow here.