In Oracle I can have an SQL string like this
select * from table where rownum <= ?
Then in an PreparedStatement I can set the rownum as a parameter.
How does it work with Postgres JDBC (Java) with the LIMIT clause? Doing the following won’e let me set a parameter:
select * from table limit ?
4
Answers
It is not possible use a
?
placeholder in aLIMIT
clause. If you absolutley needed to do this from SQL, one workaround might be to useROW_NUMBER()
with a subquery. In other words, change this:to this:
However, in practice, if you are using JPA, you could use the various JPA methods to programmatically limit the size of the result set.
Apparently you are using such an old version of the JDBC driver (version 7.x.x or lower), in which the LIMIT parameterization is not supported. This version was released about twenty years ago and is completely outdated. I recommend that you switch to using a new version of the driver as soon as possible.
In PostgreSQL, you can use
LIMIT
to limit the number of records retrieved.In the following code
You create a prepared statement and set the LIMIT parameter to get the first 10 records.
For more information, see the PostgreSQL documentation.
In PostgreSQL, unlike Oracle where
ROWNUM
can be parameterized in aPreparedStatement
, theLIMIT
clause in PostgreSQL does not accept a placeholder(?)
directly. TheLIMIT
clause expects an integer literal and doesn’t support parameterized values in the same way as typicalWHERE
conditions.However, you can still achieve the desired result by using a
PreparedStatement
and dynamically inserting theLIMIT
value into the SQL query. Dynamically build the query string with theLIMIT
value included.Here is code example of
Java
This expands on answer by @Andrey Smelik.
Using Postgres JDBC driver (access database using Java programming), you can use the SQL
LINIT
clause to limit the number of rows returned by the query.This also allows set the prepared statement’s (of JDBC API) parameter to specify the "limit". For example:
The above code prints five rows of
name
column value from the database tabletable
.