Skip to content
Advertisement

SQL select elements where sum of field is less than N

Given that I’ve got a table with the following, very simple content:

I would like to select N messages, which sum of verbosity is lower than Y (for testing purposes let’s say it should be 70, then correct results will be messages with id 1,2,3). It’s really important to me, that solution should be database independent (it should work at least on Postgres and SQLite).

I was trying with something like:

However it doesn’t seem to work as expected, because it doesn’t actually sum all values from verbosity column.

I would be very grateful for any hints/help.

Advertisement

Answer

This assumes a unique, ascending id like 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. LIMIT works for PostgreSQL and SQLite (and some others). Use TOP 1 for SQL Server, rownum for 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

Advertisement