ORDER BY NULL in MySQL

It’s for performance; adding ORDER BY NULL after a GROUP BY clause will make your query faster. An explanation, from the manual: By default, MySQL sorts all GROUP BY col1, col2, … queries as if you specified ORDER BY col1, col2, … in the query as well. If you include an explicit ORDER BY clause … Read more

Postgres: left join with order by and limit 1

Use a dependent subquery with max() function in a join condition. Something like in this example: SELECT * FROM companies c LEFT JOIN relationship r ON c.company_id = r.company_id AND r.”begin” = ( SELECT max(“begin”) FROM relationship r1 WHERE c.company_id = r1.company_id ) INNER JOIN addresses a ON a.address_id = r.address_id demo: http://sqlfiddle.com/#!15/f80c6/2

MySQL indices and order

Index order matters when your query conditions only apply to PART of the index. Consider: SELECT * FROM table WHERE first_name=”john” AND last_name=”doe” SELECT * FROM table WHERE first_name=”john” SELECT * FROM table WHERE last_name=”doe” If your index is (first_name, last_name) queries 1 and 2 will use it, query #3 won’t. If your index is … Read more