Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>EDIT</strong> See second query below, it is much better than this first one.</p> <p>Assuming Postgres 9.0 or better, you have to make use of a window function to get a row_number onto each item. Then you divide the row_number of the particular article by items_per_page (and round) to get page number. The only efficiency improvement available is to at least not query the articles that come <em>after</em> the one in question. So you get something like this:</p> <pre><code>Select ceiling(rowNumber/items_per_page) from ( SELECT article_id , article_content , row_number() over (order by article_rating, article_id) as rowNumber FROM articles where article_rating &lt;= (select article_rating from articles where article_id = 'xxxx' ) ORDER BY article_rating, article_id ) x where article_id = 'xxxx' </code></pre> <p><strong>EDIT</strong> In response to question in comments. Yes, I just realized there is a much better way to do this. By running a count(*) instead we traverse only the index.</p> <pre><code>Select ceiling(count(*)/items_per_page) FROM articles where article_rating &lt; (select article_rating from articles where article_id = 'xxxx' ) or ( article_rating = (select article_rating from articles where article_id = 'xxxx' ) and article_id &lt;= 'xxxx') </code></pre> <p>Normally we do not like OR clauses in WHERE clauses because they can degrade performance, but this one should be pretty safe because each clause ought to be optimizable if article_rating is indexed.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload