The answer to your first question is simple. SQL result sets are unordered unless you use order by
. (Or, in MySQL rely on the deprecated ordering done by group by
.) The SQL engine can process the data however it likes. And produce the results however it likes. The resulting order is arbitrary.
Your first query cannot be written more "efficiently", but proper join
syntax is highly recommended:
select a.id
from (select 1 as id union select 2 as id union select 3 as id
) a join
(select 2 as id union select 3 as id union select 1 as id
) b
on a.id = b.id;
The second is more interesting. Let's look at it:
select a.id
from (select 1 as id union select 2 as id union select 3 as id) a,
(select 2 as id union select 3 as id union select 1 as id) b
order by a.id = b.id desc;
You are doing a cross join
between two lists of numbers -- using (horror of horrors) implicit join syntax instead of cross join
.
Your order by
now has the condition a.id = b.id desc
. Well, in MySQL, a.id = b.id
becomes a boolean, which takes on a value of 1
for true and 0
for false. So, this will order the Cartesian product, putting the matches at the top of the list. It does no filtering