40
Lecture 7 – Database and Lecture 7 – Database and SQL SQL Database? Database? A database is a collection of A database is a collection of associated or related data. associated or related data. Examples – LIS (landuse Examples – LIS (landuse information databse); Medical information databse); Medical office database; tax database. office database; tax database. Differences between database and Differences between database and file? file?

Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Embed Size (px)

Citation preview

Page 1: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Lecture 7 – Database and SQLLecture 7 – Database and SQL

Database?Database?

A database is a collection of associated or A database is a collection of associated or related data. related data.

Examples – LIS (landuse information Examples – LIS (landuse information databse); Medical office database; tax databse); Medical office database; tax database. database.

Differences between database and file?Differences between database and file?

Page 2: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Database ModelsDatabase Models

A conceptual way of thinking about data in a A conceptual way of thinking about data in a database is called a logical model.database is called a logical model.

Over the past 30 years or so, 3 different Over the past 30 years or so, 3 different logical database models have evolved:logical database models have evolved:

1.1. The hierarchical modelThe hierarchical model

2.2. The network modelThe network model

3.3. The relational modelThe relational model

Page 3: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

The relational ModelThe relational Model

Dr. Edgar F. Codd introduced the relational Dr. Edgar F. Codd introduced the relational model around 1970.model around 1970.

Idea: “If you ignore the way data files are Idea: “If you ignore the way data files are connected and arrange your data into connected and arrange your data into simple two-dimensional, unordered tables, simple two-dimensional, unordered tables, then you can develop an algebra for then you can develop an algebra for queries and focus on the data as data, not queries and focus on the data as data, not as a physical realization of a logical as a physical realization of a logical model”model”

Page 4: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

What is an ArcSDC Service?What is an ArcSDC Service?

An ArcSDE service conveys spatial data An ArcSDE service conveys spatial data between geographic information system between geographic information system applications and a database. The applications and a database. The database may be any one of the database may be any one of the supported RDBMSs:supported RDBMSs:

- OracleOracle

- SQL ServerSQL Server

- InformixInformix

Page 5: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

ApplicationsApplications

The applications that can connect to and The applications that can connect to and access spatial data from an access spatial data from an ArcSDE ArcSDE service include ArcInfo, ArcView GIS, Map service include ArcInfo, ArcView GIS, Map Objects, ArcIMS, and ArcSDE CAD clientObjects, ArcIMS, and ArcSDE CAD client, , as well as custom-built applications as well as custom-built applications created by either you or an ESRI business created by either you or an ESRI business partner.partner.

Page 6: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical
Page 7: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Properties of an ArcSDE serviceProperties of an ArcSDE service

The home directory – which is defined by The home directory – which is defined by the system variable, SDEHOME.the system variable, SDEHOME.

The ArcSDE server monitor – the giomgr The ArcSDE server monitor – the giomgr processprocess

The gsrvr process – dedicated to a single-The gsrvr process – dedicated to a single-user application connection.user application connection.

Page 8: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Properties of An ArcSDR service Properties of An ArcSDR service (Cont.)(Cont.)

The TCP/IP servce name and port The TCP/IP servce name and port number – giomgr listens for application number – giomgr listens for application connection requests on a dedicated connection requests on a dedicated TCP/IP service name and port numberTCP/IP service name and port number The databaseThe database The configuration files – ArcSDE service The configuration files – ArcSDE service can be configured to control the number of can be configured to control the number of application connections as well as the OS application connections as well as the OS resources each connection may obtain.resources each connection may obtain.

Page 9: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Geographic Features in a SQL Geographic Features in a SQL Database Database

Feature - abstraction of a real world phenomenaFeature - abstraction of a real world phenomena

A feature attribute - characteristic of a feature“A feature attribute - characteristic of a feature“

Thus, a geographic feature is a real world Thus, a geographic feature is a real world phenomena with a feature attribute that defines phenomena with a feature attribute that defines its dimension and location in space. its dimension and location in space.

In a SQL database, features are managed in In a SQL database, features are managed in tables, an instance of a feature corresponds to a tables, an instance of a feature corresponds to a row, and an attribute of a feature to a column. row, and an attribute of a feature to a column.

Page 10: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Data Access  Data Access 

Data access is built around the standard cursor Data access is built around the standard cursor model defined in the Structured Query Language model defined in the Structured Query Language (SQL). (SQL).

The data access model builds on the traditional The data access model builds on the traditional model by supporting spatial and raster model by supporting spatial and raster constraints in a query. constraints in a query.

A A database connectiondatabase connection is a connection to a source is a connection to a source of geographic data. It represents the ArcSDE of geographic data. It represents the ArcSDE server, which can respond to requests for server, which can respond to requests for geographic information. geographic information.

Page 11: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical
Page 12: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Standards for Spatial Data in a Standards for Spatial Data in a SQL database SQL database

ArcSDE is based on standards for managing spatial data in ArcSDE is based on standards for managing spatial data in a SQL database that have been defined by both a SQL database that have been defined by both international standards bodies, and industry international standards bodies, and industry organizations:organizations:OpenGIS Consortium - OpenGIS Consortium - Simple Features Specification for Simple Features Specification for SQLSQLISO19125-1, ISO19125-1, Geographic Information - Simple feature Geographic Information - Simple feature access - Part 1: Common architectureaccess - Part 1: Common architectureISO19125-2, ISO19125-2, Geographic Information - Simple feature Geographic Information - Simple feature access - Part 2: SQL optionaccess - Part 2: SQL optionISO 19107, ISO 19107, Geographic information ; Spatial schemaGeographic information ; Spatial schemaISO 13249-3, ISO 13249-3, Information technology — Database Information technology — Database languages — SQL Multimedia and Application languages — SQL Multimedia and Application Packages — Part 3: SpatialPackages — Part 3: Spatial

Page 13: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

SQL and AccessSQL and Access

SQL – SEQUEL (Structured English Query SQL – SEQUEL (Structured English Query Language) and was originally an IBM Language) and was originally an IBM product.product.

Access – readily available to windows user, Access – readily available to windows user, also provides a good platform on which to also provides a good platform on which to learn SQL. Second only to Oracle, Access learn SQL. Second only to Oracle, Access is the most widely used SQL product in is the most widely used SQL product in business and industry.business and industry.

Page 14: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Getting into SQL in AccessGetting into SQL in Access

Path:Path:

Queries -> Create query in Design view -> Queries -> Create query in Design view -> New -> New Query -> Design View -> New -> New Query -> Design View -> Close Show Table -> Click “SQL” buttonClose Show Table -> Click “SQL” button

Typing a simple SQL query:Typing a simple SQL query:

Select *Select *

From StudentFrom Student

Where class=4Where class=4

Page 15: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Running s SQL QueryRunning s SQL Query

You can save your query when you try to You can save your query when you try to close your query window, or through close your query window, or through File/Save menuFile/Save menu

Click to run the script

Page 16: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Editing a SQL QueryEditing a SQL Query

Page 17: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Viewing Table DesignViewing Table Design

Page 18: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Beginning SQL Commands in Beginning SQL Commands in AccessAccess

Basic statements in SQL –Basic statements in SQL –The Select StatementThe Select Statement

Selecting FieldsSelecting Fields

Using Order BYUsing Order BY

Using ASC or DESCUsing ASC or DESC

Ordering Within an OrderOrdering Within an Order

Selecting Rows (Tuples)Selecting Rows (Tuples)

The Where ClauseThe Where Clause

Using ANDUsing AND

Using ORUsing OR

Page 19: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Beginning StatementsBeginning Statements

SQL statements in Access must begin with SQL statements in Access must begin with one of the following commands:one of the following commands: SelectSelect

InsertInsert

DeleteDelete

UpdateUpdate

ProcedureProcedure

Select is the most commonly used commandSelect is the most commonly used command

Page 20: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

The SELECT StatementThe SELECT Statement

Select Syntax:Select Syntax:

SELECT fields FROM Tables;SELECT fields FROM Tables;

As in most versions of SQL, SQL commands As in most versions of SQL, SQL commands in Access have to be terminated by in Access have to be terminated by semicolon.semicolon.

The “*” means “all fields” of the table:The “*” means “all fields” of the table:Select *Select *

FROM Student;FROM Student;

Page 21: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Selecting FieldsSelecting Fields

Select one field:Select one field:SELECT field_name FROM table;SELECT field_name FROM table;

SELECT sname FROM Student;SELECT sname FROM Student;

Select More than one field:Select More than one field:Select sname, class FROM Student;Select sname, class FROM Student;

Using ORDER BY:Using ORDER BY:SELECT sname, classSELECT sname, class

FROM StudentFROM Student

ORDER BY class;ORDER BY class;

Page 22: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Using ASC or DESCUsing ASC or DESC

SELECT sname, classSELECT sname, class

FROM StudentFROM Student

ORDER BY class ASC;ORDER BY class ASC;

Ordering Within an Order:Ordering Within an Order:

SELECT sname, classSELECT sname, class

FROM StudentFROM Student

ORDER BY class DESC, sname;ORDER BY class DESC, sname;

Page 23: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

SELECTING Rows (Tuples)SELECTING Rows (Tuples)

The WHERE Clause can restrict the output The WHERE Clause can restrict the output of rows in the results set by adding a of rows in the results set by adding a WHERE clause.WHERE clause.

SELECT fields or attributes or columnsSELECT fields or attributes or columns

FROM TableFROM Table

WHERE criteria;WHERE criteria;

SELECT *SELECT *

FROM StudentFROM Student

WHERE class=4;WHERE class=4;

Page 24: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Comparisons OperatorsComparisons Operators

All that can be used in a WHERE clause are All that can be used in a WHERE clause are listed here:listed here:

>>

<><>

==

>=>=

<=<=

Page 25: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Logical OperatorsLogical Operators

To include multiple conditions in a WHERE To include multiple conditions in a WHERE clause, logical operators, AND and OR, clause, logical operators, AND and OR, and the BETWEEN operator may be used.and the BETWEEN operator may be used.

Using ANDUsing ANDSELECT *SELECT *

FROM StudentFROM Student

WHERE class = 5WHERE class = 5

AND major = ‘ACCT’;AND major = ‘ACCT’;

Page 26: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Using OR and BETWEENUsing OR and BETWEEN

SELECT *SELECT *

FROM StudentFROM Student

WHERE class = 4WHERE class = 4

OR major = ‘ACCT’;OR major = ‘ACCT’;

SELECT …SELECT …

FROMFROM

WHEREWHERE

BETWEEN value1 and value2BETWEEN value1 and value2

Question – could you write a SQL scripts to find all students of class 1, Question – could you write a SQL scripts to find all students of class 1, 2, and 3?2, and 3?

Page 27: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

The COUNT FunctionThe COUNT Function

Number of rows what will be obtained in a Number of rows what will be obtained in a result set without actually displaying all of result set without actually displaying all of the result set itself.the result set itself.

SELECT COUNT(*)SELECT COUNT(*)FROM Student;FROM Student;SELECT COUNT(class)SELECT COUNT(class)FROM Student;FROM Student;

Question – did you get same output from above examples? Question – did you get same output from above examples? Why?Why?

Page 28: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

NULL ValuesNULL Values

NULL values are used to designate missing NULL values are used to designate missing data in tables.data in tables.

SELECT sname, classSELECT sname, class

FROM StudentFROM Student

WHERE class IS NULL;WHERE class IS NULL;

Page 29: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Using AliasesUsing AliasesWe can enhance the output and readability of a We can enhance the output and readability of a

query by using column and table aliases.query by using column and table aliases.SELECT sname AS Student_name, major AS Student_major, class AS SELECT sname AS Student_name, major AS Student_major, class AS

Student_classStudent_class

FROM StudentFROM Student

Where class = 4;Where class = 4;

A Table alias is a temporary name for a table that A Table alias is a temporary name for a table that allows us to short-hand a table’s name when we allows us to short-hand a table’s name when we reference that table in a query.reference that table in a query.

SELECT s.snameSELECT s.sname

FROM Student sFROM Student s

WHERE s.class = 4WHERE s.class = 4

Page 30: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Table QualifiersTable Qualifiers

SELECT *SELECT *

FROM StudentFROM Student

WHERE student.class = 4WHERE student.class = 4

Page 31: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

A Convention for Writing SQL A Convention for Writing SQL StatementsStatements

Use Uppercase letters for keywordsUse Uppercase letters for keywords Align the keywords on separate lines.Align the keywords on separate lines. Access does not allow comments in the Access does not allow comments in the SQL windowSQL window Single quotes and double quotes have the Single quotes and double quotes have the same meaning.same meaning. Access allows blank lines in the SQL Access allows blank lines in the SQL window, but does not allow any characters window, but does not allow any characters after the semicolon.after the semicolon.

Page 32: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Creating and Populating TablesCreating and Populating Tables

Data Types in AccessData Types in Access

Opening a DatabaseOpening a Database- Creating a New Database to Create a TableCreating a New Database to Create a Table- Opening an Existing Database to Create a tableOpening an Existing Database to Create a table

Creating a tableCreating a table

Inserting Values into a tableInserting Values into a table

The Update CommandThe Update Command

The Alter Table CommandThe Alter Table Command

Page 33: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Data Types in AccessData Types in Access

Access supports 14 primary data types:Access supports 14 primary data types:

Text, Char, Integer, Real, Text, Char, Integer, Real,

Float, Decimal, Smallint, Tinyint, Float, Decimal, Smallint, Tinyint,

Money, Datetime, Binary, Bit, Money, Datetime, Binary, Bit,

Image, and UniqueIdentifier.Image, and UniqueIdentifier.

Page 34: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Internal/External namesInternal/External names

The synonyms are external names.The synonyms are external names.

Valid synonyms for the Text field are:Valid synonyms for the Text field are:

LONGTEXT, LONGCHAR, NOTE, NTEXT, LONGTEXT, LONGCHAR, NOTE, NTEXT, and MEMO.and MEMO.

Similar structures exist for other data types.Similar structures exist for other data types.

Page 35: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Opening a DatabaseOpening a DatabaseYou can create a new database from You can create a new database from

scratch, or open an existing one. (Try this scratch, or open an existing one. (Try this by yourself to see how.)by yourself to see how.)

To introduce new data into your database, To introduce new data into your database, you will need to create tables.you will need to create tables.

CREATE TABLE TablenameCREATE TABLE Tablename

(attribute_name type, attribute_name, type, ….);(attribute_name type, attribute_name, type, ….);

Example:Example:CREATE TABLE Employee (nameCREATE TABLE Employee (name VARCHAR(20),VARCHAR(20),

addressaddress VARCHAR(20),VARCHAR(20),

employee_number employee_number NUMBER,NUMBER,

salarysalary CURRENCY);CURRENCY);

Page 36: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Inserting Values into a TableInserting Values into a Table

Using INSERT INTO … VALUESUsing INSERT INTO … VALUESINSERT INTO NamesINSERT INTO Names

VALUES(‘Joe Smith’);VALUES(‘Joe Smith’);

Note – Names is the name of an existing tableNote – Names is the name of an existing tableINSERT INTO EmployeeINSERT INTO Employee

VALUES (‘Joe Smith’, ‘102 Hamilton Av.’, 101, 2500);VALUES (‘Joe Smith’, ‘102 Hamilton Av.’, 101, 2500);

Note – if an attribute is unknown, you need to use Note – if an attribute is unknown, you need to use “NULL” to identify“NULL” to identify

Values (‘Joe Smitch’, null, 101, null)Values (‘Joe Smitch’, null, 101, null)

Page 37: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Using INSERT INTO .. SELECTUsing INSERT INTO .. SELECT

This is useful for inserting multiple rows.This is useful for inserting multiple rows.

INSERT INTO target_table(field)INSERT INTO target_table(field)

““Select clause”;Select clause”;

Example:Example:INSERT INTO Names(name)INSERT INTO Names(name)

SELECT nameSELECT name

FROM Employee;FROM Employee;

Question: Can you add employees with salary > 2600?Question: Can you add employees with salary > 2600?

Page 38: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

The Update CommandThe Update Command

For example set all salaries in the table For example set all salaries in the table Emp2 to zero, you may do so with one Emp2 to zero, you may do so with one update command:update command:

UPDATE Emp2UPDATE Emp2

SET sal = 0;SET sal = 0;

UPDATE EmployeeUPDATE Employee

SET salary = 0SET salary = 0

WHERE employee_number = 101WHERE employee_number = 101

Page 39: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

The Alter Table CommandThe Alter Table Command

ALTER TABLE TablenameALTER TABLE Tablename

ADD column-name type;ADD column-name type;ALTER TABLE EmployeeALTER TABLE Employee

ADD balance CURRENCY;ADD balance CURRENCY;

Changing a Column’s Type in a tableChanging a Column’s Type in a tableALTER TABLE EMPLOYEEALTER TABLE EMPLOYEE

ALTER COLUMN balance NUMBER;ALTER COLUMN balance NUMBER;

Page 40: Lecture 7 – Database and SQL Database? A database is a collection of associated or related data. Examples – LIS (landuse information databse); Medical

Deleting a Column in a TableDeleting a Column in a Table

ALTER TABLE TablenameALTER TABLE TablenameDROP column-name;DROP column-name;

You can also delete rows from a table:You can also delete rows from a table:DELETE FROM TableDELETE FROM TableWHERE (condition);WHERE (condition);DELETE *DELETE *FROM EmployeeFROM EmployeeWHERE salary>100WHERE salary>100