The importance of ORDER BY in SQL query

This is what just happend yesterday during my work time.

I have two tables in my database, one is topic, another is user.

What I want to do is, I want to fetch a topic list with the user who created that topic.

 

Here is my original idea:

step 1, fetch the topic list

step 2, according to the topic list, fetch user object for each topic element

 

Then I was told this is N+1 query...

Okey, use table join to join the table and then fetch the TopicAndUser object.

 

I did,

SELECT * FROM topic INNER JOIN user ON topic.user_id = user.id;

ok, this works.

Next step, I wan to fetch the same object above, but with the specific category number. So I did,

SELECT * FROM topic INNER JOIN user ON topic.user_id = user.id WHERE category.id = 1;

ok, this also works.

So the last step, let's fetch the same object above with the specific category number and also I want specify the range of topic id, so I did,

SELECT * FROM topic INNER JOIN user ON topic.user_id = user.id WHERE category.id = 1  AND topic.id  > 5;

wait, something is wrong here.

It looks like the order of this result is ordered by user id.

But what I want is to order by topic id...

 

Okey, the thing is, when we join two tables together, we don't know what the order will be. Even when I succeed at the first step, I was just lucky.

So here is the importance of ORDER BY.

What we should do is:

SELECT * FROM topic INNER JOIN user ON topic.user_id = user.id WHERE category.id = 1  AND topic.id  > 5 ORDER BY topic.id;

 

ORDER BY, a good way to solve unexpected "wrong order" error.