GeoPackage Layers – How to Write Multiple Layers to One GeoPackage Using OGR2OGR

gdalgeopackageogr2ogrshell

I'm using ogr2ogr to write a SQL query from PostGIS to a GeoPackage in a linux shell.
Query by Query to many GPKG:

ogr2ogr -f "GPKG" point.gpkg PG:"host=localhost dbname=data user=user password=*******" -sql "select * from point-features"
ogr2ogr -f "GPKG" line.gpkg PG:"host=localhost dbname=data user=user password=*******" -sql "select * from line-features"
ogr2ogr -f "GPKG" polygon.gpkg PG:"host=localhost dbname=data user=user password=*******" -sql "select * from polygon-features"

I would like to write multiple layers from queries into one GeoPackage, but I cannot find a documentation to this.

Like:

ogr2ogr -f "GPKG" pointlinepolygon.gpkg pointlayer linelayer polygonlayer PG:"host=localhost dbname=data user=user password=*******" -sql "select * from pointlinepolygon-features"

Would be happy about support.

Best Answer

You have different SQL statements, so you can't do one single line.

You can do mutiple statements like this:

ogr2ogr -f "GPKG" your_gpkg.gpkg PG:"host=localhost dbname=etienne user=postgres password=foo" -nln points -sql "SELECT * FROM points"
ogr2ogr -f "GPKG" your_gpkg.gpkg PG:"host=localhost dbname=etienne user=postgres password=foo" -nln lines -update  -sql "SELECT * FROM lines"

This will give you 2 layers in the Geopackage:

ogrinfo your_gpkg.gpkg 
INFO: Open of `your_gpkg.gpkg'
      using driver `GPKG' successful.
1: points
2: lines

The -nln is for specifying the layer name. They need to be different. https://gdal.org/programs/ogr2ogr.html#cmdoption-ogr2ogr-nln

And -update is to open the layer in update mode. https://gdal.org/programs/ogr2ogr.html#cmdoption-ogr2ogr-update

Edited, I first used -append and it worked. But as suggested in comment, I have updated the answer to use -update which is designed for this.

Related Question