2

I'm wondering if it's possible to find records that only appear after the first occurrence of a where clause. I'm currently using PostgreSQL for this example but something not PostgreSQL specific would be preferred.

If I had a table such as this for an example

drop table if exists dummy;
create table dummy (
   col_a   varchar(10),
   col_b   varchar(10),
   col_c   varchar(10),
   test    integer
);

insert into dummy values
('A', 'B', 'C', 1),
('B', 'C', 'A', 2),
('C', 'A', 'B', 3),
('D', 'E', 'F', 4);

If I run the bellow query I can get the data in a new order

select * from dummy
order by col_b;

returning

C | A | B | 3
A | B | C | 1
B | C | A | 2
D | E | F | 4

Is it possible to do something so that I can only return the rows occurring after a certain where clause, something like

select * from dummy
/* where row appears after results 'A', 'B', 'C', 1 */
order by col_b;

To get

B | C | A | 2
D | E | F | 4

UPDATE

The reason I am not using where col_b > ? is because it doesn't cater for duplicate values

It would work until I need to match on an additional column like this

select * from dummy
where col_b > 'B'
and col_c > 'C'
order by col_b;

In which case it will return the last row because both values are above the cutoff but it is not cutting off after the first occurrence of the specified row.

I'm trying to have a where clause that can identify the specific row being row

A | B | C | 1

In this case

0
4

it seems you are looking for something like this:

with cte as 
    (
    select *
        ,row_number() over(order by col_b) as rn
    from dummy
)
select * 
from cte
where rn > (select rn from cte where col_a = 'A' and col_b = 'B' and col_c = 'C' and test = 1 limit 1)
2
3

Easily.

WITH cte AS ( SELECT col_a, col_b, col_c, test, 
                     ROW_NUMBER() OVER (ORDER BY col_b) rn
              FROM dummy )
SELECT col_a, col_b, col_c, test
FROM cte
WHERE rn > ( SELECT rn
             FROM cte
             WHERE (col_a, col_b, col_c, test) = ('A', 'B', 'C', 1 ) )
ORDER BY rn;

fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.