Download presentation
Presentation is loading. Please wait.
Published byBrenda Paranhos Dinis Modified over 6 years ago
1
Ch7. SQL for DB construction and Application Processing 데이터베이스시스템 (ND352)
교수 홍 기 형
2
Chapter Objectives To be able to create and manage table structures using SQL statements To understand how referential integrity actions are implemented in SQL statements To be able to create and use SQL constraints To understand several uses for SQL views To be able to use SQL statements to create and use views To gain an understanding of how SQL is used in an application program To understand how to create and use triggers To understand how to create and use stored procedures ND352 Database Systems - Prof. Ki-Hyung Hong
3
View Ridge Gallery View Ridge Gallery is a small art gallery that has been in business for 30 years. It sells contemporary European and North American fine art. View Ridge has one owner, three salespeople, and two workers. View Ridge owns all of the art that it sells; it holds no items on a consignment basis. ND352 Database Systems - Prof. Ki-Hyung Hong
4
Application Requirements
View Ridge application requirements: Track customers and their artist interests Record gallery’s purchases Record customers’ art purchases List the artists and works that have appeared in the gallery Report how fast an artist’s works have sold and at what margin Show current inventory in a Webpage ND352 Database Systems - Prof. Ki-Hyung Hong
5
View Ridge Gallery Database Design
ND352 Database Systems - Prof. Ki-Hyung Hong
6
SQL DDL and DML Query (Select) : part of DML
ND352 Database Systems - Prof. Ki-Hyung Hong
7
Creating a New Database
in MySQL create schema dbname; drop schema dbname; ALTER SCHEMA `vrg2` DEFAULT CHARACTER SET euckr ; ND352 Database Systems - Prof. Ki-Hyung Hong
8
Create Table CREATE TABLE statement is used for creating relations.
Each column is described with three parts: column name, data type, and optional constraints. Create Table NewTablename ( ColumnName DataType OptionalConstraint, … optional table constraint ); ND352 Database Systems - Prof. Ki-Hyung Hong
9
Data Types (MySQL) ND352 Database Systems - Prof. Ki-Hyung Hong
10
Constraints Constraints can be defined within the CREATE TABLE statement, or they can be added to the table after it is created using the ALTER table statement. Five types of constraints: PRIMARY KEY may not have null values UNIQUE may have null values NULL/NOT NULL FOREIGN KEY CHECK ND352 Database Systems - Prof. Ki-Hyung Hong
11
in MySQL Workbench ND352 Database Systems - Prof. Ki-Hyung Hong
12
Create Table ARTIST .. CREATE TABLE ARTIST ( ArtistID Int NOT NULL AUTO_INCREMENT, LastName Char(25) NOT NULL, FirstName Char(25) NOT NULL, Nationality Char(30) NULL, DateOfBirth Numeric(4) NULL, DateDeceased Numeric(4) NULL, CONSTRAINT ArtistPK PRIMARY KEY(ArtistID), CONSTRAINT ArtistAK1 UNIQUE(LastName, FirstName), CONSTRAINT NationalityValues CHECK (Nationality IN ('Canadian', 'English', 'French', 'German', 'Mexican', 'Russian', 'Spanish', 'United States')), CONSTRAINT BirthValuesCheck CHECK (DateOfBirth < DateDeceased), CONSTRAINT ValidBirthYear CHECK (DateOfBirth LIKE '[1-2][0-9][0-9][0-9]'), CONSTRAINT ValidDeathYear CHECK (DateDeceased LIKE '[1-2][0-9][0-9][0-9]') ); ALTER TABLE WORK AUTO_INCREMENT = 500; ND352 Database Systems - Prof. Ki-Hyung Hong
13
Surrogate Key Column definition set initial value
ArtistID Int NOT NULL AUTO_INCREMENT, set initial value ALTER TABLE WORK AUTO_INCREMENT = 500; Primary Key CONSTRAINT ArtistPK PRIMARY KEY(ArtistID), ND352 Database Systems - Prof. Ki-Hyung Hong
14
Create Table WORK .. CREATE TABLE WORK ( WorkID Int NOT NULL AUTO_INCREMENT, Title Char(35) NOT NULL, Copy Char(12) NOT NULL, Medium Char(35) NULL, Description Varchar(1000) NULL DEFAULT 'Unknown provenance', ArtistID Int NOT NULL, CONSTRAINT WorkPK PRIMARY KEY(WorkID), CONSTRAINT WorkAK1 UNIQUE(Title, Copy), CONSTRAINT ArtistFK FOREIGN KEY(ArtistID) REFERENCES ARTIST(ArtistID) ON UPDATE NO ACTION ON DELETE NO ACTION ); ALTER TABLE WORK AUTO_INCREMENT = 500; ND352 Database Systems - Prof. Ki-Hyung Hong
15
ON UPDATE/DELETE clause
ON UPDATE NO ACTION (default) update to the primary key for a table that has children (foreign keys) should be prohibited. ON UPDATE CASCADE update to the primary key should be cascade to the children FOREIGN KEY(ArtistID) REFERENCES ARTIST(ArtistID) ON UPDATE NO ACTION ON DELETE NO ACTION ND352 Database Systems - Prof. Ki-Hyung Hong
16
Implementing Cardinalities
ND352 Database Systems - Prof. Ki-Hyung Hong
17
Implementing Default Values
Description Varchar(1000) NULL DEFAULT 'Unknown provenance', ND352 Database Systems - Prof. Ki-Hyung Hong
18
implementing Data Constraints
CHECK ND352 Database Systems - Prof. Ki-Hyung Hong
19
ALTER statement ALTER statement changes table structure, properties, or constraints after it has been created. Example ALTER TABLE ASSIGNMENT ADD CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNumber) REFERENCES EMPLOYEE (EmployeeNumber) ON UPDATE CASCADE ON DELETE NO ACTION; ND352 Database Systems - Prof. Ki-Hyung Hong
20
Adding and Dropping Columns
The following statement will add a column named MyColumn to the CUSTOMER table: ALTER TABLE CUSTOMER ADD MyColumn Char(5) NULL; You can drop an existing column with the statement: ALTER TABLE CUSTOMER DROP COLUMN MyColumn; ND352 Database Systems - Prof. Ki-Hyung Hong
21
Adding and Dropping Constraints
ALTER can be used to add a constraint as follows: ALTER TABLE CUSTOMER ADD CONSTRAINT MyConstraint CHECK ([Name] NOT IN ('Robert No Pay')); ALTER can be used to drop a constraint: DROP CONSTRAINT MyConstraint; ND352 Database Systems - Prof. Ki-Hyung Hong
22
Removing Tables If there are constraints: SQL DROP TABLE:
DROP TABLE TRANS; If there are constraints: ALTER TABLE CUSTOMER_ARTIST_INT DROP CONSTRAINT Customer_Artist_Int_CustomerFK; ALTER TABLE [TRANSACTION] DROP CONSTRAINT TransactionCustomerFK; DROP TABLE CUSTOMER; ND352 Database Systems - Prof. Ki-Hyung Hong
23
SQL DML—INSERT INSERT command: Bulk INSERT:
INSERT INTO ARTIST ([Name], Nationality, DateOfBirth, DateDeceased) VALUES ('Tamayo', 'Mexican', 1927, 1998); Bulk INSERT: INSERT INTO ARTIST ([Name], Nationality, DateOfBirth) SELECT [Name], Nationality, Birthdate FROM IMPORTED_ARTIST; ND352 Database Systems - Prof. Ki-Hyung Hong
24
SQL DML-UPDATE UPDATE command: Bulk UPDATE: UPDATE CUSTOMER
SET City = 'New York City' WHERE CustomerID = 1000; Bulk UPDATE: UPDATE CUSTOMER SET AreaCode = '333' WHERE City = 'Denver'; ND352 Database Systems - Prof. Ki-Hyung Hong
25
SQL DML—DELETE DELETE command:
DELETE FROM CUSTOMER WHERE CustomerID = 1000; If you omit the WHERE clause, you will delete every row in the table. What is the difference between the following 2 SQL statements? DELETE FROM CUSTOMER; DROP TABLE CUSTOMER; ND352 Database Systems - Prof. Ki-Hyung Hong
26
JOIN ON Syntax JOIN ON syntax: SELECT CUSTOMER.Name, ARTIST.Name
FROM CUSTOMER JOIN CUSTOMER_ARTIST_INT ON CUSTOMER.CustomerID = CUSTOMER_ARTIST_INT.CustomerID JOIN ARTIST ON CUSTOMER_ARTIST_INT.ArtistID = ARTIST.ArtistID; ND352 Database Systems - Prof. Ki-Hyung Hong
27
Using Aliases Use of aliases: SELECT C.Name, A.Name FROM CUSTOMER AS C
JOIN CUSTOMER_ARTIST_INT AS CI ON C.CustomerID = CI.CustomerID JOIN ARTIST AS A ON CI.ArtistID = A.ArtistID; ND352 Database Systems - Prof. Ki-Hyung Hong
28
Outer Joins (vs. Inner Joins)
find customers who have never made any purchase at the gallery. Left Outer Join: SELECT C.LastName, C.FirstName, A.LastName AS ArtistName FROM CUSTOMER C LEFT JOIN CUSTOMER_ARTIST_INT CI ON C.CustomerID = CI.CustomerID LEFT JOIN ARTIST A ON CI.ArtistID = A.ArtistID; ND352 Database Systems - Prof. Ki-Hyung Hong
29
Result of Outer Join ND352 Database Systems - Prof. Ki-Hyung Hong
30
SELECT T. LastName, T. FirstName From (SELECT C. LastName, C
SELECT T.LastName, T.FirstName From (SELECT C.LastName, C.FirstName, A.LastName AS ArtistName FROM CUSTOMER C LEFT JOIN CUSTOMER_ARTIST_INT CI ON C.CustomerID = CI.CustomerID LEFT JOIN ARTIST A ON CI.ArtistID = A.ArtistID) AS T Where ArtistName is null; ND352 Database Systems - Prof. Ki-Hyung Hong
31
Right Outer Join Select C.LastName, C.FirstName, T.TransactionID, T.SalesPrice From Customer AS C RIGHT JOIN TRANS AS T ON C.CustomerID = T.CustomerID ORDER BY T.TransactionID; ND352 Database Systems - Prof. Ki-Hyung Hong
32
SQL Views SQL view is a virtual table that is constructed from other tables or views. It has no data of its own, but obtains data from tables or other views. SELECT statements are used to define views: A view definition may not include an ORDER BY clause. SQL views are a subset of the external views: They can be used only for external views that involve one multivalued path through the schema. ND352 Database Systems - Prof. Ki-Hyung Hong
33
Uses of SQL Views ND352 Database Systems - Prof. Ki-Hyung Hong
34
CREATE VIEW Command CREATE VIEW command: Results:
CREATE VIEW CustomerNameView AS SELECT LastName AS CustomerLastName, FirstName AS CustomerFirstName FROM CUSTOMER; Results: SELECT * FROM CustomerNameView ORDER BY CustomerLastName, CustomerFirstName; ND352 Database Systems - Prof. Ki-Hyung Hong
35
Updateable Views ND352 Database Systems - Prof. Ki-Hyung Hong
36
Embedding SQL in Program Code
SQL can be embedded in triggers, stored procedures, and program code. Problem: assigning SQL table columns with program variables. Solution: object-oriented programming, PL/SQL. Problem: paradigm mismatch between SQL and application programming language: SQL statements return sets of rows; an application works on one row at a time. Solution: process the SQL results as pseudo-files. ND352 Database Systems - Prof. Ki-Hyung Hong
37
Application Logic - MySQL
MySQL Server database application can be processed using: Programming languages to invoke SQL Server DBMS commands The MySQL Command Line utility to invoke database commands stored in .sql files The MySQL Query Browser to invoke database commands stored in .sql files Stored procedures Triggers ND352 Database Systems - Prof. Ki-Hyung Hong
38
Triggers A trigger is a stored program that is executed by the DBMS whenever a specified event occurs on a specified table or view. Three trigger types: BEFORE, INSTEAD OF, and AFTER: Each type can be declared for Insert, Update, and Delete. Resulting in a total of nine trigger types. Oracle supports all nine trigger types. SQL Server supports six trigger types (only for INSTEAD OF and AFTER triggers). ND352 Database Systems - Prof. Ki-Hyung Hong
39
Triggers ND352 Database Systems - Prof. Ki-Hyung Hong
40
Firing Triggers When a trigger is fired, the DBMS supplies:
Old and new values for the update New values for inserts Old values for deletions The way the values are supplied depends on the DBMS product. Trigger applications include: Providing default values Enforce data constraints Updating views Performing referential integrity actions ND352 Database Systems - Prof. Ki-Hyung Hong
41
Triggers - MySQL An SQL Server trigger is invoked when a specified database activity occurs. Triggers can be used to: Enforce business rules. Set complex default values. Update views. Implement referential integrity actions. MySQL Server only supports BEFORE and AFTER triggers. Without the INSTEAD OF trigger, triggers on SQL views are not supported. MySQL trigger support is very limited, and triggers may not be used to: Make a change in the table that fired the trigger. Return an output value—triggers can use the LEAVE keyword to exit without returning a value. Make implicit or explicit ROLLBACKs of COMMITs. ND352 Database Systems - Prof. Ki-Hyung Hong
42
Create Trigger – MySQL (p307)
DELIMITER // CREATE TRIGGER AfterTRANSInsertSetAskingPrice AFTER INSERT ON TRANS FOR EACH ROW BEGIN DECLARE varRowCount Int; DECLARE varPriorRowCount Int; DECLARE varWorkID Int; DECLARE varTransactionID Int; DECLARE varAcquisitionPrice Numeric(8,2); DECLARE varNewAskingPrice Numeric(8,2); DECLARE varSumNetProfit Numeric(8,2); DECLARE varAvgNetProfit Numeric(8,2); SET varTransactionID = NEW.TransactionID; SET varAcquisitionPrice = NEW.AcquisitionPrice; SET varWorkID = NEW.WorkID; ND352 Database Systems - Prof. Ki-Hyung Hong
43
Create Trigger – MySQL (p307)
# First find if work has been here before. SELECT COUNT(*) INTO varRowCount FROM TRANS WHERE WorkID = varWorkID; SET varPriorRowCount = (varRowCount - 1); # If varPriorRowCount = 0 this is a new acquistion. IF (varPriorRowCount = 0) THEN # to twice the acquisition cost. SET varNewAskingPrice = (2 * varAcquisitionPrice); ELSE # The work has been here before # We have to determine the value of varNewAskingPrice ND352 Database Systems - Prof. Ki-Hyung Hong
44
Create Trigger – MySQL (p307)
SELECT SUM(NetProfit) INTO varSumNetProfit FROM ArtistWorkNetView AS AWNV WHERE AWNV.WorkID = varWorkID GROUP BY AWNV.WorkID; SET varAvgNetProfit = (varSumNetProfit / varPriorRowCount); # Now choose larger value for the new AskingPrice. IF ((varAcquisitionPrice + varAvgNetProfit) > (2 * varAcquisitionPrice)) THEN SET varNewAskingPrice = (varAcquisitionPrice + varAvgNetProfit); ELSE SET varNewAskingPrice = (2 * varAcquisitionPrice); END IF; ND352 Database Systems - Prof. Ki-Hyung Hong
45
Create Trigger – MySQL (p307)
# Update PRICELIST with the value of AskingPrice INSERT INTO PRICELIST VALUES (varTransactionID, 0); UPDATE PRICELIST SET AskingPrice = varNewAskingPrice WHERE TransactionID = varTransactionID; END // DELIMITER ; ND352 Database Systems - Prof. Ki-Hyung Hong
46
Application Logic: MySQL Statement Delimiters
MySQL must use a delimiter other than the SQL semicolon(;) when creating stored procedures and triggers: This is a semicolon (;) ND352 Database Systems - Prof. Ki-Hyung Hong
47
Application Logic: MySQL Control of Flow Statements
BEGIN…END IF…ELSE…END REPEAT WHILE ROLLBACK This is a semicolon (;) ND352 Database Systems - Prof. Ki-Hyung Hong
48
Application Logic: MySQL Cursor Statements
DECLARE OPEN FETCH CLOSE CURSOR DEALLOCATE CURSOR ND352 Database Systems - Prof. Ki-Hyung Hong
49
Application Logic: MySQL Output Statements
MySQL does not have output statements such as PRINT. Can use an SQL SELECT query to provide limited output ND352 Database Systems - Prof. Ki-Hyung Hong
50
Stored Procedures A stored procedure is a program that is stored within the database and is compiled when used: In Oracle, it can be written in PL/SQL or Java. In SQL Server, it can be written in TRANSACT-SQL. Stored procedures can receive input parameters and they can return results. Stored procedures can be called from: Programs written in standard languages, e.g., Java, C#. Scripting languages, e.g., JavaScript, VBScript. SQL command prompt, e.g., SQL Plus, Query Analyzer. ND352 Database Systems - Prof. Ki-Hyung Hong
51
Stored Procedures - MySQL
A stored procedure is a compiled program stored within the database. Stored procedures are programs that can: Have parameters Invoke other procedures and functions Return values Raise exceptions Creating stored procedures: Write a stored procedure in a text file and process the commands using the MySQL Query Browser ND352 Database Systems - Prof. Ki-Hyung Hong
52
Stored Procedure Advantages
Greater security as store procedures are always stored on the database server Decreased network traffic SQL can be optimized by the DBMS compiler Code sharing resulting in: Less work Standardized processing Specialization among developers ND352 Database Systems - Prof. Ki-Hyung Hong
53
ND352 Database Systems - Prof. Ki-Hyung Hong
54
ND352 Database Systems - Prof. Ki-Hyung Hong
55
Call Stored Procedure CALL InsertCustomerAndInterests ('Bench', 'Michael', '206', 'French'); SELECT * FROM CustomerInterestsView ORDER BY CustomerLastName, CustomerFirstName; ND352 Database Systems - Prof. Ki-Hyung Hong
56
Triggers vs. Stored Procedures
ND352 Database Systems - Prof. Ki-Hyung Hong
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.