<!-- Converted by db4-upgrade version 1.1 -->
<chapter xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="using_postgis_query">
  <title>Spatial Queries</title>

	<para>The <emphasis>raison d'etre</emphasis> of spatial databases
	is to perform queries inside the database which would
	ordinarily require desktop GIS functionality. Using PostGIS effectively
	requires knowing what spatial functions are available,
    how to use them in queries, and ensuring that
	appropriate indexes are in place to provide good performance.
    </para>

    <section xml:id="eval_spatial_rel">
        <title>Determining Spatial Relationships</title>

        <para>Spatial relationships indicate how two geometries interact with one another.
        They are a fundamental capability for querying geometry.
        </para>

        <section xml:id="DE-9IM">
          <title>Dimensionally Extended 9-Intersection Model</title>

         <para>According to the <link xlink:href="http://www.opengeospatial.org/standards/sfs">OpenGIS Simple
          Features Implementation Specification for SQL</link>, "the basic
          approach to comparing two geometries is to make pair-wise tests of
          the intersections between the Interiors, Boundaries and Exteriors of
          the two geometries and to classify the relationship between the two
          geometries based on the entries in the resulting 'intersection'
          matrix."</para>

        <para>In the theory of point-set topology,
        the points in a geometry embedded in 2-dimensional space are categorized into three sets:
        </para>

          <glosslist>
            <glossentry>
              <glossterm>Boundary</glossterm>

              <glossdef>
                <para>The boundary of a geometry is the set of geometries of
                the next lower dimension. For <varname>POINT</varname>s, which
                have a dimension of 0, the boundary is the empty set. The
                boundary of a <varname>LINESTRING</varname> is the two
                endpoints. For <varname>POLYGON</varname>s, the boundary is
                the linework of the exterior and interior
                rings.</para>
              </glossdef>
            </glossentry>

            <glossentry>
              <glossterm>Interior</glossterm>

              <glossdef>
                <para>The interior of a geometry are those points of a
                geometry that are not in the boundary. For
                <varname>POINT</varname>s, the interior is the
                point itself. The interior of a
                <varname>LINESTRING</varname> is the set of points
                between the endpoints. For <varname>POLYGON</varname>s, the
                interior is the areal surface inside the polygon.</para>
              </glossdef>
            </glossentry>

            <glossentry>
              <glossterm>Exterior</glossterm>

              <glossdef>
                <para>The exterior of a geometry is the rest of the space
                in which the geometry is embedded;
                in other words, all points not in the interior or on the boundary of the geometry.
                It is a 2-dimensional non-closed surface.
                </para>
              </glossdef>
            </glossentry>
          </glosslist>

        <para>The <link xlink:href="http://en.wikipedia.org/wiki/DE-9IM">Dimensionally Extended 9-Intersection Model</link>
        (DE-9IM) describes the spatial relationship between two geometries
        by specifying the dimensions of the 9 intersections between the above sets for each geometry.
        The intersection dimensions can be formally represented
        in a 3x3 <emphasis role="bold">intersection matrix</emphasis>.
        </para>

        <para>For a geometry <emphasis>g</emphasis>
            the <emphasis>Interior</emphasis>, <emphasis>Boundary</emphasis>, and <emphasis>Exterior</emphasis>
            are denoted using the notation
          <emphasis>I(g)</emphasis>, <emphasis>B(g)</emphasis>, and
          <emphasis>E(g)</emphasis>.
          Also, <emphasis>dim(s)</emphasis> denotes the dimension of
          a set <emphasis>s</emphasis> with the domain of
          <literal>{0,1,2,F}</literal>:
        </para>

        <itemizedlist spacing="compact">
        <listitem>
            <para><literal>0</literal> =&gt; point</para>
        </listitem>

        <listitem>
            <para><literal>1</literal> =&gt; line</para>
        </listitem>

        <listitem>
            <para><literal>2</literal> =&gt; area</para>
        </listitem>

        <listitem>
            <para><literal>F</literal> =&gt; empty set</para>
        </listitem>

        </itemizedlist>

        <para>
          Using this notation, the intersection matrix
          for two geometries <emphasis>a</emphasis> and <emphasis>b</emphasis> is:</para>

          <informaltable tabstyle="styledtable">
            <tgroup align="center" cols="4">
              <thead>
                <row>
                  <entry/>
                  <entry><emphasis role="bold">Interior</emphasis></entry>
                  <entry><emphasis role="bold">Boundary</emphasis></entry>
                  <entry><emphasis role="bold">Exterior</emphasis></entry>
                </row>
              </thead>

              <tbody>
                <row>
                  <entry><emphasis role="bold">Interior</emphasis></entry>
                  <entry><emphasis>dim( I(a) ∩ I(b) )</emphasis></entry>
                  <entry><emphasis>dim( I(a) ∩ B(b) )</emphasis></entry>
                  <entry><emphasis>dim( I(a) ∩ E(b) )</emphasis></entry>
                </row>
                <row>
                  <entry><emphasis role="bold">Boundary</emphasis></entry>
                  <entry><emphasis>dim( B(a) ∩ I(b) )</emphasis></entry>
                  <entry><emphasis>dim( B(a) ∩ B(b) )</emphasis></entry>
                  <entry><emphasis>dim( B(a) ∩ E(b) )</emphasis></entry>
                </row>
                <row>
                  <entry><emphasis role="bold">Exterior</emphasis></entry>
                  <entry><emphasis>dim( E(a) ∩ I(b) )</emphasis></entry>
                  <entry><emphasis>dim( E(a) ∩ B(b) )</emphasis></entry>
                  <entry><emphasis>dim( E(a) ∩ E(b) )</emphasis></entry>
                </row>
              </tbody>

            </tgroup>
          </informaltable>

         <para>The following overlapping polygons provide a concrete example.
         <xref linkend="ST_Relate"/> computes the matrix
         <literal>212101212</literal>; it matches the overlap pattern
         <literal>T*T***T**</literal> used by <xref linkend="ST_Overlaps"/>.</para>

<programlisting language="sql">WITH example AS (
  SELECT
    'POLYGON ((140 140,140 122,135 105,126 100,118 99,110 94,100 86,97 73,102 59,98 49,87 38,70 30,55 29,40 30,28 38,20 50,14 66,10 84,6 100,4 119,4 143,6 166,10 180,18 191,28 195,40 190,55 189,67 186,86 179,112 165,124 158,133 148,140 140),(48 177,40 177,30 174,24 166,22 159,25 155,30 153,40 154,45 157,52 162,53 169,51 174,48 177))'::geometry AS a,
    'POLYGON ((75 63,79 50,87 38,95 31,108 25,124 22,140 18,154 11,166 6,176 10,184 21,188 35,190 58,190 82,193 104,190 121,185 139,178 154,166 163,154 171,139 172,124 171,112 165,96 152,92 142,92 126,86 116,79 110,75 104,72 94,73 86,75 76,75 63))'::geometry AS b
), relation AS (
  SELECT a, b, ST_Relate(a, b) AS matrix
  FROM example
)
SELECT matrix,
       ST_RelateMatch(matrix, 'T*T***T**') AS matches_overlap_pattern,
       ST_Overlaps(a, b) AS overlaps
FROM relation;</programlisting>
<screen xml:id="visual-de9im-overlapping-polygons" role="visual-primary visual-overlay text-primary">  matrix   | matches_overlap_pattern | overlaps
-----------+-------------------------+----------
 212101212 | t                       | t
(1 row)</screen>

         <para>The executable query and generated overlay above are the visual
         source for the relation. The query below renders the nine cells of the
         same kind of matrix as a 3-by-3 set of examples. The final
         exterior/exterior cell is clipped to a finite viewport, since the true
         exterior/exterior intersection is unbounded.</para>

<programlisting language="sql">WITH example AS (
  SELECT
    ST_MakeEnvelope(0, 0, 6, 4) AS a,
    ST_MakeEnvelope(3, -1, 8, 3) AS b,
    ST_MakeEnvelope(-1, -2, 9, 5) AS viewport
), parts AS (
  SELECT
    a,
    b,
    ST_Boundary(a) AS ba,
    ST_Boundary(b) AS bb,
    viewport
  FROM example
)
SELECT
  ST_Relate(a, b) AS matrix,
  ST_AsText(ST_Normalize(a)) AS input_a,
  ST_AsText(ST_Normalize(b)) AS input_b,
  ST_AsText(ST_Normalize(ST_Intersection(a, b))) AS "2 I(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Intersection(a, bb))) AS "1 I(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Difference(a, b))) AS "2 I(a) ∩ E(b)",
  ST_AsText(ST_Normalize(ST_Intersection(ba, b))) AS "1 B(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Intersection(ba, bb))) AS "0 B(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Collect(
      'LINESTRING(0 0,0 4,6 4,6 3)'::geometry,
      'LINESTRING(0 0,3 0)'::geometry
  ))) AS "1 B(a) ∩ E(b)",
  ST_AsText(ST_Normalize(ST_Difference(b, a))) AS "2 E(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Collect(
      'LINESTRING(3 -1,8 -1,8 3,6 3)'::geometry,
      'LINESTRING(3 -1,3 0)'::geometry
  ))) AS "1 E(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Difference(viewport, ST_Union(a, b))))
    AS "2 E(a) ∩ E(b) clipped"
FROM parts;</programlisting>
	<screen xml:id="visual-de9im-matrix-cells" role="visual-primary visual-separate-output visual-matrix-3x3 text-primary psql-expanded">-[ RECORD 1 ]----------+-----------------------------------------------------------------------------
matrix                 | 212101212
input_a                | POLYGON((0 0,0 4,6 4,6 0,0 0))
input_b                | POLYGON((3 -1,3 3,8 3,8 -1,3 -1))
2 I(a) ∩ I(b)          | POLYGON((3 0,3 3,6 3,6 0,3 0))
1 I(a) ∩ B(b)          | LINESTRING(3 0,3 3,6 3)
2 I(a) ∩ E(b)          | POLYGON((0 0,0 4,6 4,6 3,3 3,3 0,0 0))
1 B(a) ∩ I(b)          | LINESTRING(3 0,6 0,6 3)
0 B(a) ∩ B(b)          | MULTIPOINT((6 3),(3 0))
1 B(a) ∩ E(b)          | MULTILINESTRING((0 0,0 4,6 4,6 3),(0 0,3 0))
2 E(a) ∩ I(b)          | POLYGON((3 -1,3 0,6 0,6 3,8 3,8 -1,3 -1))
1 E(a) ∩ B(b)          | MULTILINESTRING((3 -1,8 -1,8 3,6 3),(3 -1,3 0))
2 E(a) ∩ E(b) clipped  | POLYGON((-1 -2,-1 5,9 5,9 -2,-1 -2),(0 0,3 0,3 -1,8 -1,8 3,6 3,6 4,0 4,0 0))</screen>

          <para>Reading from left to right and top to bottom, the intersection matrix is
          represented as the text string '<emphasis role="bold">212101212</emphasis>'.</para>

          <para>For more information, refer to:</para>

          <itemizedlist spacing="compact">
            <listitem>
              <para><link xlink:href="http://www.opengeospatial.org/standards/sfs">OpenGIS Simple
          Features Implementation Specification for SQL</link> (version 1.1, section 2.1.13.2)</para>
            </listitem>

            <listitem>
                <para><link xlink:href="https://en.wikipedia.org/wiki/DE-9IM">Wikipedia: Dimensionally
              Extended Nine-Intersection Model (DE-9IM)</link></para>
            </listitem>
            <listitem>
              <para><link xlink:href="http://docs.geotools.org/latest/userguide/library/jts/dim9.html">GeoTools: Point Set Theory and the DE-9IM Matrix</link></para>
            </listitem>
          </itemizedlist>

        </section>

        <section xml:id="named-spatial-rel">
          <title>Named Spatial Relationships</title>

        <para>To make it easy to determine common spatial relationships,
        the OGC SFS defines a set of <emphasis>named spatial relationship predicates</emphasis>.
        PostGIS provides these as the functions
            <xref linkend="ST_Contains"/>,
            <xref linkend="ST_Crosses"/>, <xref linkend="ST_Disjoint"/>, <xref linkend="ST_Equals"/>,
            <xref linkend="ST_Intersects"/>, <xref linkend="ST_Overlaps"/>,
            <xref linkend="ST_Touches"/>, <xref linkend="ST_Within"/>.
        It also defines the non-standard relationship predicates
            <xref linkend="ST_Covers"/>, <xref linkend="ST_CoveredBy"/>,
            and <xref linkend="ST_ContainsProperly"/>.
        </para>
        <para>Spatial predicates are usually used as conditions in SQL <code>WHERE</code> or <code>JOIN</code> clauses.
        The named spatial predicates automatically use a spatial index if one is available,
        so there is no need to use the bounding box operator <code>&amp;&amp;</code> as well.
        For example:
        </para>

		<programlisting>
SELECT city.name, state.name, city.geom
FROM city JOIN state ON ST_Intersects(city.geom, state.geom);
</programlisting>

        <para>For more details and illustrations, see the
        <link xlink:href="https://postgis.net/workshops/postgis-intro/spatial_relationships.html">PostGIS Workshop.</link></para>

        </section>

        <section xml:id="general-spatial-rel">
          <title>General Spatial Relationships</title>

        <para>In some cases the named spatial relationships are insufficient
        to provide a desired spatial filter condition. These requirements can
        be expressed by computing the full DE-9IM intersection matrix with
        <xref linkend="ST_Relate"/>.</para>

        <para>To test a particular spatial relationship,
          an <emphasis role="bold">intersection matrix pattern</emphasis> is used.
          This is the matrix representation augmented with the additional symbols
          <literal>{T,*}</literal>:
            </para>

          <itemizedlist spacing="compact">
            <listitem>
              <para><literal>T</literal> =&gt;
              intersection dimension is non-empty; i.e. is in <literal>{0,1,2}</literal></para>
            </listitem>

            <listitem>
              <para><literal>*</literal> =&gt; don't care</para>
            </listitem>
          </itemizedlist>

          <para>Using intersection matrix patterns, specific spatial
          relationships can be evaluated succinctly. The <xref linkend="ST_Relate"/>
          and <xref linkend="ST_RelateMatch"/> functions can both test these
          patterns.</para>

          <para>These road segments share a line segment. <xref linkend="ST_Crosses"/>
          does not find this relationship for linear features, because it only
          returns <varname>true</varname> when their interiors intersect at a
          point. The pattern <literal>1*1***1**</literal> tests for a
          one-dimensional intersection instead.</para>

          <programlisting>WITH roads AS (
  SELECT
    'LINESTRING(10 10,40 90,70 110,140 110,170 130,190 190)'::geometry AS "road A",
    'LINESTRING(10 190,50 130,90 110,130 110,160 70,180 10)'::geometry AS "road B"
), relation AS (
  SELECT "road A", "road B", ST_Relate("road A", "road B") AS matrix
  FROM roads
)
SELECT
  ST_Intersection("road A", "road B") AS overlap,
  matrix,
  ST_Crosses("road A", "road B") AS "ST_Crosses",
  ST_RelateMatch(matrix, '1*1***1**') AS "matches 1*1***1**"
FROM relation;</programlisting>
<screen xml:id="visual-relate-overlapping-roads" role="visual-primary visual-overlay text-primary">          overlap           |  matrix   | ST_Crosses | matches 1*1***1**
----------------------------+-----------+------------+-------------------
 LINESTRING(90 110,130 110) | 1F1FF0102 | f          | t
(1 row)</screen>

          <para>The next example finds a wharf which runs from the lake
          interior onto its shoreline, with one endpoint on the shoreline.
          The other wharves provide nearby counterexamples in the figure. The
          pattern <literal>102101FF2</literal> expresses the complete required
          relationship in one test.</para>

          <programlisting>WITH data AS (
  SELECT
    'POLYGON((-20 10,30 30,80 70,110 80,145 85,190 110,300 220,230 220,-20 220,-20 10))'::geometry AS lake,
    'MULTILINESTRING((120 180,145 85,110 80),(10 130,30 70),(90 140,110 80,94.81118881118876 75.83496503496498),(150 160,180 80))'::geometry AS wharves
), wharf AS (
  SELECT lake, (item).path[1] AS id, (item).geom
  FROM data CROSS JOIN LATERAL ST_Dump(wharves) AS item
), relation AS (
  SELECT id, geom, ST_Relate(lake, geom) AS matrix
  FROM wharf
)
SELECT
  id AS wharf,
  geom AS "matching wharf",
  matrix
FROM relation
WHERE ST_RelateMatch(matrix, '102101FF2')
ORDER BY id;</programlisting>
<screen xml:id="visual-relate-lake-wharves" role="visual-primary visual-overlay text-primary"> wharf |           matching wharf           |  matrix
-------+-----------------------------------+-----------
     1 | LINESTRING(120 180,145 85,110 80) | 102101FF2
(1 row)</screen>

        </section>
    </section>

	<section xml:id="using-query-indexes">
    <title>Using Spatial Indexes</title>

    <para>When constructing queries using spatial conditions,
    for best performance it is important to
    ensure that a spatial index is used, if one exists (see <xref linkend="build-indexes"/>).
    To do this, a spatial operator or index-aware function must be used
    in a <code>WHERE</code> or <code>ON</code> clause of the query.
    </para>
    <para>Spatial operators include
    the bounding box operators
    (of which the most commonly used is <xref linkend="geometry_overlaps"/>;
    see <xref linkend="operators-bbox"/> for the full list)
    and the distance operators used in nearest-neighbor queries
    (the most common being <xref linkend="geometry_distance_knn"/>;
    see <xref linkend="operators-distance"/> for the full list.)
    </para>
    <para>Index-aware functions automatically add a bounding box operator
    to the spatial condition.
    Index-aware functions include the named spatial relationship predicates
    <xref linkend="ST_Contains"/>,
    <xref linkend="ST_ContainsProperly"/>,
    <xref linkend="ST_CoveredBy"/>,
    <xref linkend="ST_Covers"/>,
    <xref linkend="ST_Crosses"/>,
    <xref linkend="ST_Intersects"/>,
    <xref linkend="ST_Overlaps"/>,
    <xref linkend="ST_Touches"/>,
    <xref linkend="ST_Within"/>,
    <xref linkend="ST_Within"/>,
    and <xref linkend="ST_3DIntersects"/>,
    and the distance predicates
    <xref linkend="ST_DWithin"/>,
    <xref linkend="ST_DFullyWithin"/>,
    <xref linkend="ST_3DDFullyWithin"/>,
    and <xref linkend="ST_3DDWithin"/>
    .)
    </para>
    <para>Functions such as
    <xref linkend="ST_Distance"/> do <emphasis>not</emphasis> use indexes to optimize their
    operation. For example, the following query would be quite slow on a
    large table:</para>

	  <programlisting><![CDATA[
SELECT geom
FROM geom_table
WHERE ST_Distance(geom, 'SRID=312;POINT(100000 200000)') < 100
]]></programlisting>

    <para>This query selects all the geometries in <code>geom_table</code> which are
    within 100 units of the point (100000, 200000). It will be slow because
    it is calculating the distance between each point in the table and the
    specified point, ie. one <varname>ST_Distance()</varname> calculation
    is computed for <emphasis role="bold">every</emphasis> row in the table.
    </para>
    <para>
    The number of rows processed can be reduced substantially by using the
	index-aware function <xref linkend="ST_DWithin"/>:</para>

	  <programlisting>SELECT geom
FROM geom_table
WHERE ST_DWithin(geom, 'SRID=312;POINT(100000 200000)', 100)</programlisting>

    <para>This query selects the same geometries, but it does it in a more
    efficient way.
    This is enabled by <varname>ST_DWithin()</varname> using the
    <varname>&amp;&amp;</varname> operator internally on an expanded bounding box
    of the query geometry.
    If there is a spatial index on <code>geom</code>, the query
    planner will recognize that it can use the index to reduce the number of
    rows scanned before calculating the distance.
    The spatial index allows retrieving only records with geometries
    whose bounding boxes overlap the expanded extent
    and hence which <emphasis>might</emphasis> be within the required distance.
    The actual distance is then computed to confirm whether to include the record in the result set.
    </para>

    <para>For more information and examples see the
        <link xlink:href="https://postgis.net/workshops/postgis-intro/indexing.html">PostGIS Workshop</link>.
    </para>

	</section>

	<section xml:id="examples_spatial_sql">
	  <title>Examples of Spatial SQL</title>

	  <para>The examples in this section make use of a table
	  of linear roads, and a table of polygonal municipality boundaries. The
	  definition of the <varname>bc_roads</varname> table is:</para>

	  <screen>Column    | Type              | Description
----------+-------------------+-------------------
gid       | integer           | Unique ID
name      | character varying | Road Name
geom      | geometry          | Location Geometry (Linestring)</screen>

	  <para>The definition of the <varname>bc_municipality</varname>
	  table is:</para>

	  <screen>Column   | Type              | Description
---------+-------------------+-------------------
gid      | integer           | Unique ID
code     | integer           | Unique ID
name     | character varying | City / Town Name
geom     | geometry          | Location Geometry (Polygon)</screen>

	  <qandaset>
		<qandaentry xml:id="qa_total_length_roads">
		  <question>
			<para>What is the total length of all roads, expressed in
			kilometers?</para>
		  </question>

		  <answer>
			<para>You can answer this question with a very simple piece of
			SQL:</para>

			<programlisting>SELECT sum(ST_Length(geom))/1000 AS km_roads FROM bc_roads;</programlisting>
<screen>
km_roads
------------------
70842.1243039643
</screen>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>How large is the city of Prince George, in hectares?</para>
		  </question>

		  <answer>
			<para>This query combines an attribute condition (on the
			municipality name) with a spatial calculation (of the
			polygon area):</para>

			<programlisting>SELECT
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
WHERE name = 'PRINCE GEORGE';
</programlisting>
<screen>
hectares
------------------
32657.9103824927
</screen>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>What is the largest municipality in the province, by
			area?</para>
		  </question>

		  <answer>
			<para>This query uses a spatial measurement as an ordering value.
            There are several ways of approaching this problem, but
			the most efficient is below:</para>

			<programlisting>SELECT
  name,
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
ORDER BY hectares DESC
LIMIT 1;</programlisting>
<screen>name           | hectares
---------------+-----------------
TUMBLER RIDGE  | 155020.02556131</screen>

			<para>Note that in order to answer this query we have to calculate
			the area of every polygon. If we were doing this a lot it would
			make sense to add an area column to the table that could
			be indexed for performance. By ordering the results in a
			descending direction, and them using the PostgreSQL "LIMIT"
			command we can easily select just the largest value without using an
			aggregate function like MAX().</para>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>What is the length of roads fully contained within each
			municipality?</para>
		  </question>

		  <answer>
			<para>This is an example of a "spatial join",
			which brings together data from two tables (with a join) using a
			spatial interaction ("contained") as the join condition
			(rather than the usual relational approach of joining on a common
			key):</para>

			<programlisting>SELECT
  m.name,
  sum(ST_Length(r.geom))/1000 as roads_km
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Contains(m.geom, r.geom)
GROUP BY m.name
ORDER BY roads_km;</programlisting>
<screen>name                        | roads_km
----------------------------+----------
SURREY                      | 1539.476
VANCOUVER                   | 1450.331
LANGLEY DISTRICT            |  833.793
BURNABY                     |  773.769
PRINCE GEORGE               |  694.376
...</screen>

			<para>This query takes a while, because every road in the table is
			summarized into the final result (about 250K roads for the
			example table). For smaller datasets (several thousand
			records on several hundred) the response can be very fast.</para>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>Create a new table with all the roads within the city of
			Prince George.</para>
		  </question>

		  <answer>
			<para>This is an example of an "overlay", which takes in two
			tables and outputs a new table that consists of spatially clipped
			or cut resultants. Unlike the "spatial join" demonstrated above,
			this query creates new geometries. An overlay is like a
			turbo-charged spatial join, and is useful for more exact analysis
			work:</para>

			<programlisting>CREATE TABLE pg_roads as
SELECT
  ST_Intersection(r.geom, m.geom) AS intersection_geom,
  ST_Length(r.geom) AS rd_orig_length,
  r.*
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Intersects(r.geom, m.geom)
WHERE
  m.name = 'PRINCE GEORGE';
</programlisting>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>What is the length in kilometers of "Douglas St" in
			Victoria?</para>
		  </question>

		  <answer>
			<programlisting>SELECT
  sum(ST_Length(r.geom))/1000 AS kilometers
FROM bc_roads r
JOIN bc_municipality m
  ON ST_Intersects(m.geom, r.geom
WHERE
  r.name = 'Douglas St'
  AND m.name = 'VICTORIA';</programlisting>
<screen>
kilometers
------------------
4.89151904172838
</screen>
		  </answer>
		</qandaentry>

		<qandaentry>
		  <question>
			<para>What is the largest municipality polygon that has a
			hole?</para>
		  </question>

		  <answer>
			<programlisting language="sql"><![CDATA[
SELECT gid, name, ST_Area(geom) AS area
FROM bc_municipality
WHERE ST_NRings(geom) > 1
ORDER BY area DESC LIMIT 1;
]]></programlisting>
<screen><![CDATA[gid  | name         | area
-----+--------------+------------------
12   | SPALLUMCHEEN | 257374619.430216
]]></screen>
		  </answer>
		</qandaentry>
	  </qandaset>

  </section>
</chapter>
