Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql subquery order

Does the order of the results inside a mysql subquery affect the order of the actual query? I tried it but did not came to a real result cause sometimes it seemed so and sometimes it doesn't.

eg:

SELECT name FROM people WHERE pid IN (SELECT mid FROM member ORDER BY mdate)

Is the "order by"-clause going to affect the order of the results in this case?

Thanks.

like image 580
Rico Ocepek Avatar asked Sep 08 '13 14:09

Rico Ocepek


People also ask

Can we use ORDER BY in subquery MySQL?

A subquery can contain many of the keywords or clauses that an ordinary SELECT can contain: DISTINCT , GROUP BY , ORDER BY , LIMIT , joins, index hints, UNION constructs, comments, functions, and so on. Beginning with MySQL 8.0. 19, TABLE and VALUES statements can be used in subqueries.

Can a sub query have order?

An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

Why is ORDER BY in a from subquery ignored?

A "table" (and subquery in the FROM clause too) is - according to the SQL standard - an unordered set of rows. Rows in a table (or in a subquery in the FROM clause) do not come in any specific order. That's why the optimizer can ignore the ORDER BY clause that you have specified.

Is subquery always executed first?

Answer: D. The sub-query always executes before the execution of the main query. Subqueries are completed first. The result of the subquery is used as input for the outer query.


1 Answers

No it cant and if you want to change the order as per your need then better use a JOIN

Something like this:-

select name 
from people p inner join member m on p.pid = m.mid
order by p.name
like image 157
Rahul Tripathi Avatar answered Nov 13 '22 11:11

Rahul Tripathi