« first day (1484 days earlier)      last day (1174 days later) » 

3:16 AM
Which MySQL query would be more efficient to find if a username is taken?
SELECT * FROM users WHERE Username = "[USER]"
or...
SELECT id FROM users WHERE Username = "[USER]"
Would the first query search my entire database before returning the result, while the second one only scans the database until it find the first match?
 
 
2 hours later…
5:23 AM
hello ?
anyone here ?
 
 
4 hours later…
ASR
9:26 AM
Hi
@TehShrike hi
 
 
4 hours later…
1:44 PM
@Leaf There's a couple wrong assumptions there. They would both cover the same number of rows, unless you used a LIMIT on one of the queries. However, Username should have a unique key on it, which would make them both know to stop after it found the one row.
@Leaf But assuming that id is the primary key, and you're using the InnoDB storage engine, the unique key on Username would be a covering index for the second query, making it potentially much more efficient (though in practice it probably wouldn't matter until you had millions of users)
@Leaf Best practice is to NOT use SELECT * in any production queries, and to only select the columns that you need.
@jemz As the topic says, Ask your question, and then hang around a while to see if an expert looks back at their screen and answers it!
@ASR Howdy!
 
ASR
@TehShrike hi
While executing stored procedure I am getting the following error
The user specified as a definer ('root'@'%') does not exist
 
 
1 hour later…
3:18 PM
@ASR Yeah, stored procedure security is kind of weird. Check out the SQL SECURITY stuff on the CREATE PROCEDURE page - you probably want it to be "invoker" for your procedures.
 
 
2 hours later…
5:20 PM
@TehShrike Thank you for your answer!
My storage engine is MyISAM, if that's important. My client likely won't ever get more than 1000 users, and by the time he does, I'll hopefully be much more experienced. :p
I guess it isn't too important figuring out which is more efficient. I'll see if I can Google more about not using SELECT * and how to use an alternative.
Thank you again!
Okay so I think I get it now...
I wouldn't be selecting the ID column because that's not what's being searched and thus doesn't matter, so instead I should simply select the Username column like so:

mysqli_query($mysqliConnection, "SELECT Username FROM users WHERE Username = '".$username."'");

or without the php:

SELECT Username FROM users WHERE Username = '[USERNAME]'
Though I should probably research the select query a bit more
 
6:04 PM
@Leaf If all you care about is "is there a match" then you can just SELECT COUNT(*) FROM users WHERE username = ?
@Leaf Check out select * is evil
@Leaf I would very very highly recommend using InnoDB as your storage engine. MyISAM has been the inferior choice for nearly a decade now
Also, just to make sure, do you have a unique key on the username column?
 

« first day (1484 days earlier)      last day (1174 days later) »