2

I've a table called ranges which looks like this-

create table ranges(low bigint, high bigint, id int);
insert into ranges values (10,20,100);
insert into ranges values (21,30,101);

I've another table which looks like this-

create table ip(ip bigint);
insert into ip values (12);

I want a query which will output the id from the ranges table if the ip from ip table is between low and high of ranges table.

For example, for the ip 12, I want the output to be -

12,100

since 12 is between the low 10 and high 20 from the ranges table. What is the most efficient way of doing this? the column ip doesn't exist in the ranges table so I can't do a straightforward join.

1 Answer 1

3

You can join a table using range.

SELECT
    ip.ip, ranges.id
FROM
    ip
JOIN ranges ON ip.ip BETWEEN ranges.low AND ranges.high
Sign up to request clarification or add additional context in comments.

2 Comments

Although it works, on RedShift, it is very slow. I am getting warning- Nested Loop Join in the query plan - review the join predicates to avoid Cartesian products
Right, the join like this is not recommended in large table. Alternatively, if there's a regular interval in ranges. You may round up your ip.ip to nearest interval base and do a JOIN.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.