Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Introduction to SQL

Similar presentations


Presentation on theme: "Chapter 6: Introduction to SQL"— Presentation transcript:

1 Chapter 6: Introduction to SQL
Modern Database Management 11th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi © 2013 Pearson Education

2 Chapter Outline Origin of the SQL Standard The SQL Environment
Defining a Database in SQL Inserting, Updating, and Deleting Data Internal Schema Definition in RDBMS Processing Single Tables

3 Learning Objectives Understand definitions of terms
Interpret history and role of SQL Define a database using SQL data definition language Write single table queries using SQL Establish referential integrity using SQL Discuss SQL:1999 and SQL:2008 standards

4 SQL Overview SQL : Structured Query Language
The standard language for relational database management systems (RDBMS) RDBMS A database management system that manages data as a collection of tables in which all relationships are represented by common values (PK-FK) in related tables Data in Relational DB

5 Figure 6.3 Sample Data of a Relational Database
PK PK FK FK PK FK PK 5

6 History of SQL 1970 – E. F. Codd develops relational database concept
1974 – 1979 – System R with Sequel (later SQL) created at IBM Research Lab 1979 – Oracle markets first relational DB with SQL 1981 – SQL/DS (Structured Query Language/Data System) first available RDBMS system on DOS/VSE Others followed: INGRES (1981), IDM (1982), DG/SGL (1984), Sybase (1986) 1986 – ANSI SQL standard released 1989, 1992, 1999, 2003, 2006, 2008–Major ANSI SQL standard updates Current – SQL is supported by most major database vendors

7 Purpose of SQL Standard
Specify syntax/semantics for data definition and manipulation Define data structures and basic operations Enable portability (可攜性) of database definition and application modules Specify minimal (level 1) and complete (level 2) standards Allow for later growth/enhancement to standard (referential integrity, transaction management, user-defined functions, extended join operations, national character sets)

8 Benefits of a Standardized Relational Language
Reduced training costs Productivity Application portability Application longevity (長壽) Reduced dependence on a single vendor Cross-system communication

9 Some Terms in SQL ENVIRONMENT
Catalog A set of schemas that constitute the description of a database Schema (架構概要) A structure that contains descriptions of objects (base tables, views, constraints) created by a user Data Definition Language (DDL) Commands used to define a database, including creating, altering, and dropping tables and establishing constraints Data Manipulation Language (DML) Commands used to maintain and query a database Data Control Language (DCL) Commands used to control a database, including those for administering privileges and committing (確認寫入) data (making tentative changes permanent)

10 Figure 6-1 A simplified schematic of a typical SQL environment, as described by the SQL: 2008 standard Database 1 Database 2 © 2013 Pearson Education Chapter 6 10

11 SQL Data Types

12 DDL, DML, DCL, and the database development process
Figure 6-4 DDL, DML, DCL, and the database development process Logical Design used by programmer used by DBA 相反 © 2013 Pearson Education Chapter 6 12

13 SQL Database Definition
By Data Definition Language (DDL) Major CREATE statements: CREATE SCHEMA – used to define the portion of the database owned by a particular user Schema objects include base tables, views, constraints, … Privilege of creating DBs may be reserved for the DBA CREATE TABLE – used to define a new table and its columns CREATE VIEW – used to define a logical (virtual) table from one or more tables or views Advanced CREATE statements: CHARACTER SET, TRANSLATION, DOMAIN, COLLATE, ASSERTION (Not covered in this textbook) 重點

14 Steps in Table Creation
Identify data type for each attribute Identify columns that can and cannot be null Identify columns that must be unique (candidate keys) Identify primary key–foreign key mates Determine default values Identify constraints on columns (domain specifications) Create the table and associated indexes

15 Figure 6-5 General syntax for CREATE TABLE statement used in data definition language
較不常用 statement example Notation { } : one or more [ ] : optional ( ) : reserved symbol | : or

16 Simplified general syntax for CREATE TABLE statement
不常用 statement example Notation { } : one or more [ ] : optional ( ) : reserved symbol | : or

17 Example of column definitions and table constraint
constraints column definitions table constraint

18 More on Defining attributes and their data types
(Example of Column Definitions) column constraints data types column names DDL syntax column names column constraints data types © 2013 Pearson Education table constraint Chapter 6 18

19 Non-nullable specification
(Example of Column Constraint Clause) column constraint clause DDL syntax column constraint clause table constraint Primary keys can never have NULL values Identifying primary key © 2013 Pearson Education Chapter 6 19

20 Non-nullable Specifications
DDL syntax 2 non-nullable column constraints 3 table constraints 2-attribute primary key The primary key is composite. It is composed of 2 attributes D/B Schema © 2013 Pearson Education Chapter 6 20

21 Controlling the Values in an Attribute
default value DDL syntax domain constraint © 2013 Pearson Education Chapter 6 21

22 Identifying foreign keys and establishing relationships
PK of parent table Foreign key of the dependent (child) table Relational schema © 2013 Pearson Education Chapter 6 22

23 Referential integrity constraints are drawn via arrows from child table to parent table
Corresponding SQL DDL Data Example (From Figure 4-5 Relational Schema for Pine Valley Furniture) Creation order of tables : CUSTOMER > ORDER > ORDER LINE PRODUCT > ORDER LINE Data entry order : © 2013 Pearson Education Chapter 4 23

24 Figure 6-6 SQL DB definition commands for Pine Valley Furniture Company
(Oracle 11g) Overall table definitions Relational Schema Data Example

25 Creating Data Integrity Controls
Referential integrity (參照的完整性) Establishing referential integrity constraint between two tables (a child and a parent tables) with a 1:M relations. In an SQL statement, the referential integrity constraint ensures that the foreign key values of a (child) table must match the primary key values of its related (parent) table, or Be NULL The REFERENCES clause prevents making a non-matching change in FK value. Other situations of creating referential integrity control: Delete primary records in the parent table Update primary records in the parent table Clause Data Example

26 Figure 6-7 Example of ensuring data integrity in data updates
Relational Schema Parent table Child table Relational integrity is enforced via PK-FK match is ensured The other 3 options © 2013 Pearson Education Chapter 6 26

27 Changing Table Definitions
ALTER TABLE statement allows you to change column specifications: alter_table_action : Example (adding a new column with a default value):

28 DROP TABLE statement allows you to remove tables from your schema:
Removing Tables DROP TABLE statement allows you to remove tables from your schema: Example : DROP TABLE CUSTOMER_T

29 Insert Statement Statement for adding one or more data rows to a table
Example of inserting into a table Inserting a record that has some null attributes requires identifying the fields that actually get data Inserting records from another table table definition table definition Attribute productLineID is not specified. NULL is entered for attribute productLineID in this record.

30 CREATING TABLES WITH IDENTITY (識別) COLUMNS (INTRODUCED IN SQL:2008)
Remove the need to create a procedure to generate a sequence and then apply into it to data insertion.

31 Creating Tables with Identity Columns (Introduced IN SQL:2008)
Only one column can be an identity column in a table. Insertion statement does not require value explicitly specified for identity column (CustomerID in the following example). Example : INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601); table definition

32 Delete Statement Removes data rows from a table
Example of deleting certain rows DELETE FROM Customer_T WHERE CustomerState = ‘HI’; Example of Deleting all data rows : DELETE FROM Customer_T; Sample data

33 Update Statement Example of modifying data in existing rows
UPDATE Product_T SET ProductStandardPrice = 775 WHERE ProductID = 7; Data Example

34 Definition of Internal Schema
Control processing/storage efficiency: Choice of indexes File organizations for base tables File organizations for indexes Data clustering Maintenance Statistics Creating indexes Speed up random/sequential access to base table data Statement example : CREATE INDEX Name_IDX ON CUSTOMER_T(CustomerName) This makes an index for the CustomerName field of the CUSTOMER_T table CUSTOMER table

35 SELECT Statement Used for queries on single or multiple tables
Clauses of the SELECT statement: SELECT List the columns (and expressions) to be returned from the query FROM Indicate the table(s) or view(s) from which data will be obtained WHERE Indicate the conditions under which a row will be included in the result GROUP BY Indicate the attribute(s) used for the categorization of query results HAVING Indicate the conditions under which category (group) will be included in the query result ORDER BY Sorts the query result according to the specified criteria

36 SQL statement processing order (based on van der Lans, 2006 p.100)
Must have these 2 clauses in a SQL statement Figure 6-2 General syntax of the SELECT statement used in DML Figure 6-10 SQL statement processing order (based on van der Lans, 2006 p.100) © 2013 Pearson Education Chapter 6 36

37 PRODUCTSTANDARDPRICE
SELECT Example Relational Schema Data Example Query : List product description and price for products with standard price less than $275. Product_T table Result : PRODUCTDESCRIPTION PRODUCTSTANDARDPRICE End Table 175 Computer Desk 250 Coffee Table 200

38 SELECT Example Using Alias
Alias is an alternative column or table name (Often, it is a shorter name) SELECT CUST.CustomerName AS Name, CUST.CustomerAddress FROM CUSTOMER_T CUST WHERE Name = ‘Home Furnishings’; alias CUSTOMER_T table Relational Schema 需一致 需一致 alias Result : NAME CUSTOMERADDRESS Home Furnishings 1900 Allard Ave.

39 SELECT Example Using An Aggregate Function
Using the COUNT aggregate function to find total number of records. Example : SELECT COUNT(*) FROM ORDERLINE_T WHERE ORDERID = 1004; Note: With aggregate functions you can’t have column name(s) included in the SELECT clause, unless they are included in the GROUP BY clause. Result : Data COUNT(*) 2

40 ERROR Example Using An Aggregate Function
Using the COUNT aggregate function to find totals. Error example : SELECT ProductID, COUNT(*) FROM ORDERLINE_T WHERE ORDERID = 1004; Result (in Microsoft SQL): Column ‘OrderLine_T.ProductID’ is invalid in the select list because it is not contained in an Aggregate function and there is no GROUP BY clause. Correct example: SELECT ProductID, COUNT(ProductID) GROUP BY ProductID; error Result : ORDERLINE PRODUCTID COUNT(*) 6 1 8 match

41 SELECT Example–Boolean Operators
AND, OR, and NOT boolean operators for combining multiple conditions in the WHERE clause Relational Schema Data Example Note: LIKE operator allows us to compare the partial part of a string using wildcards (萬用字元). For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the suffix (字尾) “Desk” will be allowed.

42 Figure 6-8 : A Boolean query without use of parentheses
ProductDescription LIKE ‘%Desk’ ProductDescription LIKE ‘%Table’ By default, processing order of Boolean operators is NOT, then AND, then OR ( ) ; Product_T

43 Result of a Boolean query without use of parentheses
Product_T PRODUCTDESCRIPTION PRODUCTFINISH PRODUCTSTANDARDPRICE Computer Desk Natural Ash 375 Writer’s Desk Cherry 325 8-Drawer Desk White Ash 750 Dining Table 800 Walnut 250

44 SELECT Example–Boolean Operators
Parentheses override the normal precedence of Boolean operators In this case parentheses make the OR take place before the AND.

45 Figure 6-9 : A Boolean query with use of parentheses
ProductDescription LIKE ‘%Desk’ ProductDescription LIKE ‘%Table’ Product_T

46 Result of a Boolean query with use of parentheses
Product_T PRODUCTDESCRIPTION PRODUCTFINISH PRODUCTSTANDARDPRICE Computer Desk Natural Ash 375 Writer’s Desk Cherry 325 8-Drawer Desk White Ash 750 Dining Table 800

47 Sorting Results with ORDER BY Clause
Query : List customer name, city, and state for all customers in the CUSTOMER table whose address is in Florida, Texas, California, or Hawaii. List the customers alphabetically by state, and alphabetically by name within each state. Data Note: The IN operator in this example allows you to include rows whose CustomerState value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions.

48 Sorting Results with ORDER BY Clause
Customer_T

49 Categorizing Results Using GROUP BY Clause
Combined with an aggregate function to provide a summary information for each data subgroup categorized by certain attribute(s). The attributes used in GROUP BY clause have to appear in SELECT clause. The SELECT clause has to contains at least one aggregate function. Example an aggregate function match

50 Categorizing Results Using GROUP BY Clause
Query : List the number of customers in each state. Customer_T

51 QUALIFYING (限定) RESULTS BY CATEGORIES : USING HAVING CLAUSE
Having clause is used with GROUP BY Functioning like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result. match match

52 QUALIFYING (限定) RESULTS BY CATEGORIES : USING HAVING CLAUSE
Example of No Having

53 Using and Defining Views
Views provide users controlled access to tables Base Table : A table containing the raw data Dynamic (動態的) View A “virtual table” created dynamically upon request by a user No data actually stored; instead data from base table made available to user Based on SQL SELECT statement on base tables or other views Materialized (實體化的) View Copy or replication of data Data actually stored Must be refreshed periodically to match the changes of the corresponding base tables

54 Sample CREATE VIEW View has a name. CHECK OPTION
rule of the view View has a name. CHECK OPTION works only for updateable views prevents updates on ExpensiveStuff_V that would make data rows not obey the rule of the view.

55 Database SQL查詢實作 (Microsoft Access 2010)
Visit ftp:// Folder : cchen/106Spring/106S_DBMS/Data Files/MS Access Download MS Access File : PVFC11e.mdb

56 Microsoft Access Database SQL實作
進入Query的設計環境 2.點選「查詢設計」以新增一個query 1.點選「建立」

57 Microsoft Access Database SQL實作
新增一個Query 1.點選Customer_T資料表 以表示查詢的資料是來自資料表 2.點選「關閉」

58 Microsoft Access Database SQL實作
1.點選SQL檢視,以進入SQL程式撰寫視窗

59 Microsoft Access Database SQL實作

60 Microsoft Access Database SQL實作
1.點選「檔案」 2.點選「另存物件為」 3.輸入查詢「查詢名稱」

61 Microsoft Access Database SQL實作
點選X 可關閉「Customer_Query1」 若欲重新開啟「Customer_Query1」 1.點選「Customer_T」資料表 2.點選「Customer_Query1」可開啟它

62 Microsoft Access Database SQL實作
課本的範例資料庫 Positive Aspects Simplify query commands Help provide data security and confidentiality Improve programmer productivity 下拉式選單 : 可選所有資料表

63 隨堂作業題目 第六章 Problems and Exercises (319~322頁) 請注意 :
6-34: relations QUALIFIED, FACULTY and COURSE 6-39 : a (改為“用你自己學號和姓名”), c 6-40 : a 6-41 : a 6-64 6-71 請注意 : 第6-64和6-71題可使用 ftp:// 中MS Access資料庫的資 料表cchen/106Spring/106S_DBMS/Data Files/MS Access/PVFC11e.mdb

64 Copyright © 2013 Pearson Education
64


Download ppt "Chapter 6: Introduction to SQL"

Similar presentations


Ads by Google