how to query for min or max inet/cidr with postgre

2019-07-12 20:15发布

问题:

Consider query:

select min(d) from temp;
select max(d) from temp;

Either one, I get an error like:

# select max(d) from temp;
ERROR:  function max(inet) does not exist
LINE 1: select max(d) from temp;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

So, I create a table called temp and populate it:

create table temp (d inet);
insert into temp (d) values ('1.1.10.2');
insert into temp (d) values ('1.1.10.10');
insert into temp (d) values ('1.1.10.20');
insert into temp (d) values ('1.1.10.100');

# select * from temp order by d;

     d      
------------
 1.1.10.2
 1.1.10.10
 1.1.10.20
 1.1.10.100
(4 rows)

So, I can use host() to convert to text, but that produces incorrect answer:

select min(host(d)) from temp;

That is because it is doing a text 'min' function, which is this ordering:

# select host(d) as r from temp order by r;
     r      
------------
 1.1.10.10
 1.1.10.100
 1.1.10.2
 1.1.10.20
(4 rows)

Is there a min() and max() function for ip types in postgres? There are ways to trick it (convert to int and compare, or do a order by with a limit). I am more interested in proper min() and max(). Thank you SO!

-g

回答1:

You can use existing functions network_smaller(inet, inet) and network_larger(inet, inet) to define your own aggregates:

create aggregate min (inet) (
    sfunc = network_smaller,
    stype = inet);

create aggregate max (inet) (
    sfunc = network_larger,
    stype = inet);

select min(d) min, max(d) max
from temp;

   min    |    max     
----------+------------
 1.1.10.2 | 1.1.10.100
(1 row)


回答2:

i checked again, pg still not support min(inet). i guess what you can do is make another column to mapping the inet like replace(r,'.','') and min() it.