SQL212 Oracle SQL Manual
Post on 21-May-2015
301 Views
Preview:
DESCRIPTION
Transcript
Accelerated Computer Training for Working Professionals Factory 2010 Case
Orange Coast Database Associates Course (800)355-9855 or http://ocdatabases.itgo.com
Orange Coast
Database Associates
Specializing in Microsoft Office,
Access, SQL, and related technologies Classes custom designed for Working Professionals
http://www.dhdursoassociates.com
San Juan Capistrano, CA
(800)355-9855
SQL212 Introduction to SQL Using
Oracle
1
Bookstore SQL212 1
An accelerated introduction to SQL for non-programmers
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
Welcome to SQL212 –Accelerated Introduction to
SQL with Oracle
Bookstore SQL212 2
Accelerated Introduction to Oracle SQL
• Introduction (s)
• Facilities
• Course Packet (content may vary by class)
– Student questionnaire
– Collaterals (Price List, Flyers, etc.)
– PowerPoint handouts for all sessions (instructor slides may have some changes)
– Evaluation form
– Training certificate
• Website (Terms, Practice Tests, etc.)
2
Bookstore SQL212 3
SQL Curriculum
SQL200*
SQL200S*
SQL212
OracleSQL202
SQL Server
SQL201W
MySQL
* = included in
above courses
Bookstore SQL212 4
Accelerated Introduction to SQL
• Assumes no prior knowledge of SQL or Oracle products
• Quick pace for experienced computer users
• End-user, not programmer, oriented
• SQL212 is an extension to SQL/200
– Uses Oracle in class but is otherwise identical.
• SQL200s is first two modules of SQL200 - a “read only” version.
3
Bookstore SQL212 5
Accelerated Introduction to Oracle SQL
• Select– Basic– Filters– Joins– Subqueries– Unions– Grouping and
Summarization
SQL Covered (Day 1) 9:00AM – 4:00PM:
Bookstore SQL212 6
Accelerated Introduction to Oracle SQL
• Data Updates– Insert– Update– Delete
• Data structures– Create– Drop– Alter– Views– Indexes
SQL Covered (Day 2, 9:00AM – 12:00PM):
4
Bookstore SQL212 7
Accelerated Introduction to SQL
• Focus is on SQL language
• We will use Oracle SQL Developer in this
class
• Enterprise manager outside scope of this
class
Bookstore SQL212 8
Accelerated Introduction to SQL
• 3 Sessions• Lecture• Demo• Student “hands-on” • Many exercises are cumulative –
later examples build on queries created earlier
Course Format:
5
Bookstore SQL212 9
Accelerated Introduction to SQL
• Session 1 – Basic SQL• Session 2 – Multi-table
Retrieval• Session 3 – Modifying Data
Course Schedule (“1/2” day sessions):
Notes
Bookstore SQL212 10
6
Notes
Bookstore SQL212 11
Notes
Bookstore SQL212 12
11/25/2011
1
Bookstore SQL200 Module 1 1
SQL200
Based on SQL Clearly Explained by Jan Harrington
SQL Programming
Module 1 – Relational Database Background,
Basic Single Table Retrieval Operations
Bookstore SQL200 Module 1 2
SQL Programming
• Course focus is SQL language
• Widely used for:
– Database administration
– Enterprise application development
– Data driven web sites
• A foundation skill for eBusiness and almost all major business applications that use relational databases
11/25/2011
2
Bookstore SQL200 Module 1 3
SQL Programming
• A basic knowledge of query systems,
perhaps via MS Access, or some
programming knowledge, is desirable
• We will use “SQL View” almost
exclusively
Bookstore SQL200 Module 1 4
Relational Database Evolution
• Based on Codd‟s paper
• Early commercial efforts focused on Unix
• First mainframe implementation by IBM -
precursor to today‟s DB2
• First PC implementation in early 80‟s by
Oracle
11/25/2011
3
Bookstore SQL200 Module 1 5
Relational Database Basics
• Storage
• Databases
• Tables
• Rows
• Columns
• Indexes
• Views
• Cursors
• Application interfaces
Bookstore SQL200 Module 1 6
Relational Database Table
11/25/2011
4
Bookstore SQL200 Module 1 7
Constraints
• Database
– Domain
– Uniqueness
– Relationship
Cardinality
• 1 to 1
• 1 to N
• Other Business Rule
– Triggers
– Stored Procedures
Bookstore SQL200 Module 1 8
Relational Database with constraints
11/25/2011
5
Bookstore SQL200 Module 1 9
Database Management Systems
Positioning Chart
VLDB
Enterprise
Workgroup
Single user
Spreadsheet
# Users
Cost
Bookstore SQL200 Module 1 10
System Architecture
AccessMDB
File Server Architecture
Access
11/25/2011
6
Bookstore SQL200 Module 1 11
System Architecture
OracleDB
Visual Basic App
Client/Server Architecture
Access
SQL
Bookstore SQL200 Module 1 12
System Architecture
OracleDB
Browser
Web Architecture
WebServer
SQL
11/25/2011
7
Bookstore SQL200 Module 1 13
Approaching SQL
• Relatively simple
• Two main environments
– Interactive (This course)
– Embedded
• Static (Compiled)
• Dynamic
Bookstore SQL200 Module 1 14
SQL Standardization
ANSI standardization
– First standard in 1986
– SQL 89
– SQL 92
– SQL 99
• Various vendor extensions
– Microsoft/Sybase: T-SQL
– Oracle: PL/SQL
11/25/2011
8
Bookstore SQL200 Module 1 15
SQL Conformance
• Entry
• Intermediate
• Advanced
• Most are at least entry level
Bookstore SQL200 Module 1 16
SQL Statements
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Definition Language (DDL)
• Note: SQL 99 changes these to seven types
11/25/2011
9
Bookstore SQL200 Module 1 17
SQL DDL
• Data definition language (DDL)
– Create, alter, drop, etc.
– Frequently implemented via various CASE
tools: Visio, Embarcadero, ERWin, etc.
– But very useful for database administration
Bookstore SQL200 Module 1 18
SQL DCL
• Data Control Language (DDL)
– Grant
– Revoke
– Constraints
11/25/2011
10
Bookstore SQL200 Module 1 19
SQL DML
• Data Manipulation Language (DML)
– Select
– Insert
– Update
– Delete
Bookstore SQL200 Module 1 20
SQL Statement Processing
Parse
Validate
Optimize
Access Plan
Execute
11/25/2011
11
Bookstore SQL200 Module 1 21
Bookstore Sample Database
• Before we continue (note: instructor may have already done this)…
• Load the sample database if you haven‟t already– Use Access import table feature, or
– Run SQL script, or
– Use Access upsizing wizard
Bookstore SQL200 Module 1 22
Conventions
• In Access character strings are normally
surrounded by double quotes
– “Jones”
• In an enterprise database such as Oracle or SQL
Sever, then single quotes
– „Jones‟
• Be sensitive to the environment of your class in
copying scripts from the PowerPoint slides!
11/25/2011
12
Bookstore SQL200 Module 1 23
SELECT
Basic Syntax (Projection):
Select <column-list> or <*>
From <table-list>
Bookstore SQL200 Module 1 24
SELECT
Basic Example (Projection):
select
customer_last_name,
customer_street
from customers
11/25/2011
13
Bookstore SQL200 Module 1 25
MS Access SQL Query
Bookstore SQL200 Module 1 26
11/25/2011
14
Bookstore SQL200 Module 1 27
SQL Server Query
Bookstore SQL200 Module 1 28
SELECT with Where Clause
Example (Restriction plus Projection):
Select <column-list>
From <table-list>
Where <selection-criteria>;
11/25/2011
15
Bookstore SQL200 Module 1 29
SELECT with Where
Basic Example (Restriction plus
Projection):
select customer_last_name,
customer_street
from customers
where customer_last_name =
‘Jones’
Bookstore SQL200 Module 1 30
Select with Where
11/25/2011
16
Bookstore SQL200 Module 1 31
On Your Own
• Find books written by Mark Twain
• Show title, publisher, year
Bookstore SQL200 Module 1 32
Complex Predicates
Follow normal boolean logic
Select customer_last_name,
customer_street
From customers
Where (customer_last_name =
‘Jones’ or customer_last_name =
‘Smith’)and customer_state=‘NY’
11/25/2011
17
Bookstore SQL200 Module 1 33
Select with Complex Where
Bookstore SQL200 Module 1 34
Complex Where Result
11/25/2011
18
Bookstore SQL200 Module 1 35
Special Operators
• Can be used in where clause
• LIKE
• IN
• BETWEEN
• IS NULL
Bookstore SQL200 Module 1 36
Like (“Wild Card Matches”)
• ANSI
• Where
customer_last_name
like “Jo%”
• Like “Jo_”
• Access
• Where
customer_last_name
like “Jo*”
• Like “Jo?”
11/25/2011
19
Bookstore SQL200 Module 1 37
IN
Select *
From customers
Where customer_last_name in
(‘Rizzo’, ‘Jones’, ‘Garcia’)
The list in parentheses can be replaced by a
subquery. We will study this later.
Bookstore SQL200 Module 1 38
SQL Where Clause with IN
11/25/2011
20
Bookstore SQL200 Module 1 39
IS NULL
Select *
From customers
Where customer_street IS NULL
SQL uses three valued logic. Must use IS NULL
to test for unknowns. A null is NOT the same as
blank or empty.
Bookstore SQL200 Module 1 40
On Your Own
• Find all customers with an address not equal to 4592 Maple Lane
• Was Peter Johnson selected?
• Why or why not?
11/25/2011
21
Bookstore SQL200 Module 1 41
BETWEEN
Select *
From orders
Where order_date BETWEEN
‘1-jan-99’ and ‘31-dec-99’
Note: date formats vary from product to product.
Bookstore SQL200 Module 1 42
Where with Between
11/25/2011
22
Bookstore SQL200 Module 1 43
Removing Duplicates
Select DISTINCT
customer_city
From customers
List once each city in which there are
customers
Removes duplicate rows from result set
Bookstore SQL200 Module 1 44
Removing Duplicates
11/25/2011
23
Bookstore SQL200 Module 1 45
Sorting – ORDER BY
DESC will sort in descending order
Basic syntax:
Select <column list>
From <table list>
Where <selection criteria>
Order by <column list> [DESC]
Bookstore SQL200 Module 1 46
Sorting – ORDER BY
Select *
From customers
Order by customer_state,
customer_city
Example:
List all records sorted by state, city
11/25/2011
24
Bookstore SQL200 Module 1 47
Sorting Results with Order By
Bookstore SQL200 Module 1 48
SQL Exercises
• List all books whose publisher name begins with “H” or “T”; sort by title [hint: use LIKE]
• List all customers whose last name ends with “S”; sort by state, city, last name
• Find the order numbers of orders with order dates in 1999; sort by order #. [Hint: use BETWEEN]
• Find the order numbers and order dates of all orders with a “2” in column 2 of the credit card #; sort by order date descending
[end module]
1
Bookstore2 SQL212 Module 2 1
SQL212
SQL Programming
Workshop 2 – Joins, Subqueries, Unions,
Calculations and Grouping
Bookstore2 SQL212 Module 2 2
SQL212 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2001-2009. All rights reserved.
2
Bookstore2 SQL212 Module 2 3
SQL212
SQL Programming
Part 1 – Joins, Subqueries
Bookstore2 SQL212 Module 2 4
Relational Database with constraints (from text)
3
Bookstore2 SQL212 Module 2 5
Warning!
• Some slides may show queries using a
table called…
Order_filled
• The current database uses a better name…
Orders
Construct your queries with this
latter table name
Bookstore2 SQL212 Module 2 6
Joins
• Inner
• Outer
– Left
– Right
– Full
• Cross
• Self
• Theta
• We will cover the most important; others as time and interest permit
4
Bookstore2 SQL212 Module 2 7
Inner Join
• Pairs each row from first table with
corresponding row from second table over
the “join column”
• The result set only contains rows where
there is a match over the join column in
both tables
• Equi-join is the common inner join
Bookstore2 SQL212 Module 2 8
Inner Join
Older Syntax:
Select <column-list>
From <tablelist>
Where <predicate>
Still very commonly used
5
Inner Join Examples
• Show customers and their orders
• Join the customers table to the orders table
where the customer number in each table
matches
Bookstore2 SQL212 Module 2 9
Bookstore2 SQL212 Module 2 10
Inner Join
Example using older syntax:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers, orders
Where customers.customer_numb =
orders.customer_numb
6
Bookstore2 SQL212 Module 2 11
Inner Join with Result
Bookstore2 SQL212 Module 2 12
Inner Join (New Syntax)
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Inner join <table2>
On <join condition>
7
Bookstore2 SQL212 Module 2 13
Inner Join
Basic Example:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers
inner join orders
on customers.customer_numb =
orders.customer_numb
Bookstore2 SQL212 Module 2 14
Inner Join with Result
8
Bookstore2 SQL212 Module 2 15
Inner Join over Multiple columns
• Note that that the join condition can apply
to multiple columns if desired
• Used with composite keys
Bookstore2 SQL212 Module 2 16
Inner Join Result in MS Access
9
Bookstore2 SQL212 Module 2 17
Inner Join
• In the last example…
– What was the cardinality of the relationship
between customers and orders?
– Which table was the parent?
– What was it‟s primary key?
– In which table did we employ a foreign key
and what was it?
Bookstore2 SQL212 Module 2 18
Cross Join
• What happens when you omit a join
expression?
• Get the cartesian product of the tables – all
possible combinations of the two tables
• For large tables this will run a long time!
10
Dual
• Sometimes we want to generate an
expression without actually referring to a
real table.
• A trivial example would show the date.
• Oracle has a 1 row, 1 column built in table
called Dual to handle this.
• Ex: select sysdate from dual;
Bookstore2 SQL212 Module 2 19
Bookstore2 SQL212 Module 2 20
Cross Join Result Set in MS Access
11
Bookstore2 SQL212 Module 2 21
Additional SQL92 Syntax
• Table1 natural join table2 – automatically
uses columns with same name
• Table1 natural join table2 using(<column-
list>)
• Not yet widely available in commercial
implementations
Natural Join
Bookstore2 SQL212 Module 2 22
12
Bookstore2 SQL212 Module 2 23
Joining More than Two Tables
• Can join several tables in one select
• Try to limit to three or four
• Join order can be important for performance (although optimizers will usually handle this for you)
• Use parentheses to force order of evaluation (also vendor extensions, often called “hints”)
Bookstore2 SQL212 Module 2 24
Joining More than Two Tables
• Add orderlines detail to previous queries
SELECT customer_first_name, customer_street,
orders.order_numb, orders.order_date,
orderlines.isbn, orderlines.quantity
FROM customers
INNER JOIN orders ON
customers.customer_numb=orders.customer_numb
INNER JOIN orderlines
on orders.order_numb = orderlines.order_numb
13
Bookstore2 SQL212 Module 2 25
Multi-table Join with Results
Bookstore2 SQL212 Module 2 26
MS Access Multi-table Join Result Set
14
Own Your Own
• Add the book title to the previous query
Bookstore2 SQL212 Module 2 27
Bookstore2 SQL212 Module 2 28
Sample Database
• Before we continue (Access classes
only)…
• Create a new employees table
15
Bookstore2 SQL212 Module 2 29
Correlation Names (Table Aliases)
• Can abbreviate references to tables
• For example:
Select e.name, j.payrange
From employees as e
Inner join job_information as j
On e.jobcode = j.jobcode;
Bookstore2 SQL212 Module 2 30
Self Joins
• Implements a recursive relationship
• Important in various applications
– Parts lists/assemblies
– HR
– Etc.
– Table joined to itself using correlation names
16
Bookstore2 SQL212 Module 2 31
Self Joins
SELECT e.*, m.name
FROM employees AS e, employees
AS m
WHERE e.managerid =
m.employeeid;
Bookstore2 SQL212 Module 2 32
17
Bookstore2 SQL212 Module 2 33
Outer Joins
• Left – selects all rows from the left or first table,
even if no match exists in the other table
– Widely used in commercial practice
– Especially useful for reporting
– Can be slower and interfere with optimizer
• Right – same idea but all rows from right table
• Full – all rows form both tables
Bookstore2 SQL212 Module 2 34
Left Outer Join
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Left [outer] join <table2>
On <join condition>
18
Outer Join Example
• Show all customers and their orders.
• Include customers with no orders as well.
Bookstore2 SQL212 Module 2 35
Bookstore2 SQL212 Module 2 36
Left-Join
Basic Example:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers as c
left join orders as o
on c.customer_numb =
o.customer_numb
19
Bookstore2 SQL212 Module 2 37
Bookstore2 SQL212 Module 2 38
Left Join with Results
20
Bookstore2 SQL212 Module 2 39
SQL200
SQL Programming
Part 2– Subqueries, Unions
Bookstore2 SQL212 Module 2 40
Subqueries
• One select statement embedded in another.
• Can be paced in select list, from clause or
where clause.
– We will study the latter in this class
• Can be nested multiple levels deep
• Two types:
– Uncorrelated – executes inner query then outer
– Correlated – executes inner query once for each outer
query row
21
Subquery Example
• Show all the orderline information for
orders places in 1999
• Note that orderlines table does not have
order date. Thus must filter on a different
table (orders).
Bookstore2 SQL212 Module 2 41
Bookstore2 SQL212 Module 2 42
Uncorrelated Subquery
select isbn, quantity
from orderlines ol
where ol.order_numb in
(select o.order_numb from
orders o where order_date
between „1-JAN-99‟ and ‟31-
DEC-99‟)
22
Bookstore2 SQL212 Module 2 43
Uncorrelated Subquery with Results
Bookstore2 SQL212 Module 2 44
Negative Subquery
• A type of subquery that matches “not
found” conditions
23
Bookstore2 SQL212 Module 2 45
Negative Subquery
select isbn, quantity
from orderlines ol
where ol.order_numb not in
(select o.order_numb from
orders o where order_date
between „1-JAN-99‟ and 31-
DEC-99‟)
Bookstore2 SQL212 Module 2 46
Negative Subquery with Results
24
Bookstore2 SQL212 Module 2 47
Correlated Subquery with Exists
• Inner subquery executed once for each outer row
• Exists will return true or false depending on
whether the result will have any rows or not
• Can be a quick way to test for existence of
records (parent records, say) as used in
application enforcement of referential integrity
Bookstore2 SQL212 Module 2 48
Correlated subquery with Exists
SELECT isbn, quantity
FROM orderlines AS ol
WHERE exists
(select * from orders o where
ol.order_numb = o.order_numb
and o.order_date between „1-JAN-
99‟ and „31-DEC-99‟);
This type of query covered in intermediate SQL class
25
Bookstore2 SQL212 Module 2 49
Unions
• Combines two tables
• Tables must be union compatible
• Uses:
– Combine current tables with history
– Combine information from tables with no
common join column
Bookstore2 SQL212 Module 2 50
Unions
Select <column-list> from
<table1>
Union [ALL]
Select <same-columns> from
<table2>
26
Union Example
• Create a mailing list of customers and
sources
• Use a union of the two tables, making sure
the columns match
Bookstore2 SQL212 Module 2 51
Bookstore2 SQL212 Module 2 52
Unions
27
Union Results
Bookstore2 SQL212 Module 2 53
Bookstore2 SQL212 Module 2 54
SQL200
SQL Programming
Part 3 – Calculations, Aggregates
28
Bookstore2 SQL212 Module 2 55
Calculated Fields
• Can add a column calculated from others
SELECT order_numb, quantity,
cost_each,
quantity*cost_each as
extension
FROM orderlines
Bookstore2 SQL212 Module 2 56
Calculated field in the Result
29
Bookstore2 SQL212 Module 2 57
Bookstore2 SQL212 Module 2 58
String Manipulation
• Concatenation
• Trim
• Substring
• Upper, Lower
• Etc. (various vendor extensions)
30
Bookstore2 SQL212 Module 2 59
Concatenation
• Used for concatenated keys
• Useful to format reports
Basic syntax:
(Oracle, std) Field1 || Field2
Bookstore2 SQL212 Module 2 60
Concatenation
select customer_first_name
|| „ „ ||
trim(customer_last_name)
as Name
from customers
31
Bookstore2 SQL212 Module 2 61
Bookstore2 SQL212 Module 2 62
Date Functions
• Numerous date functions
• Often vendor specific
• Often used:– Take the year of a date
– Take the month of a date
– Add a month (not 30 days)
– Etc.
32
Bookstore2 SQL212 Module 2 63
Aggregate Functions
• Count
• Sum
• Min
• Max
• Avg
• Often used in conjunction with grouping
Bookstore2 SQL212 Module 2 64
Aggregate Functions
Basic syntax:
Select <function>(<column>)
From <table>
Group by <column-list>
Having <predicate>
Group by all columns to left of one(s)
you want to aggregate
33
Bookstore2 SQL212 Module 2 65
Aggregate Functions
SELECT orderlines.order_numb,
Count(*) AS “Number of Order Lines”
, Sum(orderlines.quantity) AS
SumOfquantity, Sum(quantity *
cost_each) AS extension
FROM orderlines
GROUP BY orderlines.order_numb
having count(*) > 1
Bookstore2 SQL212 Module 2 66
34
Bookstore2 SQL212 Module 2 67
Having vs. Where
• Having and Where clauses are similar but
not the same
• Having removes groups after they are
formed
• Where removes rows before groups are
formed
Bookstore2 SQL212 Module 2 68
Exercise
• List all customers and their orders
– Name nicely formatted
– With orders in the year of 1999
– Show total order quantities and amounts
– Only include orders with more than three
order lines
35
Bookstore2 SQL212 Module 2 69
Exercise Result
[end module]
Notes
Bookstore2 SQL212 Module 2 70
36
Notes
Bookstore2 SQL212 Module 2 71
Notes
Bookstore2 SQL212 Module 2 72
1
SQL/212
SQL Programming
Bookstore SQL212 Module 3 1
Workshop 3 – Modifying Data, Managing the Database
SQL212 Contact Information
P.O. Box 6142Laguna Niguel, CA 92607949-489-1472htt // d2 i t
Bookstore SQL212 Module 3 2
http://www.d2associates.comslides.1@dhdursoassociates.com
Copyright 2001-2009. All rights reserved.
2
SQL212 Module 3
• Part 1 – Modifying Data• Part 2 – Managing Database Structures• Part 3 – Creating Views and Indexes• Part 4 -- Security
Bookstore SQL212 Module 3 3
SQL/212
SQL Programming
Bookstore SQL212 Module 3 4
Part 1 – Modifying Data
3
Relational Database with constraints (from text)
Bookstore SQL212 Module 3 5
Data Modification Statements
• Insert• Insert
• Update
D l t
Bookstore SQL212 Module 3 6
• Delete
4
Data Modification Statements
• End-user rarely sees theseEnd user rarely sees these statements
• Application developer prepares these statements “behind the scenes” based on forms filled out b
Bookstore SQL212 Module 3 7
by user
Insert
• Adds new rows to an existing table• Two forms:
– Single Row– Multi-Row
Bookstore SQL212 Module 3 8
5
Single Row Insert
Basic Syntax:Insert [into] <table-name>
Values (<value-list>)
Bookstore SQL212 Module 3 9
Single Row Insert
Basic Example:insert into sources(source_numb, source_name, source_street)values(22,'Specialty Books', 'Canal Street')
Bookstore SQL212 Module 3 10
6
Insert Statement
Bookstore SQL212 Module 3 11
Sources table after Insert
Bookstore SQL212 Module 3 12
7
Multi-row Insert
Basic Syntax:
Insert [into] <table-name>
Select <select-statement>
Bookstore SQL212 Module 3 13
We will do this after creating a new table later in this module
Update
• Updates fields in an existing row
Basic Syntax:
Update <table-name>
Set <field1> = new value <field2> = new
Bookstore SQL212 Module 3 14
Set <field1> new value, <field2> new value,…
Where <selection-criteria>
8
Update
• Increase Ingram prices by 10%
Example:
Update books
Set retail price = retail price
Bookstore SQL212 Module 3 15
Set retail_price retail_price *1.10
Where source_numb = 1
Ingram Book Prices before Update
Bookstore SQL212 Module 3 16
9
Ingram Book Prices after Update
Bookstore SQL212 Module 3 17
Delete
• Deletes one or more rows
Basic Syntax:
Delete from <table-name>
Bookstore SQL212 Module 3 18
Where <selection-criteria>
10
Delete
Example: delete the source we added
Delete from sources
h b 22
Bookstore SQL212 Module 3 19
Where source_numb = 22
Delete
Bookstore SQL212 Module 3 20
11
Sources table after Delete
Bookstore SQL212 Module 3 21
Delete and Referential Integrity• Can affect referential integrity when deleting a
“parent” rowparent row• Can do following with child…
– Cascade: delete the child row– Set null: set the child’s foreign key null– Set default: as above but to default value– No action: don’t allow delete of parent row
• Referential integrity can be established when
Bookstore SQL212 Module 3 22
• Referential integrity can be established when creating or modifying table structures which we will look at later in the class
12
SQL/212
SQL Programming
Bookstore SQL212 Module 3 23
Part 2– Managing Database Structures
Schemas
• Logical view of a database; sort of a “sub-database” – we will not cover these in this module…– Catalogs– Clusters– Domains (somewhat like a user defined datatype)
Bookstore SQL212 Module 3 24
• These topics are highly dependent upon the vendor DBMS and installation practices– In Oracle you are logged in to your schema
13
Tables
• Two types• Two types– Base tables– Temporary tables
• Local (or module scope)• Global (session scope)
Bookstore SQL212 Module 3 25
• We will create base tables in this class
Creating Tables
• Use create statement• Specify:
– Columns with data types and column constraints
– Table constraints• Foreign key references
Bookstore SQL212 Module 3 26
• Foreign key references• Primary key designation
14
Data Types
• Int – integers or whole numbers– Ex: how_many int
• Char – fixed length fields– Ex: state char(2)
• Varchar/Varchar2 – variable length fields– Ex: address varchar2(35)
• Money money field
Bookstore SQL212 Module 3 27
• Money – money field• Date/Datetime – date and time • And many others – see documentation or Help
Create Table
Basic syntax:
Create table <table-name>
<column1> <datatype> <constraints>
,.. <column1> <datatype> <constraints>
Bookstore SQL212 Module 3 28
…
<table constraints>Note: often preceded by a drop
15
Temporary Tables
Basic syntax:
Create [global] temporary table <table-name>
<rest of statement as for normal create>
Bookstore SQL212 Module 3 29
Note: SQL Server uses a different syntax. Just put a #in front of the table name as in #mytable. Access doesn’t have true temporary tables.
Column Constraints
• Primary key• Not NULL• CHECK clause• Default• Unique
Bookstore SQL212 Module 3 30
q
16
Table Constraints
• Primary Key• Foreign Key• Compare fields against each other. I.e.
ship_date >= order_date
Bookstore SQL212 Module 3 31
But first – the Drop Statement
• Deletes a database “object”– Drop table <table-name>– Drop view <view-name>– Drop index <index-name>– Drop domain <domain-name>
Bookstore SQL212 Module 3 32
17
Create Table
Example 1: Create a summary tableCreate table summary(
isbn varchar2(20) primary key,
How_many int check (how_many >= 0),
Constraint isbn_fk
Bookstore SQL212 Module 3 33
Foreign key (isbn) referencesbooks(isbn)
)
Create Summary Table
Bookstore SQL212 Module 3 34
18
Constraints on Summary Table
Bookstore SQL212 Module 3 35
Multi-row Insert
Basic Syntax:
Insert [into] <table-name>
Bookstore SQL212 Module 3 36
Select <select-statement>
19
Multi-row Insert
Basic Example: (store # times each book ordered)
Insert into summary(isbn, how_many)
S l t i b t(*)
Bookstore SQL212 Module 3 37
Select isbn, count(*)
From orderlines
Group by isbn;
Multi-row Insert
Bookstore SQL212 Module 3 38
20
After multi-row insert in MS Access
Bookstore SQL212 Module 3 39
SQL/212
SQL Programming
Bookstore SQL212 Module 3 40
Part 3 – Creating Views and Indexes, Modifying Structures
21
Views
• Think of a view as a named query wherein the definition is stored in the database
• Can be read like a table• Some are updateable
Bookstore SQL212 Module 3 41
Views
Basic syntax:
Create view <view-name> (<column-list>)
As
<select statement>
Bookstore SQL212 Module 3 42
22
Creating a View
• Example: show inventory for each book
Bookstore SQL212 Module 3 43
Using Views
• Can be used like a table subject to various limitations– Cannot insert into grouped queries, etc.– Etc.
• Sample syntax:l l l
Bookstore SQL212 Module 3 44
select column-listfrom employee_view
23
Using a View
Bookstore SQL212 Module 3 45
Indexes
• Used to speed searches, joins, etc.• Placed on:
– primary and foreign keys– Secondary keys
• In commercial practice often managed by
Bookstore SQL212 Module 3 46
DBA’s for large databases
24
Indexes
Basic syntax:y
Create [unique] index <index-name>
On <table-name> (field-name> [desc])
Bookstore SQL212 Module 3 47
Note: can place index on a composite key; ex: state and city
Indexes
• Add an index on state to speed searches
Basic example:
t i d t t i
and reporting
Bookstore SQL212 Module 3 48
create index state_inx
on customers(customer_state)
25
After indexing on customer_state
Bookstore SQL212 Module 3 49
State_inx in Oracle
Bookstore SQL212 Module 3 50
26
Modifying a Table Design
• Applies to tables• Use ALTER statement
– Add columns– Delete columns– Rename columns
Bookstore SQL212 Module 3 51
– Add column constraints– Add table constraints
Modifying a Table Design
Basic syntax:y
Alter <table-name>
Add <field-name>,
Add <table-constraint>,
M dif fi ld
Bookstore SQL212 Module 3 52
Modify <field-name>
Etc.
27
Modify a Table Design
l dd h b fi ldExample: add a phone number field
alter table publishers
add phone char(12);
Bookstore SQL212 Module 3 53
After alter publishers table
Bookstore SQL212 Module 3 54
28
SQL/212
SQL Programming
Bookstore SQL212 Module 3 55
Part 4 – Security
Security
• Important DBA function– Beyond scope of this course– Typically controlled through Enterprise
Manager or Studio GUI’s• In commercial practice application security
frequently controlled via own login and a
Bookstore SQL212 Module 3 56
frequently controlled via own login and a “users” table or similar
29
Security
• Specifics can vary by product• Access: workgroup administrator• SQL Server: users, roles• Oracle: users, roles
Bookstore SQL212 Module 3 57
SQL Security Statements
• Grant• Revoke• Deny
Bookstore SQL212 Module 3 58
30
Grant
Syntax:
Grant <access-right> [with grant option]
On <object> to <user>
Bookstore SQL212 Module 3 59
Note: by default only tables owners and admins can access a table. Others must be granted the relevant rights.
Access Rights
• Select• Update• Insert• Delete• References
Bookstore SQL212 Module 3 60
• All privileges
31
Grant
Example: Give user ddurso the permission to update the employees table.
Grant update
Bookstore SQL212 Module 3 61
On employees to ddurso
Revoke
• Revokes the rights• Syntax similar to grant
Bookstore SQL212 Module 3 62
[end module]
32
Notes
Bookstore SQL212 Module 3 63
Notes
Bookstore SQL212 Module 3 64
Accelerated Computer Training for Working Professionals
Orange Coast Database Associates Course (800)355-9855 or http://ocdatabases.itgo.com
Orange Coast
Database Associates
Specializing in Microsoft Office,
Access, SQL, and related technologies Computer Training, Programming & Consulting
32422 Alipaz St., Suite A-15
San Juan Capistrano, CA
(800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax)
http://www.dhdursoassociates.com | sales@dhdursoassociates.com
Accelerated Computer Training
top related