SQL The questing beast Sir Thomas Mallory. SQL A standard ANSI ISO SQL skills are in demand Developed by IBM Object-oriented extensions created.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 12 ODBC, OLE DB, ADO, and ASP.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
SQL components In Oracle. SQL in Oracle SQL is made up of 4 components: –DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE. Creates / Alters.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
1 IS 4420 Database Fundamentals Chapter 7: Introduction to SQL Leon Chen.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Management Fall 2003 Functions, Procedures and Triggers Chapter 10.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Introduction to SQL J.-S. Chou Assistant Professor.
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 13 Managing Databases with SQL Server 2000.
Introduction to Databases Chapter 6: Understanding the SQL Language.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
RDB/1 An introduction to RDBMS Objectives –To learn about the history and future direction of the SQL standard –To get an overall appreciation of a modern.
Database Technical Session By: Prof. Adarsh Patel.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
CS 3630 Database Design and Implementation. Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
CSc-340 3b1 Intermediate SQL Chapter 4 [2 of 2] Phase 1 of Student Projects SQL Data Types & Schemas Authorization.
Concepts of Database Management Seventh Edition
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Lec 3- B Database Integrity 1. Overview Define a database using SQL data definition language Work with Views Write single table queries Establish referential.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
SQL Overview Structured Query Language
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL Basics Review Reviewing what we’ve learned so far…….
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Big Data Yuan Xue CS 292 Special topics on.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
More SQL: Complex Queries,
The questing beast Sir Thomas Mallory
TABLES AND INDEXES Ashima Wadhwa.
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
More SQL: Complex Queries, Triggers, Views, and Schema Modification
The questing beast Sir Thomas Mallory
Database systems Lecture 3 – SQL + CRUD
Chapter 7 Introduction to Structured Query Language (SQL)
SQL-1 Week 8-9.
Contents Preface I Introduction Lesson Objectives I-2
SQL (Structured Query Language)
Presentation transcript:

SQL The questing beast Sir Thomas Mallory

SQL A standard ANSI ISO SQL skills are in demand Developed by IBM Object-oriented extensions created

SQL A complete database language Data definition Definition of tables and views Data manipulation Specifying queries Maintaining a database INSERT UPDATE DELETE

SQL Not a complete programming language Used in conjunction with complete programming languages e.g., COBOL and Java Embedded SQL

Data definition Table, views, and indexes can be defined while the system is operational Base table An autonomous, named table CREATE TABLE

Constraints Primary key CONSTRAINT pk_stock PRIMARY KEY(stkcode); Foreign key CONSTRAINT fk_stock_nation FOREIGN KEY(natcode) REFERENCES nation; Unique CONSTRAINT unq_stock_stkname UNIQUE(stkname);

Check constraint Table & Column Table CREATE TABLE item ( itemcode INTEGER, CONSTRAINT chk_item_itemcode CHECK(itemcode <500)); Column CREATE TABLE item ( itemcode INTEGER CONSTRAINT chk_item_itemcode CHECK(itemcode <500), itemcolor VARCHAR(10));

Check constraint Domain CREATE DOMAIN valid_color AS CHAR(10) CONSTRAINT chk_qitem_color CHECK( VALUE IN ('Bamboo',’Black',’Brown',Green', 'Khaki',’White')); CREATE TABLE item ( itemcode INTEGER, itemcolor VALID_COLOR);

Data types BOOLEAN INTEGER 31 binary digits SMALLINT 15 binary digits FLOAT Scientific work DECIMAL Commercial applications CHAR and VARCHAR Character strings DATE, TIME, TIMESTAMP, and INTERVAL BLOB and CLOB

Changing a table ALTER TABLE Adding one new column at a time Cannot be used to Change a column’s storage format Delete an unwanted column DROP TABLE Deletes a table

A view CREATE VIEW DROP VIEW

An index CREATE INDEX DROP INDEX

Data manipulation statements INSERT UPDATE DELETE SELECT

INSERT One row Multiple rows With a subquery - like a copy INSERT INTO STOCK (stkcode, stkfirm, stkprice, stkdiv, stkpe) SELECT code, firm, price, div, pe FROM download WHERE code IN ('FC','PT','AR','SLG','ILZ','BE','BS','NG', 'CS','ROF');

UPDATE One row Multiple rows All rows

DELETE One row Multiple rows All rows Not the same as DROP TABLE

Product All rows of the first table concatenated with all possible rows of the second table Form the product of stock and nation SELECT * FROM stock, nation;

Product Find the percentage of Australian stocks in the portfolio. CREATE VIEW austotal (auscount) AS SELECT COUNT(*) FROM stock WHERE natcode = 'AUS'; CREATE VIEW TOTAL (totalcount) AS SELECT COUNT(*) FROM stock; SELECT DECIMAL((FLOAT(auscount)/ FLOAT(totalcount)*100),5,2) AS percentage FROM austotal, total; 18.75

Join Join creates a new table from two existing tables by matching on a column common to both tables Equijoin The new table contains two identical columns SELECT * FROM stock, nation WHERE stock.natcode = nation.natcode;

Join variations SELECT * FROM stock INNER JOIN nation USING (natcode); SELECT * FROM stock NATURAL JOIN nation;

Outer join Left outer join An inner join plus those rows from t1 not included in the inner join SELECT * FROM t1 LEFT JOIN t2 USING (id); t1t2 idcol1idcol2 1a1x 2b3y 3c5z t1.idcol1t2.idcol2 1a1x 2bnull 3c3y

Outer join Right outer join An inner join plus those rows from t2 not included in the inner join SELECT * FROM t1 RIGHT JOIN t2 USING (id); t1.idcol1t2.idcol2 1a1x 3c3y null 5z t1t2 idcol1idcol2 1a1x 2b3y 3c5z

Outer join Full outer join An inner join plus those rows from t1 and t2 not included in the inner join SELECT * FROM t1 FULL JOIN t2 USING (id); t1t2 idcol1idcol2 1a1x 2b3y 3c5z t1.idcol1t2.idcol2 1a1x 2bnull 3c3y 5z

Outer join Left join example List all items with details of deliveries if any have been made (see page 284) SELECT * FROM qitem LEFT JOIN qdel USING (itemname); Right join example List all departments and any sales they have made SELECT * FROM qsale RIGHT JOIN qdept USING (deptname);

Theta join Join is a product with a condition clause The condition is not restricted to equality. A theta join is the general version Theta is a variable that can take any value from the set [=, <>, >, ≥, <, ≤]

Correlated subquery The inner query is evaluated many times rather than once Find those stocks where the quantity is greater than the average for that country. SELECT natname, stkfirm, stkqty FROM stock, nation WHERE stock.natcode = nation.natcode AND stkqty > (SELECT AVG(stkqty) FROM stock WHERE stock.natcode = nation.natcode);

Correlated subquery Clue The need to compare each row of a table against a function (e.g., average or count) for some rows of a column Must be used with EXISTS and NOT EXISTS

Aggregate functions COUNT SUM AVG MAX MIN

SQL Routines Functions Procedures Introduced in SQL-99 Not all vendors compliant with the standard Improve flexibility, productivity, and enforcement of business rules

SQL function Similar purpose to built-in functions CREATE FUNCTION km_to_miles() RETURNS FLOAT CONTAINS SQL RETURN ; Use in SQL SELECT distance*km_to_miles FROM travel;

SQL procedure A stored procedure is SQL code that is dynamically loaded and executed by a CALL statement Accounting example

SQL procedure CREATE PROCEDURE transfer ( IN cracct INTEGER, IN dbacct INTEGER, IN amt DECIMAL(9,2), IN transno INTEGER) LANGUAGE SQL BEGIN INSERT INTO transaction VALUES (transno, amt, current date); UPDATE account SET acctbalance = acctbalance + amt WHERE acctno = cracct; INSERT INTO entry VALUES(transno, cracct, 'cr'); UPDATE account SET acctbalance = acctbalance - amt WHERE acctno = dbacct; INSERT INTO entry VALUES (transno, dbacct, 'db'); END;

SQL procedure Execution CALL transfer(cracct, dbacct, amt, transno); Example Transaction 1005 transfers $100 to account 1 (the credit account) from account 2 (the debit account) CALL transfer(1,2,100,1005);

Trigger A set of actions set off by an SQL statement that changes the state of the database UPDATE INSERT DELETE

Trigger Automatically log all updates to a log file Create a table for storing log rows Create a trigger CREATE TABLE stock_log ( stkcodeCHAR(3), old_stkpriceDECIMAL(6,2), new_stkpriceDECIMAL(6,2), old_stkqtyDECIMAL(8), new_stkqtyDECIMAL(8), update_stktimeTIMESTAMP NOT NULL, PRIMARY KEY(update_stktime));

Trigger CREATE TRIGGER stock_update AFTER UPDATE ON stock REFERENCING old AS old_row new AS new_row FOR EACH ROW MODE db2sq1 INSERT INTO stock_log VALUES (old_row.stkcode, old_row.stkprice, new_row.stkprice, old_row.stkqty, new_row.stkqty, CURRENT TIMESTAMP);

Nulls Don’t confuse with blank or zero Multiple meanings Unknown data Inapplicable data No value supplied Value undefined Create confusion because the user must make an inference Date advises that NOT NULL be used for all columns to avoid confusion

Security Data is a valuable resource Access should be controlled SQL security procedures CREATE VIEW Authorization commands

Authorization Based on privilege concept You cannot execute an operation without the appropriate privilege DBA has all privileges

GRANT Defines a user’s privileges Format GRANT privileges ON object TO users [WITH GRANT OPTION]; An object is a base table or view The keyword privilege can be ALL PRIVILEGES or chosen from SELECT UPDATE DELETE INSERT Privileges can be granted to everybody using the keyword PUBLIC or to selected users by specifying their user identifier

GRANT The UPDATE privilege can specify particular columns in a base table or view Some privileges apply only to base tables ALTER INDEX WITH GRANT OPTION Permits a user to pass privileges to another user

Using GRANT Give Alice all rights to the STOCK table. GRANT ALL PRIVILEGES ON stock TO alice; Permit the accounting staff, Todd and Nancy, to update the price of a stock. GRANT UPDATE (stkprice) ON stock TO todd, nancy; Give all staff the privilege to select rows from ITEM. GRANT SELECT ON item TO PUBLIC; Give Alice all rights to view STK. GRANT SELECT, UPDATE, DELETE, INSERT ON stk TO alice;

REVOKE Removes privileges Format REVOKE privileges ON object FROM users; Cascading REVOKE Reverses use of the WITH GRANT OPTION When a user’s privileges are revoked, all users whose privileges were established using WITH GRANT OPTION are also revoked

Using REVOKE Remove Sophie's ability to select from ITEM. REVOKE SELECT ON item FROM sophie; Nancy is no longer permitted to update stock prices. REVOKE UPDATE ON stock FROM nancy;

The catalog A relational database containing definitions of base tables, view, etc. Can be interrogated using SQL Called systems tables rather than base tables Key tables are syscatalog syscolumns sysindexes

Interrogating the catalog Find the table(s) with the most columns. SELECT tname FROM system.syscatalog WHERE ncols = (SELECT MAX(ncols) FROM system.syscatalog); What columns in what tables store dates? SELECT tname, cname FROM system.syscolumns WHERE coltype = 'date';

Natural language processing

Open Database Connectivity (ODBC) Application ODBC API ODBC driver manager Service provide API Driver for DBMS server DBMS server

Embedded SQL SQL is not a stand-alone programming language SQL statements can be embedded in application programs The incompatibility between the table processing of SQL and record-at-time processing of COBOL is addressed using a cursor

MS Access and SQL Strengths Interface SQL DML Referential integrity Fast execution Views (queries) Updateable views Weaknesses No support for GRANT and REVOKE Domains No support for COMMIT and ROLLBACK Limited concurrency control

The future of SQL One of the most successful standardization stories Highly portable Objects have made standardization more difficult as vendors have added extensions prior to standards setting

SQL-99 Better support for Java and other object-oriented languages Support for multimedia extensions Retention of portability by defining standards for object-oriented extensions to the relational model Enhancements add functionality at the expense of ease of use

User-defined data types May be used in the same way as built-in data types A UDT is defined by Specifying a set of declarations of the stored attributes that represent the value of the UDT The operations that define the equality and ordering relationships of the UDT The operations and derived attributes that represent the behavior of the UDT

SQLJ Simplifies the interface to Java ANSI standard Integration of SQL and Java reinforces the adoption and use of Java for enterprise data-intensive applications A good choice for static SQL programming tasks Use JDBC for dynamic tasks

Key points SQL is a standard It matters little which implementation you use for learning SQL Data definition language (DDL) CREATE TABLE Constraint CREATE INDEX Data manipulation language (DML) SELECT INSERT UPDATE DELETE

Key points SQL routines Function Procedure Triggers Security GRANT REVOKE Connectivity Embedded SQL SQL-99