We have already learned how to export SHP from PostGIS. We'll use SHP as the output format again, this time to show how to export a subset of data using ogr2ogr and how to re-project it during the export:
ogr2ogr -f "ESRI Shapefile" ne_coastline_islands PG:"host=localhost port=5434 user=postgres dbname=mastering_postgis" -t_srs EPSG:3857 -where "scalerank=1" data_import.ne_coastline
The preceding command extracts the islands off the 110M Natural Earth Coastline dataset, transforms it to EPSG 3857 (aka 900913), and exports the data as a shapefile. It is worth noting that because the shapefile is a format that is made up of a few files, the files were exported to a directory named ne_coastline_islands, and the file names are actually named after a schema and table we exported from, in this case data_import.ne_coastline.*. If the output file name was specified as ne_coastline_islands.shp, ogr2ogr would not create a directory for us and the exported files named ne_coastline_islands.*.
Let's rewrite the preceding command a bit using the -select parameter, so we can see it in action:
ogr2ogr ne_coastline_with_select_param PG:"host=localhost port=5434 user=postgres dbname=mastering_postgis" -select "scalerank,featurecla" -t_srs EPSG:3857 -where "scalerank=1" data_import.ne_coastline
The result should be exactly the same in terms of exported data; we just got there using a bit of a different path, this time specifying the columns explicitly.
Similarly to pgsql2shp, if there is no geometry to output, ogr2ogr will only output a DBF when exporting to SHP :
ogr2ogr -f "ESRI Shapefile" ne_coastline_data_only_with_sql_param PG:"host=localhost port=5434 user=postgres dbname=mastering_postgis" -sql "SELECT gid, scalerank, featurecla FROM data_import.ne_coastline;" data_import.ne_coastline
This time, ogr2ogr has also created an output directory for us. The DBF file name is not that obvious initially, but it makes perfect sense: sql_statement. You have surely noticed the presence of the -sql parameter that was used to customize the output content.