Postgresql – Insert into int8range from columns of another table

postgresqlpostgresql-9.4range-types

I have two tables in PostgreSQL:

Table indexces_grid:

+---------------+------------+
| Column Name   | Type       |
+---------------+------------+
| indexid       | bigint     |
| iprange       | int8range  |
+---------------+------------+

Table citydetails:

+---------------+-----------+
| Column Name   | Type      |
+---------------+-----------+
| ipfrom        | bigint    |
| ipto          | bigint    |
| cityname      | varchar   |
+---------------+-----------+

I want to insert the ipfrom and ipto into the single column iprange of the indexces_grid table.

Best Answer

It's so simple:

INSERT INTO indexces_grid ("Row2")
SELECT int8range(ipfrom, ipto, '[]')
  FROM citydetails;

The documentation linked above tells you all.

Note that one has to use the three-parameter form of the range constructor function (here int8range()) to include the upper bound, too. Using the two-parameter form, the upper bound would be non-inclusive.

I've created an SQLFiddle to show this at work.