laravel/framework — pull request #6295 by janhartigan (2014-11-01 22:01:46+00:00)
Title: Setting up order, limit, and offset for union queries

This is the follow-up to #4758. The goal is to allow ordering, limiting, and offsetting for union queries. I'm really only familiar with MySQL's application of this, but I did some research to see how this is done in all the different SQL flavors. It seems that MySQL is the deviant here, but [this commit](https://github.com/laravel/framework/commit/ea1d3c89311e763d6c78d17325d21f2ad4614c1c) from a year ago seems to aggressively put parentheses around all the things (and rightfully so).

The resources that I found regarding the other languages:

- SQL Server: http://technet.microsoft.com/en-us/library/ms173288(v=sql.110).aspx
- SQLite: http://stackoverflow.com/a/16913355/385950
- Postgres: http://stackoverflow.com/questions/4232626/posgresql-how-to-union-3-tables-sorted-by-date

All of these would seem to suggest that the normal order by syntax is (using the example from the unit test):

```sql
select * from "users" where "id" = ? union select * from "users" where "id" = ? order by "id" desc
```

In MySQL, of course, this would only order the union select, not the combined result of the two tables. So in MySQL, that would be:

```sql
(select * from `users` where `id` = ?) union (select * from `users` where `id` = ?) order by `id` desc
```

The four new unit tests reflect this syntax. Please let me know if one of these grammars is incorrect and I'll be sure to write some new tests.