Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check for each row in subquery in SQL?

I have a table PrivateIPAddress with the following data

id ipAddress ipAddressTo
1 10.0.0.0 10.255.255.255
2 172.16.0.0 172.31.255.255
3 192.168.0.0 192.168.255.255

I need to find if an IP address is external or internal. To find an IP address as internal, the IP address that I give as an input should fall within any of the higher and lower bounds given in the table PrivateIPAddress. ie., 10.70.10.1 falls within the higher and lower bounds (ipAddress and ipAddressTo) of first row in the table.

I tried different queries, but none of them worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT (INET_ATON('10.70.10.1') >= ANY (select inet_aton(ipAddress) from PrivateIPAddress) OR INET_ATON('10.70.10.1') <= ANY (select inet_aton(ipAddressTo) from PrivateIPAddress));

The above query will not check for each row seperately, which is why it is failing. The inet_aton function converts the IP address to an integer which helps me in checking if it is within an ip range.

Can anyone suggest a better alternative to get the required result ?

>Solution :

Try this:

select case count(*) 
when 1 then 'private address'
when 0 then 'public address'
end as 'type of address' 
from  PrivateIPAddress where inet_aton('172.16.3.1') between inet_aton(ipAddress) and inet_aton(ipAddressTo);
-- result: private address

select case count(*) 
when 1 then 'private address'
when 0 then 'public address'
end as 'type of address' 
from  PrivateIPAddress where inet_aton('162.16.3.1') between inet_aton(ipAddress) and inet_aton(ipAddressTo);
-- result: public address
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading