I have the following SQL query , it seems to run ok , but i am concerned as my site grows it may not perform as expected ,I would like some feeback as to how effective and efficient this query really is:
select * from articles where category_id=XX AND city_id=XXX GROUP BY user_id ORDER BY created_date DESC LIMIT 10;
Basically what i am trying to achieve – is to get the newest articles by created_date limited to 10 , articles must only be selected if the following criteria are met :
- City ID must equal the given value
- Category ID must equal the given value
- Only one article per user must be returned
- Articles must be sorted by date and only the top 10 latest articles must be returned
You’ve got a
GROUP BYclause which only contains one column, but you are pulling all the columns there are without aggregating them. Do you realise that the values returned for the columns not specified inGROUP BYand not aggregated are not guaranteed?You are also referencing such a column in the
ORDER BYclause. Since the values of that column aren’t guaranteed, you have no guarantee what rows are going to be returned with subsequent invocations of this script even in the absence of changes to the underlying table.So, I would at least change the
ORDER BYclause to something like this:or this: