Professional Documents
Culture Documents
SBD Gabungan
SBD Gabungan
What is a query?
What is a Query ?
A query is a “question” posed to a database
Queries are expressed in a high-level declarative manner
• Algorithms needed to answer the query are not specified in the query
Examples:
Mouse click on a map symbol (e.g. road) may mean
• What is the name of road pointed to by mouse cursor ?
Typing a keyword in a search engine (e.g. google, yahoo) means
• Which documents on web contain given keywords?
SELECT S.name FROM Senator S WHERE S.gender = ‘F’ means
• Which senators are female?
What is a query language?
What is a query language?
A language to express interesting questions about data
A query language restricts the set of possible queries
Examples:
Natural language, e.g. English, can express almost all queries
Computer programming languages, e.g. Java,
• can express computable queries
• however algorithms to answer the query is needed
Structured Query Language(SQL)
• Can express common data intensive queries
• Not suitable for recursive queries
Graphical interfaces, e.g. web-search, mouse clicks on a map
• can express few different kinds of queries
An Example World Database
Purpose: Use an example database to learn query language SQL
Conceptual Model
3 Entities: Country, City, River
2 Relationships: capital-of, originates-in
Attributes listed in Figure 3.1
An Example Database - Logical Model
• 3 Relations
Country(Name, Cont, Pop, GDP, Life-Exp, Shape)
City(Name, Country, Pop,Capital, Shape)
River(Name, Origin, Length, Shape)
• Keys
•Primary keys are Country.Name, City.Name, River.Name
• Foreign keys are River.Origin, City.Country
•Data for 3 tables
•Shown on next slide
World database data tables
What is SQL?
SQL - General Information
is a standard query language for relational databases
It support logical data model concepts, such as relations, keys, ...
Supported by major brands, e.g. IBM DB2, Oracle, MS SQL Server, Sybase, ...
3 versions: SQL1 (1986), SQL2 (1992), SQL 3 (1999)
Can express common data intensive queries
SQL 1 and SQL 2 are not suitable for recursive queries
SQL and spatial data management
ESRI Arc/Info included a custom relational DBMS named Info
Other GIS software can interact with DBMS using SQL
• using open database connectivity (ODBC) or other protocols
In fact, many software use SQL to manage data in back-end DBMS
And a vast majority of SQL queries are generated by other software
Although we will be writing SQL queries manually!
Three Components of SQL?
Data Definition Language (DDL)
Creation and modification of relational schema
Schema objects include relations, indexes, etc.
Data Manipulation Language (DML)
Insert, delete, update rows in tables
Query data in tables
Data Control Language (DCL)
Concurrency control, transactions
Administrative tasks, e.g. set up database users, security permissions
Focus for now
A little bit of table creation (DDL) and population (DML)
Primarily Querying (DML)
Creating Tables in SQL
• Table definition
• “CREATE TABLE” statement
• Specifies table name, attribute names and data types
• Create a table with no rows.
• See an example at the bottom
• Related statements
• ALTER TABLE statement modifies table schema if needed
• DROP TABLE statement removes an empty table
Populating Tables in SQL
• Adding a row to an existing table
• “INSERT INTO” statement
• Specifies table name, attribute names and values
• Example:
INSERT INTO River(Name, Origin, Length) VALUES(‘Mississippi’, ‘USA’, 6000)
• Related statements
• SELECT statement with INTO clause can insert multiple rows in a table
• Bulk load, import commands also add multiple rows
• DELETE statement removes rows
•UPDATE statement can change values within selected rows
Querying populated Tables in SQL
• SELECT statement
• The commonly used statement to query data in one or more tables
•Returns a relation (table) as result
• Has many clauses
• Can refer to many operators and functions
• Allows nested queries which can be hard to understand
• Scope of our discussion
• Learn enough SQL to appreciate spatial extensions
•Observe example queries
• Read and write simple SELECT statement
• Understand frequently used clauses, e.g. SELECT, FROM, WHERE
• Understand a few operators and function
SELECT Statement- General Information
• Clauses
•SELECT specifies desired columns
•FROM specifies relevant tables
•WHERE specifies qualifying conditions for rows
•ORDER BY specifies sorting columns for results
•GROUP BY, HAVING specifies aggregation and statistics
•Operators and functions
•arithmetic operators, e.g. +, -, …
•comparison operators, e.g. =, <, >, BETWEEN, LIKE…
•logical operators, e.g. AND, OR, NOT, EXISTS,
•set operators, e.g. UNION, IN, ALL, ANY, …
•statistical functions, e.g. SUM, COUNT, ...
• many other operators on strings, date, currency, ...
SELECT Example 1.
• Simplest Query has SELECT and FROM clauses
• Query: List all the cities and the country they belong to.
Result →
SELECT Example 2.
• Commonly 3 clauses (SELECT, FROM, WHERE) are used
•Query: List the names of the capital cities in the CITY table.
SELECT *
FROM CITY
WHERE CAPITAL=‘Y ’
Result →
Query Example…Where clause
Query: List the attributes of countries in the Country relation
where the life-expectancy is less than seventy years.
SELECT Co.Name,Co.Life-Exp
FROM Country Co
WHERE Co.Life-Exp <70
Result →
Multi-table Query Examples
Query: List the capital cities and populations of countries
whose GDP exceeds one trillion dollars.
Note:Tables City and Country are joined by matching “City.Country =
Country.Name”. This simulates relational operator “join” discussed in 3.2
SELECT Ci.Name,Co.Pop
FROM City Ci,Country Co
WHERE Ci.Country =Co.Name
AND Co.GDP >1000.0
AND Ci.Capital=‘Y ’
Multi-table Query Example
Query: What is the name and population of the capital city in the
country where the St. Lawrence River originates?
Note: Three tables are joined together pair at a time. River.Origin is matched
with Country.Name and City.Country is matched with Country.Name. The
order of join is decided by query optimizer and does not affect the result.
Query Examples…Aggregate Staistics
Query: What is the average population of the noncapital cities listed in the
City table?
SELECT AVG(Ci.Pop)
FROM City Ci
WHERE Ci.Capital=‘N ’
Query: List the countries whose GDP is greater than that of Canada.
SELECT Co.Name
FROM Country Co
WHERE Co.GDP >ANY(SELECT Co1.GDP
FROM Country Co1
WHERE Co1.Name =‘Canada ’)
3.4 Extending SQL for Spatial Data
Motivation
SQL has simple atomic data-types, like integer, dates and string
Not convenient for spatial data and queries
• Spatial data (e.g. polygons) is complex
• Spatial operation: topological, euclidean, directional, metric
SQL 3 allows user defined data types and operations
Spatial data types and operations can be added to SQL3
Open Geodata Interchange Standard (OGIS)
Half a dozen spatial data types
Several spatial operations
Supported by major vendors, e.g. ESRI, Intergraph, Oracle, IBM,...
OGIS Spatial Data Model
Consists of base-class Geometry and four sub-classes:
Point, Curve, Surface and GeometryCollection
Note: Spatial operator Touch() is used in WHERE clause to join Country table
with itself. This query is an example of spatial self join operation.
Spatial Query with multiple tables
Query: For all the rivers listed in the River table, find the countries through
which they pass.
Note: Spatial operation “Cross” is used to join River and Country tables. This
query represents a spatial join operation.
Query: The St. Lawrence River can supply water to cities that are
within 300 km. List the cities that can use water from the St.
Lawrence.
SELECT Ci.Name
FROM City Ci, River R
WHERE Overlap(Ci.Shape, Buffer(R.Shape,300))=1
AND R.Name =‘St.Lawrence ’
Earlier version of OGIS did not provide spatial aggregate operation to support
GIS operations like reclassify.
Using Spatial Operation in Nested Queries
Query: For each river, identify the closest city.
Note: It shows a complex nested query with aggregate operations. Such queries can be written into
two expression, namely a view definition, and a query on the view. The inner query becomes a view
and outer query is runon the view. This is illustrated in the next slide.
Rewriting nested queries using Views
•Views are like tables
•Represent derived data or result of a query
•Can be used to simplify complex nested queries
•Example follows:
CREATE VIEW Neighbor AS
SELECT Co.Name, Count(Co1.Name)AS num neighbors
FROM Country Co,Country Co1
WHERE Touch(Co.Shape,Co1.Shape)
GROUP BY Co.Name
Exercise: List two ways you have used spatial data. Which
software did you use to manipulate spatial data?
What is a SDBMS ?
A SDBMS is a software module that
can work with an underlying DBMS
supports spatial data models, spatial abstract data types (ADTs)
and a query language from which these ADTs are callable
supports spatial indexing, efficient algorithms for processing
spatial operations, and domain specific rules for query
optimization
Example: Oracle Spatial data cartridge, ESRI SDE
can work with Oracle 8i DBMS
Has spatial data types (e.g. polygon), operations (e.g. overlap)
callable from SQL3 query language
Has spatial indices, e.g. R-trees
SDBMS Example
Consider a spatial dataset with:
County boundary (dashed white line)
Census block - name, area, population,
boundary (dark line)
Water bodies (dark polygons)
Satellite Imagery (gray scale pixels)
Fig 1.2
Modeling Spatial Data in Traditional DBMS
Figure 1.3
Spatial Data Types and Traditional Databases
Traditional relational DBMS
Support simple data types, e.g. number, strings, date
Modeling Spatial data types is tedious
Example: Figure 1.4 shows modeling of polygon using numbers
Three new tables: polygon, edge, points
• Note: Polygon is a polyline where last point and first point are same
A simple unit sqaure represented as 16 rows across 3 tables
Simple spatial operators, e.g. area(), require joining tables
Tedious and computationally inefficient
Fig 1.4
Evolution of DBMS technology
Fig 1.5
Spatial Data Types and Post-relational Databases
Post-relational DBMS
Support user defined abstract data types
Spatial data types (e.g. polygon) can be added
Choice of post-relational DBMS
Object oriented (OO) DBMS
Object relational (OR) DBMS
A spatial database is a collection of spatial data types, operators,
indices, processing strategies, etc. and can work with many post-
relational DBMS as well as programming languages like Java, Visual
Basic etc.
How is a SDBMS different from a GIS ?
GIS is a software to visualize and analyze spatial data
using spatial analysis functions such as
Search Thematic search, search by region, (re-)classification
Location analysis Buffer, corridor, overlay
Terrain analysis Slope/aspect, catchment, drainage network
Flow analysis Connectivity, shortest path
Distribution Change detection, proximity, nearest neighbor
Spatial analysis/Statistics Pattern, centrality, autocorrelation, indices of
similarity, topology: hole description
Measurements Distance, perimeter, shape, adjacency, direction
GIS uses SDBMS
to store, search, query, share large spatial data sets
How is a SDBMS different from a GIS ?
SDBMS focusses on
Efficient storage, querying, sharing of large spatial datasets
Provides simpler set based query operations
Example operations: search by region, overlay, nearest
neighbor, distance, adjacency, perimeter etc.
Uses spatial indices and query optimization to speedup queries
over large spatial datasets.
SDBMS may be used by applications other than GIS
Astronomy, Genomics, Multimedia information systems, ...
Will one use a GIS or a SDBM to answer the following:
How many neighboring countries does USA have?
Which country has highest number of neighbors?
Evolution of acronym “GIS”
Geographic Information Systems (1980s)
Geographic Information Science (1990s)
Geographic Information Services (2000s)
Fig 1.1
Three meanings of the acronym GIS
Geographic Information Services
Web-sites and service centers for casual users, e.g. travelers
Example: Service (e.g. AAA, mapquest) for route planning
Geographic Information Systems
Software for professional users, e.g. cartographers
Example: ESRI Arc/View software
Geographic Information Science
Concepts, frameworks, theories to formalize use and
development of geographic information systems and services
Example: design spatial data types and operations for querying
Exercise: Which meaning of the term GIS is closest to the focus of
the book titled “Spatial Databases: A Tour”?
Components of a SDBMS
Recall: a SDBMS is a software module that
can work with an underlying DBMS
supports spatial data models, spatial ADTs and a query
language from which these ADTs are callable
supports spatial indexing, algorithms for processing spatial
operations, and domain specific rules for query optimization
Components include
spatial data model, query language, query processing, file
organization and indices, query optimization, etc.
Figure 1.6 shows these components
We discuss each component briefly in chapter 1.6 and in more
detail in later chapters.
Three Layer Architecture Fig 1.6
1.6.1 Spatial Taxonomy, Data Models
Spatial Taxonomy:
multitude of descriptions available to organize space.
Topology models homeomorphic relationships, e.g. overlap
Euclidean space models distance and direction in a plane
Graphs models connectivity, Shortest-Path
Spatial data models
rules to identify identifiable objects and properties of space
Object model help manage identifiable things, e.g. mountains,
cities, land-parcels etc.
Field model help manage continuous and amorphous
phenomenon, e.g. wetlands, satellite imagery, snowfall etc.
More details in chapter 2.
1.6.2 Spatial Query Language
• Spatial query language
• Spatial data types, e.g. point, linestring, polygon, …
• Spatial operations, e.g. overlap, distance, nearest neighbor, …
• Callable from a query language (e.g. SQL3) of underlying DBMS
SELECT S.name
FROM Senator S
WHERE S.district.Area() > 300
• Standards
• SQL3 (a.k.a. SQL 1999) is a standard for query languages
• OGIS is a standard for spatial data types and operators
• Both standards enjoy wide support in industry
• More details in chapters 2 and 3
Multi-scan Query Example
• Spatial join example
SELECT S.name FROM Senator S, Business B
WHERE S.district.Area() > 300 AND Within(B.location, S.district)
• Non-Spatial Join example
SELECT S.name FROM Senator S, Business B
WHERE S.soc-sec = B.soc-sec AND S.gender = ‘Female’
Fig 1.7
1.6.3 Query Processing
• Efficient algorithms to answer spatial queries
• Common Strategy - filter and refine
• Filter Step:Query Region overlaps with MBRs of B,C and D
• Refine Step: Query Region overlaps with B and C
Fig 1.8
Query Processing of Join Queries
•Example - Determining pairs of intersecting rectangles
• (a):Two sets R and S of rectangles, (b): A rectangle with 2 opposite corners
marked, (c ): Rectangles sorted by smallest X coordinate value
• Plane sweep filter identifies 5 pairs out of 12 for refinement step
•Details of plane sweep algorithm on page 15
Fig 1.9
1.6.4 File Organization and Indices
• A difference between GIS and SDBMS assumptions
•GIS algorithms: dataset is loaded in main memory (Fig. 1.10(a))
•SDBMS: dataset is on secondary storage e.g disk (Fig. 1.10(b))
•SDBMS uses space filling curves and spatial indices
•to efficiently search disk resident large spatial datasets
Fig 1.10
Organizing spatial data with space filling curves
•Issue:
•Sorting is not naturally defined on spatial data
•Many efficient search methods are based on sorting datasets
•Space filling curves
•Impose an ordering on the locations in a multi-dimensional space
•Examples: row-order (Fig. 1.11(a), z-order (Fig 1.11(b))
• Allow use of traditional efficient search methods on spatial data
Fig 1.11
Spatial Indexing: Search Data-Structures
•Choice for spatial indexing:
•B-tree is a hierarchical collection of ranges of linear keys, e.g. numbers
•B-tree index is used for efficient search of traditional data
•B-tree can be used with space filling curve on spatial data
•R-tree provides better search performance yet!
•R-tree is a hierarchical collection of rectangles
•More details in chapter 4
Sub Type
Geometry SpatialReferenceSystem
Relationship
Line LinearRing
MultiPolygon MultiLineString
Spatial Types – OGC Simple
Features for SQL (*)
Operations OGC Simple Feature Types
OGC Simple Features for SQL1(*)
▪ The OGC SF (roughly AKA ISO 19125-1)
describes 2-D geometry with linear
interpolation between vertices. The simple
feature model consists of a root class
Geometry and its subclasses Point, Curve,
Surface, GeometryCollection. The class
Geometry collection has the subclasses
Multipoint, Multicurve, MultiSurface.
OGC Simple Features for SQL1 (*)
▪ The OGC does not include complexes, a third
dimension, non-linear curves, `networking or
topology (i.e. connectivity information).
▪ Because of it relative simplicity and its support in
both the commercial & open source community
SFSQL is widely used in DBMS and is
supported in many Web applications.
▪ It is expected that newer more sophisticated
standards such as ISO-19107 will gradually
replace OGC SF.
OGC Simple Features for SQL (*)
▪ Brief description
▪ A simple feature is defined to have both spatial
and non-spatial attributes. Spatial attributes are
geometry valued, and simple features are based
on 2D geometry with linear interpolation
between vertices. Each feature is stored as a
row in a database table. This course covers the
OGC: GEOMETRY type with subtypes such as
POINT, LINE, POLYLINE, POLYGON, and
collections of these.
OGC Spatial Relations
▪ Equals – same geometries
▪ Disjoint – geometries share common point
▪ Intersects – geometries intersect
▪ Touches – geometries intersect at common boundary
▪ Crosses – geometries overlap
▪ Within– geometry within
▪ Contains – geometry completely contains
▪ Overlaps – geometries of same dimension overlap
▪ Relate – intersection between interior, boundary or
exterior
Contains Relation
Does the base geometry (small circles) contain the comparison geometry
(big circles)?
Touches Relation
Does the base geometry (small circles) touch the comparison geometry
(big circles) ?
Latin languages
Anglo-Saxon
Minimum
Bounding
Rectangle
Study
Area
What can PostGIS do?
Many PostGIS functions available via SQL
Compliant with OGC1 Simple Features Specification
Coordinate Crosses
transformation Within
Identify Overlaps
Buffer Contains
Touches Area
Crosses Length
Within Point on surface
Overlaps Return geometry
Contains as SVG
What can PostGIS do?
PostGIS supports a geometry type which is
compliant with the OGC standard for Simple
Features.
▪ POINT( 50 100 )
▪ LINESTRING ( 10 10, 20 20 )
▪ POLYGON ( ( 0 0, 5 5, 5 0, 0 0 ) )
▪ MULTIPOINT ( ( 1 1 ), ( 0 0 ) )
▪ MULTILINESTRING ( … )
▪ MULTIPOLYGON ( … )
Spatial Database Features
Informix
PostGIS
MySQL
Oracle
DB2
Spatial Objects ✓ ✓ ✓ ✓ ✓
R-Tree Index ✓ ✓ ✓ ✓
Spatial Functions ✓ ✓ ✓ ✓
OpenGIS ✓ ✓ ✓ ✓
Coord Transform ✓ ✓ ✓ ✓
Spatial Aggregates ✓ ✓ ✓ ✓
HOW Spatial Databases Fit into
GIS
LAN
Internet
Editing
GIS
Loading Mapping
Database Web
Analysis Features Client
GIS Other
SRID=4326;MULTILINESTRING((125.934150.364070000000
1,-125.9335 50.36378))
Indexes:
"spatial_ref_sys_pkey" PRIMARY KEY, btree (srid)
geometry_columns
▪ postgis=# \d geometry_columns
Table "public.geometry_columns"
Column | Type | Modifiers
-------------------+------------------------+-----------
f_table_catalog | character varying(256) | not null
f_table_schema | character varying(256) | not null
f_table_name | character varying(256) | not null
f_geometry_column | character varying(256) | not null
coord_dimension | integer | not null
srid | integer | not null
type | character varying(30) | not null
Indexes:
"geometry_columns_pk" PRIMARY KEY, btree
(f_table_catalog, f_table_schema, f
_table_name, f_geometry_column)
Database Rules
Valid Invalid
(SELECT x, y, t
FROM Clouds
WHERE humidity >= 80)
INTERSECT
(SELECT x, y, t
FROM Region
WHERE temperature <= 32)
Temporal Example: roads, buildings,
and regions
F1
F1
Lets add an administrative region (outer red rectangle) and some houses
Example: roads, buildings, and regions
F2 F3
Time1 Time2
A
A
F1
F2 F3
B B
http://www.pragprog.com/titles/sdgis/gis-for-web-developers
References