ST_SquareGrid
What is ST_SquareGrid?
ST_SquareGrid is a set-returning PostGIS function (added in 3.1) that generates a square (fishnet) grid covering the bounding box of an input geometry. Each row is one cell, with integer (i, j) coordinates and its polygon.
ST_SquareGrid(float size, geometry bounds) → setof record(geom geometry, i int, j int)size is the cell edge length in the input geometry's CRS units. Cells are aligned to the origin of the SRID unless you manually offset with a different bounds.
When would you use ST_SquareGrid?
Use ST_SquareGrid for spatial binning and raster-style analysis where uniform rectangular cells are appropriate — typical uses include population counts per grid cell, kernel-density precomputation, or generating a regular sampling scheme:
1SELECT s.i, s.j, s.geom, SUM(p.population) AS pop
2FROM ST_SquareGrid(1000, ST_Transform(region_geom, 3857)) AS s
3JOIN parcels p ON ST_Intersects(s.geom, ST_Transform(p.geom, 3857))
4GROUP BY s.i, s.j, s.geom;Pair with a projected CRS so size is in metres. For isotropic neighbour analysis prefer ST_HexagonGrid; for single cells by known index use ST_Square.
FAQs
How do I keep the grid output manageable on large extents?
Filter bounds to your exact area of interest, not a continent-wide bbox. A 10 m grid over a country yields billions of cells. Materialize only where you need density.
What CRS should I use for ST_SquareGrid?
A projected CRS where size units are meaningful (usually metres). Lat/lon hands you cells that vary dramatically with latitude.
What is the difference between ST_SquareGrid and ST_HexagonGrid?
Cell shape. Squares are faster to compute and store, but have two distinct neighbour distances (edge and diagonal). Hexagons have uniform six-neighbour distances, preferred for spatial statistics and movement analysis.
How do I align the grid to a specific origin?
Translate the bounds so its lower-left corner falls on your desired origin before calling the function — the cell indexing is relative to the SRID origin by default.