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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With