ST_Square
What is ST_Square?
ST_Square is a PostGIS function (added in 3.1) that returns a single square polygon at the specified integer grid coordinate, matching the tiling produced by ST_SquareGrid.
ST_Square(float size, integer cell_i, integer cell_j, geometry origin = null) → geometrysize is the edge length in CRS units. (cell_i, cell_j) are the grid indices. origin (optional) anchors the grid; when omitted, cells align to the SRID origin.
When would you use ST_Square?
Use ST_Square to reconstruct a single grid cell from a stored (i, j) key. This is the standard compact-storage pattern for dashboards and tile services:
1SELECT i, j, count,
2 ST_Square(1000, i, j, ST_Transform(ST_MakePoint(0,0), 3857)) AS geom
3FROM cell_counts
4WHERE count > 0;Storing (i, j) + aggregate is typically 10–50x smaller than storing polygon geometry per row, and ST_Square lets you materialize the polygon only when needed for rendering or spatial filter.
FAQs
Does ST_Square produce the same geometry as ST_SquareGrid for matching (i, j)?
Yes, when size and origin match. That is the point of the pair: store (i, j), reconstruct geometry on demand.
What CRS should I pick?
Whatever puts size in meaningful units. For most real-world workflows that means a projected metre-based CRS such as UTM, a local plane, or EPSG:3857.
Can I produce non-aligned squares?
Yes — supply an origin geometry whose (x, y) anchor cell (0, 0). Omit to align to the SRID origin.
When would I pick ST_Square over ST_Hexagon?
Use squares for raster-aligned analysis, faster rendering, or when matching external grids (census blocks, satellite pixels). Use hexagons when uniform neighbour distances matter (movement, diffusion, clustering).