On Wed, Jan 17, 2018 at 3:30 PM, Melvin Davidson <melvin6925@xxxxxxxxx> wrote: .... > Just a suggestion. The first query is not really needed. > You can simply do: > second query (B): > > SELECT id > , ... > FROM events > WHERE id > MIN(ID) > AND id <= MAX(ID) > AND ... > > See https://www.postgresql.org/docs/9.6/static/functions-aggregate.html > MAX and MIN functions Are you sure? ( http://sqlfiddle.com/#!17/7805a/3 ) In fact your link, in the first paragraph, points to https://www.postgresql.org/docs/9.6/static/tutorial-agg.html which, near the end ( 2nd paragraph from the end, I think its called next to last in English, but not sure if penultimate is the correct word, like in Spanish ), states: "Thus, the WHERE clause must not contain aggregate functions; it makes no sense to try to use an aggregate to determine which rows will be inputs to the aggregates." Francisco Olarte.