Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
Casey Flynn Avatar asked Aug 02 '11 14:08

Casey Flynn


1 Answers

There could be only one row, matching the user_agent and the session_id, so there will be no need to limit the number of selections, it is already limited by being the only one.

The issue has been reported to the Codeigniter Reactor devs on Bitbucket and dismissed as invalid:

https://bitbucket.org/ellislab/codeigniter-reactor/issue/422/session-class-should-use-limit-1-when

Their response:

the session_id field is a primary key so it's going to be a unique row

Is there any point using MySQL "LIMIT 1" when querying on indexed/unique field?

So it would appear that this is not in fact an optimization, it's just unnecessary.

like image 193
Grigor Avatar answered Oct 18 '22 14:10

Grigor