Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LIMIT when searching by a unique field

Tags:

sql

indexing

Given a table structure like this:

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(32) NOT NULL,
  `username` varchar(16) NOT NULL,
  `password` char(32) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `username` (`username`)
);

Is there any use in using the LIMIT keyword when searching by username, or is the DB smart enough to know that there can only possibly be one result, and therefore stop searching once it's found one?

SELECT * FROM `user` WHERE `username` = 'nick';

-- vs --

SELECT * FROM `user` WHERE `username` = 'nick' LIMIT 1;

Update: Thanks for the answers, they've been enlightening. It seems like, even though it's unnecessary, putting LIMIT 1 on the query doesn't hurt, and probably increases readability (you don't have to go looking into the DB schema to know that only one is going to be returned). Special shoutout for JR's answer - I didn't even know you could do that with indices.

Also, there's a similar question I've found here, which might also help.

like image 544
nickf Avatar asked Dec 13 '25 04:12

nickf


1 Answers

There is no need to use LIMIT.

However... If you have a HUGE HUGE HUGE cardinality on the table (and you're worried about speed), you might consider not using the special UNIQUE constraint in the DB and manage it from your application. Then, you can specify an INDEX on only the first few characters of your username field. This will drastically reduce the size of your index, being sure the whole thing fits into RAM, and possibly speed up your queries.

So, you might try:

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(32) NOT NULL,
  `username` varchar(16) NOT NULL,
  `password` char(32) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `username` (`username`(4))
);

as an alternative if your first attempt turns out to be too slow. This means, of course, you have to check for duplicate user names before inserting, but you'll probably have to do that anyway to tell the user they have to pick another user name.

Depending on what DB server and engine you're using, it may also be faster to specify fixed width fields for all your strings also. Instead of varchar, use char.

like image 96
JR Lawhorne Avatar answered Dec 14 '25 18:12

JR Lawhorne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!