I have a the following sql statement:
$sql = "select siteid, row_number() OVER (ORDER BY siteid) as rownum FROM nwsite WHERE rownum >= 4";
“rownum” works when i use the name outside of the query (e.g. in a foreach loop) but when it comes to using it as a WHERE clause it never works.
Any ideas?
Thanks
Because the where clause is evaluated before the window function row_number is computed, you can’t include that column in your where clause.
You can structure the query like this:
select siteid, rownum from (select siteid, row_number() OVER (ORDER BY siteid) as rownum FROM nwsite) nw WHERE rownum >= 4
In this case the inner query is computed in its entirety and then passed to the outer query where the rownum column can be acted upon.