SQL LIMIT vs. JDBC Statement setMaxRows. Which one is better?

后端 未结 5 1688
离开以前
离开以前 2021-02-08 20:13

I want to select the Top 10 records for a given query. So, I can use one of the following options:

  • Using the JDBC Statement.setMaxRows() method
  • Using LIMI
5条回答
  •  死守一世寂寞
    2021-02-08 20:20

    For most cases, you want to use the LIMIT clause, but at the end of the day both will achieve what you want. This answer is targeted at JDBC and PostgreSQL, but is applicable to other languages and databases that use a similar model.

    The JDBC documentation for Statement.setMaxRows says

    If the limit is exceeded, the excess rows are silently dropped.

    i.e. The database server may return more rows but the client will just ignore them. The PostgreSQL JDBC driver limits on both the client and server side. For the client side, have a look at the usage of maxRows in the AbstractJdbc2ResultSet. For the server side, have a look of maxRows in QueryExecutorImpl.

    Server side, the PostgreSQL LIMIT documentation says:

    The query optimizer takes LIMIT into account when generating a query plan

    So as long as the query is sensible, it will load only the data it needs to fulfill the query.

提交回复
热议问题