Creating a Postgis Template

$ createdb -E UTF8 -T template0 template_postgis

$ psql -d template_postgis -c "CREATE EXTENSION postgis;"
$ psql -d template_postgis -c "CREATE EXTENSION postgis_topology;"

$ psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;"
$ psql -d template_postgis -c "GRANT ALL ON geography_columns TO PUBLIC;"
$ psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC ...
more ...

Feature table with triggers

create table capaxy (gid serial primary key, x double precision, y double precision);
select addgeometrycolumn ('','capaxy','geom',-1,'POINT',2);

BEGIN TRANSACTION;

CREATE OR REPLACE FUNCTION tggFunction_updateEventos() RETURNS trigger AS
$$
  BEGIN
    IF ((NEW.x != OLD.x) OR (NEW.y != OLD.y)) THEN
      NEW.geom = ST_MAKEPOINT (NEW.x, NEW.y);
    ELSE ...
more ...

Hexgrids in Postgis

-- Function: makegrid_epsg3857(text, text, text, numeric)

-- DROP FUNCTION makegrid_epsg3857(text, text, text, numeric);

CREATE OR REPLACE FUNCTION makegrid_epsg3857(schemaname text, boundingbox text, gridtable text, halfwidth numeric)
  RETURNS text AS
$BODY$
    DECLARE
    tbl_cnt int;
    XMIN numeric;
    XMAX numeric;
    YMIN numeric;
    YMAX numeric;
    x_value numeric;
    y_value numeric;
    x_count integer;
    y_count integer;
    y_offset ...
more ...

Insert from an Union

INSERT INTO g_islas(geom, cisla, cprov, agrisla, cca)
SELECT multi(ST_Union(geom)), '01', '07', '0701', '04'
FROM g_munici
WHERE cine IN ('07024','07994');
more ...

Multipart to singlepart

CREATE TABLE land_single AS (SELECT generate_series(1, ST_NumGeometries(geom)) as gid, ST_GeometryN(geom, generate_series(1, ST_NumGeometries(geom))) as geom FROM ne_10m_land);
more ...

Split of a coordinate field

SELECT st_astext(st_geomfromtext('POINT(' || split_part(txt_coords, ' ', 1) || ' ' || split_part(txt_coords, ' ', 2) || ')', 4258)) FROM tablatxt;
more ...


Updating geo tables with temp tables

BEGIN;

CREATE TEMP TABLE temp_r_sp (seccion character varying(13), pj character varying(5)) ON COMMIT DROP;

INSERT INTO temp_r_sp
SELECT cme_cod, p.agrparjud
    FROM e_cme e, g_seccio07 s, g_parjud p
    WHERE s.geom && p.geom AND
          ST_CONTAINS(p.geom, ST_CENTROID(s.geom)) AND
          e.cme_cod = s.cseccion;

UPDATE e_cme SET ...
more ...