How to use FETCH FIRST in Postgresql correctly?

I tried to figure out how to select only the first element of a SELECT query.

It seems a lot of people use LIMIT 1 to select only the first, but this does not seem like the best way to do this.

I read in SELECT in Postgresql docs and it seems that there is an option for the FETCH statement, but I can not find any examples on the Internet, can someone explain to me how to use it correctly?

+5
source share
1 answer

The following statements are equivalent:

SELECT * FROM foo LIMIT 10; 

and

 SELECT * FROM foo FETCH FIRST 10 ROWS ONLY; 

ROWS is interchangeable with ROW , making sampling just 1 a little more grammatically consistent.

FETCH FIRST X ROWS ONLY is part of the SQL standard, but to my memory, LIMIT is not. LIMIT is very popular and much more concise, therefore it is also supported by postgres.

Edited to add : two operators are syntactically different from each other. They generate exactly the same plans:

 =# explain select * from foo fetch first 10 row only; QUERY PLAN ------------------------------------------------------------- Limit (cost=0.00..0.22 rows=10 width=68) -> Seq Scan on foo (cost=0.00..18.50 rows=850 width=68) =# explain select * from foo limit 10; QUERY PLAN ------------------------------------------------------------- Limit (cost=0.00..0.22 rows=10 width=68) -> Seq Scan on foo (cost=0.00..18.50 rows=850 width=68) 
+8
source

All Articles