class 03 topic 2 2 sql fundamentals -...

49
SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1

Upload: ledan

Post on 09-Sep-2018

243 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

SQL FundamentalsChapter 3

Class 03: SQL Fundamentals 1

Page 2: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Class 03: SQL Fundamentals 2

Page 3: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

SQL

• SQL (Structured Query Language):  A language that is used in relational databases to build and query tables.

• Earlier versions named Structured English Query Language (SEQUEL)

Class 03: SQL Fundamentals 3

Page 4: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Syntax Conventions

• Keyword identifies the operation• Statement ended with an optional semi‐colon• Statements divided into clauses

• Most clauses are optional• Clauses usually must be in a specific sequence

• White space separates elements (keywords, operators, constants, etc.)

Class 03: SQL Fundamentals 4

Page 5: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Constants in SQL

• Numeric constants are simply numbers; may include:• A decimal point• A sign• E (scientific notation)

• Character constants are enclosed in single quotes

Class 03: SQL Fundamentals 5

Page 6: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Object Names

• SQL Standard specifies up to 128 character names• Many SQL implementations have lower length limits

• Names should not be case‐sensitive per the standard• However, there are exceptions

• Names are composed of letters, numeric digits, and the underscore (spaces within names are not supported)• SQL Standard allows for quoted identifiers (using double‐quotes to enclose the entire name) • Supports names with keywords, spaces, special characters• Quoted identifiers must match exactly, including case

Class 03: SQL Fundamentals 6

Page 7: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

SQL Statement Categories

• Data Query Language (DQL)• Statements that query data but change nothing• SELECT statement

• Data Manipulation Language (DML)• Statements that modify data values but not data structures (tables, views, etc.)

• INSERT, UPDATE, DELETE statements

Class 03: SQL Fundamentals 7

Page 8: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

SQL Statement Categories

• Data Definition Language (DDL)• Statements that add/change/delete database objects, but not the data within them (the containers but not the contents)

• CREATE, ALTER, DROP statements

• Data Control Language (DCL)• Statements that manage privileges users have regarding database objects• GRANT, REVOKE statements

Class 03: SQL Fundamentals 8

Page 9: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Data Types• SQL Standard specifies data types, but vendor extensions are common

• Data Type Classes:• String:  for character strings and bit strings• Numeric:  for numbers• Datetime: for dates, times, timestamps• Boolean:  logical true/false (sparsely supported)

Class 03: SQL Fundamentals 9

Page 10: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

String Data Types

• CHARACTER (CHAR)• CHARACTER VARYING (VARCHAR)• CHARACTER LARGE OBJECT (CLOB)• XML• NATIONAL CHARACTER (NCHAR)• NATIONAL CHARACTER VARYING (NVARCHAR)• BINARY• BINARY VARYING• BINARY LARGE OBJECT (BLOB)

Class 03: SQL Fundamentals 10

Page 11: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Numeric Data Types

• NUMERIC• DECIMAL• INTEGER• SMALLINT• BIGINT• FLOAT• REAL• DOUBLE PRECISION

Class 03: SQL Fundamentals 11

Page 12: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DateTime Data Types

• DATE• Some implementations store time down to seconds in DATE data types

• TIME• TIME WITH TIME ZONE• TIMESTAMP

• Use DATETIME in SQL Server – it uses TIMESTAMP for an entirely different purpose• TIMESTAMP WITH TIME ZONE

Class 03: SQL Fundamentals 12

Page 13: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

NULL Values

•NULL represents an unknown value (instead of using false data to represent “unknown”)•NULL is not the same as a blank or a zero or an empty string•NULLs are not equal to anything else, including other NULLs•Test for NULL using “IS NULL” rather than “= NULL”•Nulls cause problems because they introduce three‐value logic where Boolean is two‐valued

Class 03: SQL Fundamentals 13

Page 14: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

The Need for Null Values

Class 03: SQL Fundamentals 14

Page 15: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DDLData Definition Language

Class 03: SQL Fundamentals 15

Page 16: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DDL Statements

• CREATE – creates new objects (tables, indexes, views, etc.)• ALTER – changes the definition of existing objects• DROP – destroys objects• TRUNCATE – efficiently empties a table (without the need for row‐by‐row deletion of the data)• Not described in the text because TRUNCATE was added to the standard after the text was written

Class 03: SQL Fundamentals 16

Page 17: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Creating Tables

CREATE TABLE table_name(column_name data_type [(length)] [NOT NULL], …)IN tablespace_namePRIMARY KEY [key_name] (column list)FOREIGN KEY [constraint_name] (column list)REFERENCES table_name (column list)ON DELETE {RESTRICT | CASCADE | SET NULL}

Class 03: SQL Fundamentals 17

Page 18: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

CREATE TABLE Example

DROP TABLE INVOICE;CREATE TABLE INVOICE

( ID CHAR(5), ORDER_DATE DATE, AMOUNT DECIMAL(8,2), CUSTOMER_ID CHAR(5), EMPLOYEE_ID CHAR(11)

);

Class 03: SQL Fundamentals 18

Page 19: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Primary Key Constraint

•A Primary Key constraint forces uniqueness on a column or set of columns.  The DBMS creates a Unique Index to enforce the constraint.•Each table may have only one primary key (but that key may be one or several columns)•Alternatively, you can create a Unique Index to do the same thing, but it won’t have a constraint name.

Class 03: SQL Fundamentals 19

Page 20: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Primary Key Example

ALTER TABLE INVOICEADD CONSTRAINT  PK_INVOICE PRIMARY KEY (ID);

‐‐VS.‐‐

CREATE UNIQUE INDEX PK_INVOICEON INVOICE (ID);

Class 03: SQL Fundamentals 20

Page 21: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Altering Table Definitions

ALTER TABLE table_nameADD column_name…RENAME column_name TO new_nameMODIFY column_name …DROP PRIMARY KEYDROP FOREIGN KEY constraint_nameCHECK (check constraint condition)

Class 03: SQL Fundamentals 21

Page 22: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Alter Table

ALTER TABLE CUSTOMERADD CONSTRAINT PK_CUSTOMER PRIMARY KEY (ID);

ALTER TABLE INVOICE ADD CONSTRAINT FK_CUST_ID FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(ID);

Class 03: SQL Fundamentals 22

Page 23: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Create Index

• Indexes can make queries run more efficiently but they are never necessary to achieve correct results

• Indexes are used to enforce uniqueness of single columns or sets of columns

• Example:CREATE INDEX invoice_customer_ix

ON invoice (customer_id);

Class 03: SQL Fundamentals 23

Page 24: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DROP Statement

• DROP statement destroys an object and its contents.  • If you merely want to remove the data from a table, use TRUNCATE or DELETE instead.

DROP INDEX RACE_RESULT_HORSE;

DROP TABLE RACE_RESULT

CASCADE CONSTRAINTS;

Class 03: SQL Fundamentals 24

Page 25: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DQLData Query Language (The SELECT Statement)

Class 03: SQL Fundamentals 25

Page 26: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Relational Operations

•Selection:  Defines a relation that contains only those tuples (rows) that satisfy the specified condition (predicate)•Projection:  Defines a relation that extracts the values of specified attributes (and eliminates duplicates)•Cartesian Product:  Defines a relation that is the concatenation of every tuple in one relation with every tuple in another

Class 03: SQL Fundamentals 26

Page 27: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Relational Operations

• Union:  The concatenation of two relations (duplicates eliminated);  relations must be union‐compatibleUnion‐compatible:  relations with the same number of attributes and matching domains

• Set Difference:  Defines a relation that contains all tuples from one relation that are not contained in another;  must be union‐compatible 

Class 03: SQL Fundamentals 27

Page 28: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Relational Operations

• Join:  a combination of two relations to form a new relation;  a derivative of a Cartesian product that uses a join predicate to specify how tuples are to be joined• There are multiple types of joins, but in a language like SQL, they are all written using the same syntax

Class 03: SQL Fundamentals 28

Page 29: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Relational Joins

• Equi‐join:  A join where the join predicate contains only the equality operator (=)• The most commonly used form

• Theta Join:  A join where the join predicate contains any comparison operator:  <, <=, >, >=, != (<>), BETWEEN

Class 03: SQL Fundamentals 29

Page 30: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Relational Joins

• Outer Join:  A join that includes a row from one of the relations even when there is no matching row in the other;  missing attributes appear as null• Left Outer Join:  Outer join that returns every row for the left‐hand relation• Right Outer Join:  Outer join that returns every row from the right‐hand relation

Class 03: SQL Fundamentals 30

Page 31: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

SQL Demo(see separate presentation)

Class 03: SQL Fundamentals 31

Page 32: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Views

Class 03: SQL Fundamentals 32

Page 33: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Views

• View:  A dynamic result of one or more relational operations on the base relations to produce another relation;  a virtual relation that does not exist in the database, but is produced upon request

• Base Relation:  A named relation corresponding to an entity in the conceptual schema whose tuples are physically stored in the database

Class 03: SQL Fundamentals 33

Page 34: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Views

• Views can be constructed “on the fly” by performing various relational operations

• The definition of a view can be permanently stored in the catalog and used in relational operations in the same way as tables;  stored views never contain data

• Changes made to the data in the base relations are automatically reflected in the view.

Class 03: SQL Fundamentals 34

Page 35: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Class 03: SQL Fundamentals 35

Page 36: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Purpose/Benefits of Views

• Provides a powerful and flexible security mechanism by hiding parts of the database from certain users

• Permits users to access data that is customized to their needs• Can simplify complex operations on base relations (e.g. views can handle joins)

Class 03: SQL Fundamentals 36

Page 37: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Updating Views

• The ability to apply updates to views varies widely from one DBMS to another

• Most DBMSs recognize views as “updateable” and “not updateable”;  a few recognize “partially updateable” views

• Generally, views formed form a single relation that contain either a primary or candidate key can be updated

Class 03: SQL Fundamentals 37

Page 38: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Updating Views

• Updates are generally not allowed through views involving multiple base relations

• Updates are generally not allowed through views involving aggregation or grouping operations

• Updates are generally not allowed on derived/calculated attributes in views

Class 03: SQL Fundamentals 38

Page 39: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Updating Views

Class 03: SQL Fundamentals 39

Page 40: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DMLData Manipulation Language

Class 03: SQL Fundamentals 40

Page 41: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

INSERT Statement

• Adds new rows to a table• Column list is optional, but highly recommended for flexibility and data independence

• Two forms:• INSERT with VALUES:

• VALUES clause provides values for a row of data• Some implementation support multiple VALUES clauses, each of which causes one row to be added

• INSERT with Subquery• SELECT statement provides the rows and column values to be inserted.

Class 03: SQL Fundamentals 41

Page 42: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

INSERT Statement Examples

INSERT INTO RACE_RESULT

(TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE

PURSE, LENGTHS_BEHIND)

VALUES ('Winona','1','2015-07-04','KY0993',4,0,10);

INSERT INTO RACE_RESULT

(TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE

PURSE, LENGTHS_BEHIND)

VALUES ('Winona','1','2015-07-04','QH0334',1,2500,0),

('Winona','1','2015-07-04','QH3993',5,0,11),

('Winona','1','2015-07-04','QH0443',3,500,1.5);

Class 03: SQL Fundamentals 42

Page 43: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

INSERT Statement Examples

INSERT INTO RACE_RESULT

(TRACK_ID, RACE_NUMBER, RACE_DATE, HORSE_ID, PLACE

PURSE, LENGTHS_BEHIND)SELECT TRACK_ID, RACE_NUMBER, RACE_DATE,

HORSE_ID, PLACE, PURSE, LENGTHS_BEHIND

FROM RACE_RESULTWHERE RACE_DATE BETWEEN '2015-01-01'

AND '2015-12-31';

Class 03: SQL Fundamentals 43

Page 44: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Update Statement

• Modifies data values within a table• SET clause specifies the list of columns to be updated, along with an expression that provides a new value for each column

• If WHERE clause is omitted, will attempt to update very row in the table

UPDATE OWNER

SET OWNER_LAST_NAME = 'McMillan‘,

STREET_ADDRESS = '3205 Equine Ct., Apt. 6'

WHERE OWNER_ID = '00011';

Class 03: SQL Fundamentals 44

Page 45: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DELETE Statement

• Removes rows from a table• If WHERE clause is omitted, attempts to delete all the rows in the table

DELETE FROM RACE_RESULTWHERE RACE_DATE < '2012-01-01';

Class 03: SQL Fundamentals 45

Page 46: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

DCL

Data Control Language

Class 03: SQL Fundamentals 46

Page 47: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

Privileges

• DCL statements manage privileges for database accounts.• Privileges can be:

• System privileges, which permit the grantee to perform a general DBMS function, such as creating views or connecting to the database.

• Object privileges, which permit the grantee to perform specific actions on specific objects, such as selecting from the OWNER table or inserting into the RACE_RESULT table

Class 03: SQL Fundamentals 47

Page 48: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

GRANT Statement

• Gives one or more privileges to grantee(s).• Examples:

GRANT CREATE VIEW TO HR;

GRANT SELECT, INSERT, UPDATE

ON RACE_RESULT TO Mgr123;

Class 03: SQL Fundamentals 48

Page 49: Class 03 Topic 2 2 SQL Fundamentals - AndyOppel.comandyoppel.com/X4091/lectures/Class_03_Topic_2_2... · SQL •SQL(Structured Query Language): A language that is used in relational

REVOKE Statement

• Takes privileges away from grantees• Examples:

REVOKE CREATE VIEW FROM HR;

REVOKE SELECT, INSERT, UPDATEON RACE_RESULT FROM Mgr123;

Class 03: SQL Fundamentals 49