OGR2OGR Usage – Deleting Table Content and Loading New Data from Shapefile

ogr2ogr

Is it possible to load a shapefile to a PostGIS database by replacing the content of the table with the new content of the shapefile WITHOUT DROPPING the table?

I want to do this using ogr2ogr.

In the past I have used shp2pgsql, which gives you the option of four flags (-drop|-append|-create|-prepare) but none of these options actually maintains the table and deletes the data.

Is there something like this in ogr2ogr?

Best Answer

From the GDAL/OGR PG documentation:

Configuration Options

There are a variety of Configuration Options which help control the behavior of this driver.

  • ...

  • OGR_TRUNCATE: (GDAL >= 1.11) If set to "YES", the content of the table will be first erased with the SQL TRUNCATE command before inserting the first feature. This is an alternative to using the -overwrite flag of ogr2ogr, that avoids views based on the table to be destroyed. Typical use case: ogr2ogr -append PG:dbname=foo abc.shp --config OGR_TRUNCATE YES.

If you are stuck with GDAL < 1.11 and are unable to upgrade, you could issue a truncate SQL command before the ogr2ogr command:

psql -h pghost -p 5432 -U pguser -d pgdbname -c "TRUNCATE TABLE sometable;"
ogr2ogr etc...
Related Question