Bug 35966

Summary: Koha should not strip limits from SQL queries
Product: Koha Reporter: Andrew Fuerste-Henry <andrew>
Component: ReportsAssignee: Bugs List <koha-bugs>
Status: NEW --- QA Contact: Testopia <testopia>
Severity: normal    
Priority: P5 - low CC: blawlor, magnus, nick, rcoert
Version: Main   
Hardware: All   
OS: All   
Change sponsored?: --- Patch complexity: ---
Documentation contact: Documentation submission:
Text to go in the release notes:
Version(s) released in:
Circulation function:

Description Andrew Fuerste-Henry 2024-01-31 19:33:38 UTC
Koha removes LIMIT from queries in some cases, which can cause incorrect results. For example, consider this report to give the 5 oldest items in the collection, sorted into callnumber order:
SELECT *
FROM (
SELECT itemnumber, cn_sort, dateaccessioned
FROM items
ORDER BY dateaccessioned
LIMIT 5
) foo
ORDER BY cn_sort

That query should get all the items, put them in dateaccessioned order, drop all but the first 5, and then put those 5 in cn_sort order.

But Koha processes that by dropping the LIMIT and then re-applying it at the end:
SELECT *
FROM (
SELECT itemnumber, cn_sort, dateaccessioned
FROM items
ORDER BY dateaccessioned
) foo
ORDER BY cn_sort
LIMIT 5

That makes the query get all the items, put them in dateaccessioned order, then put them in cn_sort order, then drop all but the first 5. It changes the query hugely. 

It only does this in queries without a WHERE, so that first query can be made to work by editing it to: 

SELECT *
FROM (
SELECT itemnumber, cn_sort, dateaccessioned
FROM items
ORDER BY dateaccessioned
LIMIT 5
) foo
WHERE 1=1
ORDER BY cn_sort