Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Order of Operations?

Tags:

mysql

Is there a definitive place to find order of operations for mySQL statements? Is the below order correct?

FROM clause WHERE clause GROUP BY clause HAVING clause SELECT clause ORDER BY clause

If this is the case, can I use a term defined in the SELECT clase (select first_name as "f_name") within the group by clause?

Thanks!

like image 773
Evan Avatar asked Oct 22 '10 21:10

Evan


People also ask

Does order matter in MySQL?

Whereas if the telephone book were organized by first name then by last name, you'd find all the Johns together, then within the Johns, all the 'S' last names would be grouped together. So the order of columns in a multi-column index definitely matters. One type of query may need a certain column order for the index.

What is the correct order of SQL?

Detailed Solution. The correct answer is Select, where, group by, having.

Does order of operations matter in SQL?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.

Can we use 2 ORDER BY in MySQL?

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query. After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary).


1 Answers

I assume you are interested in SELECT, according to the MySQL documentation the syntax is as follows

SELECT
[ALL | DISTINCT | DISTINCTROW ]
  [HIGH_PRIORITY]
  [STRAIGHT_JOIN]
  [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
  [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
  [ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
  [ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
  | INTO DUMPFILE 'file_name'
  | INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]

Yes, you can use columns defined with AS in the GROUP BY clause.

like image 169
Adam Byrtek Avatar answered Sep 21 '22 15:09

Adam Byrtek