0

How do I SELECT rows using a LIMIT but exclude rows from that LIMIT which have a value for the column disabled = true.

Disabled rows should also be returned in the result set but not increment LIMIT when they're identified.

For example: Given table Runners

id   runner   km_run   disabled
 1     mary      3.5       true
 2     anna      1.5      false
 3     john      6.5      false
 4     bill      1.5      false
 5     jess      6.2       true
 6     jack      2.5      false

How would I do something like:

SELECT * FROM runners LIMIT 4 so that it returns every row above?

I considered using a dynamic LIMIT like this:

SELECT * FROM runners LIMIT (4+sum(disabled::int)) but this counts every disabled entry in the table as opposed to the ones iterated over so far. It also produces this error:

aggregate functions are not allowed in LIMIT

The table runners is 100,000+ rows and 65 columns. What's a more efficient approach?

Setup Queries:

CREATE TABLE runners(
 id SERIAL,
 runner VARCHAR, 
 km_run DECIMAL,
 disabled BOOLEAN DEFAULT false,
 PRIMARY KEY (id)
);

INSERT INTO runners (runner, km_run, disabled)
VALUES ('mary', 3.5, true);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('anna', 1.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('john', 6.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('bill', 1.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('jess', 6.2, true);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('jack', 2.5, false);
Mathomatic
  • 899
  • 1
  • 13
  • 38

1 Answers1

1

First you must get the maximum id for the rows having disabled = false and then select at least up to that id:

select * from runners
where id <= (
  select coalesce(min(r.id), 4) 
  from runners r
  where (select count(*) from runners where id <= r.id and disabled = false) = 4
)

See the demo.
Results:

> id | runner | km_run | disabled
> -: | :----- | -----: | :-------
>  1 | mary   |    3.5 | t       
>  2 | anna   |    1.5 | f       
>  3 | john   |    6.5 | f       
>  4 | bill   |    1.5 | f       
>  5 | jess   |    6.2 | t       
>  6 | jack   |    2.5 | f       
forpas
  • 160,666
  • 10
  • 38
  • 76