Which is a faster query?
Posted: Thu Sep 17, 2009 12:55 pm
Code: Select all
SELECT * FROM table WHERE FIELD = 'field';Code: Select all
SELECT 1 FROM table WHERE FIELD = 'field';A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
SELECT * FROM table WHERE FIELD = 'field';Code: Select all
SELECT 1 FROM table WHERE FIELD = 'field';I don't need any columns, just a row to say that there is a user, is a something, is a whatever, etc. It's just so I can check to see if something exists, and if not I could add that something in another query.pytrin wrote:If you don't need all the columns, select just what you need.
Code: Select all
SELECT COUNT(`field`) FROM `table` WHERE `field` = 'foo';Well I'm only expecting one row. But I whenever I need to count the rows returned I will do it with the COUNT function, like you said. But in order for the COUNT function to work, do I need the GROUP BY clause? I recall COUNT being an aggregate function.jayshields wrote:Don't pull out a resultset full of 1s if you're going to count them, just pull out a resultset with the number of rows in the first and only row. Not sure if it'll be faster but it'll save memory.Code: Select all
SELECT COUNT(`field`) FROM `table` WHERE `field` = 'foo';
Oh I didn't know that. What is the difference between when I use the COUNT function with the GROUP BY clause and when I use the COUNT function without the GROUP BY clause?pytrin wrote:COUNT is a special kind of aggregate function, it can be used without a group by clause.