Given this table:
# select * from messages;
| id | verbosity |
|---|---|
| 1 | 20 |
| 2 | 20 |
| 3 | 20 |
| 4 | 30 |
| 5 | 100 |
(5 rows) I would like to select N messages for which sum of verbosity is lower than N. So if N = 70, the desired result will be messages with id 1, 2 and 3. It’s important the solution is database-independent. It should work at least on PostgreSQL and SQLite.
Something like:
SELECT * FROM messages GROUP BY id HAVING SUM(verbosity) < 70;
doesn’t sum all values from the verbosity column.
This assumes a unique, ascending
idlike you have in your example.In modern Postgres – or generally with modern standard SQL (but not in SQLite):
Simple CTE
Recursive CTE
Should be faster for big tables where you only retrieve a small set.
All standard SQL, except for
LIMIT.Strictly speaking, there is no such thing as "database-independent". There are various SQL-standards, but no RDBMS complies completely.
LIMITworks for PostgreSQL and SQLite (and some others). UseTOP 1for SQL Server,rownumfor Oracle. Here’s a comprehensive list on Wikipedia.The SQL:2008 standard would be:
… which PostgreSQL supports – but hardly any other RDBMS.
The pure alternative that works with more systems would be to wrap it in a subquery and
But that is slow and unwieldy.
db<>fiddle here
Old sqlfiddle