COUNT(*) gives more than 1 with LIMIT 1?

You're limiting the resultset of the aggregate function count(), which will always return 1 row. IE: It's limiting the output of the count(*) function, rather than LIMITing just FROM data WHERE datetime < '2015-09-23 00:00:00'.


  • Postgres reads all the rows FROM data WHERE datetime < '2015-09-23 00:00:00'
  • Postgres then count(*)s them
  • Postgres then LIMITs that count

I suspect you're wanting it to do this:

    SELECT * FROM data WHERE datetime < '2015-09-23 00:00:00' LIMIT 1

As this is basically an existence check, one could also do:

           (SELECT 1 FROM data WHERE datetime < '2015-09-23 00:00:00')

From the postgres manual (

If a limit count is given, no more than that many rows will be returned (but possibly less, if the query itself yields less rows).

Limit does not constrain how many rows your query will scan - it only affects how many rows will show up in your record set.