You are on page 1of 84

7

Chapter 7
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel
1

7

In this chapter, you will learn:
• The basic commands and functions of SQL
• How to use SQL for data administration (to create tables, indexes, and views) • How to use SQL for data manipulation (to add, modify, delete, and retrieve data)

• How to use SQL to query a database to extract useful information
Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

2

7

Introduction to SQL
• SQL functions fit into two broad categories: • Data definition language
– SQL includes commands to create
• Database objects such as tables, indexes, and views • Commands to define access rights to those database objects

• Data manipulation language
– Includes commands to insert, update, delete, and retrieve data within the database tables
Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

3

7

Introduction to SQL (continued)
• SQL is relatively easy to learn
• Basic command set has a vocabulary of less than 100 words

• Nonprocedural language
• American National Standards Institute (ANSI) prescribes a standard SQL • Several SQL dialects exist
Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

4

Rob & Coronel 5 .7 SQL Data Definition Commands Database Systems: Design. & Management. 6th Edition. Implementation.

6th Edition. Rob & Coronel 6 . & Management.7 Data Manipulation Commands Database Systems: Design. Implementation.

Implementation.7 Data Definition Commands • Examine the simple database model and the database tables that will form the basis for the many SQL examples • Understand the data environment Database Systems: Design. 6th Edition. Rob & Coronel 7 . & Management.

6th Edition. Implementation. & Management.7 The Database Model Database Systems: Design. Rob & Coronel 8 .

6th Edition. Rob & Coronel 9 . Implementation. & Management.7 Creating the Database • Two tasks must be completed – create the database structure – create the tables that will hold the end-user data • First task – RDBMS creates the physical files that will hold the database – Tends to differ substantially from one RDBMS to another Database Systems: Design.

Rob & Coronel 10 .7 The Database Schema • Authentication – Process through which the DBMS verifies that only registered users are able to access the database – Log on to the RDBMS using a user ID and a password created by the database administrator • Schema – Group of database objects—such as tables and indexes—that are related to each other Database Systems: Design. 6th Edition. Implementation. & Management.

& Management. Rob & Coronel 11 . Implementation.7 Data Types • Data type selection is usually dictated by the nature of the data and by the intended use • Pay close attention to the expected use of attributes for sorting and data retrieval purposes Database Systems: Design. 6th Edition.

& Management. Rob & Coronel 12 . 6th Edition. Implementation.7 Some Common SQL Data Types Database Systems: Design.

& Management. Implementation. Rob & Coronel 13 . 6th Edition.7 Creating Table Structures • Use one line per column (attribute) definition • Use spaces to line up the attribute characteristics and constraints • Table and attribute names are capitalized • NOT NULL specification • UNIQUE specification • Primary key attributes contain both a NOT NULL and a UNIQUE specification • RDBMS will automatically enforce referential integrity for foreign keys • Command sequence ends with a semicolon Database Systems: Design.

6th Edition. Implementation. & Management.7 Other SQL Constraints • NOT NULL constraint – Ensures that a column does not accept nulls • UNIQUE constraint – Ensures that all values in a column are unique • DEFAULT constraint – Assigns a value to an attribute when a new row is added to a table • CHECK constraint – Validates data when an attribute value is entered Database Systems: Design. Rob & Coronel 14 .

DBMS automatically creates a unique index • Often need additional indexes • Using the CREATE INDEX command. 6th Edition. SQL indexes can be created on the basis of any selected attribute • Composite index – Index based on two or more attributes – Often used to prevent data duplication Database Systems: Design. Implementation. & Management. Rob & Coronel 15 .7 SQL Indexes • When a primary key is declared.

Implementation. 6th Edition. & Management. Rob & Coronel 16 .7 A Duplicated TEST Record Database Systems: Design.

Rob & Coronel 17 .Example Attribute (Field) Name EMP_NUM EMP_LNAME EMP_FNAME EMP_INITIAL Data Declaration INTEGER VARCHAR(15) VARCHAR(15) CHAR(1) EMP_HIREDATE JOB_CODE DATE CHAR(3) Database Systems: Design.7 Creating Table Structures . 6th Edition. Implementation. & Management.

Database Systems: Design. FOREIGN KEY (JOB_CODE) REFERENCES JOB). EMP_HIREDATE DATE. EMP_INITIAL CHAR(1). Implementation. EMP_LNAME VARCHAR(15) NOT NULL. 6th Edition. Rob & Coronel 18 .Example CREATE TABLE EMP( EMP_NUM INTEGER PRIMARY KEY.7 Creating Table Structures . EMP_FNAME VARCHAR(15) NOT NULL. & Management. JOB_CODE CHAR(3) DEFAULT ‘000’.

EMP_FNAME VARCHAR(15) NOT NULL. PRIMARY KEY (EMP_NUM).7 Creating Table Structures . Rob & Coronel 19 . Implementation. EMP_INITIAL CHAR(1). Database Systems: Design. & Management. JOB_CODE CHAR(3) DEFAULT ‘000’. FOREIGN KEY (JOB_CODE) REFERENCES JOB). 6th Edition.Example CREATE TABLE EMP( EMP_NUM INTEGER NOT NULL. EMP_LNAME VARCHAR(15) NOT NULL. CONSTRAINT JAYZSA UNIQUE (EMP_NUM). EMP_HIREDATE DATE.

6th Edition. Rob & Coronel 20 . Implementation. & Management.7 Data Manipulation Commands • Adding table rows • Saving table changes • Listing table rows • Updating table rows • Restoring table contents • Deleting table rows • Inserting table rows with a select subquery Database Systems: Design.

7 Common SQL Data Manipulation Commands Database Systems: Design. Rob & Coronel 21 . Implementation. & Management. 6th Edition.

& Management. Rob & Coronel 22 . Implementation.7 A Data View and Entry Form Database Systems: Design. 6th Edition.

& Management. Rob & Coronel 23 . Implementation. 6th Edition.7 Saving Table Changes • Changes made to table contents are not physically saved on disk until – Database is closed – Program is closed – COMMIT command is used • Syntax – COMMIT [WORK] • Will permanently save any changes made to any table in the database Database Systems: Design.

separated by commas • Asterisk can be used as wildcard character to list all attributes Database Systems: Design.7 Listing Table Rows • SELECT – Used to list contents of table • Syntax – SELECT columnlist FROM tablename • Columnlist represents one or more attributes. Implementation. Rob & Coronel 24 . 6th Edition. & Management.

Rob & Coronel 25 . • If more than one attribute is to be updated in the row. 6th Edition. separate corrections with commas Database Systems: Design.7 Updating Table Rows • UPDATE – Modify data in a table • Syntax – UPDATE tablename SET columnname = expression [. Implementation. & Management. columname = expression] [WHERE conditionlist].

Example Database Systems: Design.7 Updating Table Rows . & Management. Implementation. 6th Edition. Rob & Coronel 26 .

EMP EMP_PCT = 5.00 EMP_NUM = ‘102’. Implementation. Rob & Coronel 27 . Database Systems: Design. & Management. 6th Edition.7 Updating Table Rows . EMP EMP_PCT = 8.Example UPDATE SET WHERE UPDATE SET WHERE UPDATE SET WHERE EMP EMP_PCT = 3.00 EMP_NUM = ‘101’.85 EMP_NUM = '103'.

& Management. modify. 6th Edition.7 Restoring Table Contents • ROLLBACK – Used restore the database to its previous condition – Only applicable if COMMIT command has not been used to permanently store the changes in the database • Syntax – ROLLBACK. or delete table rows Database Systems: Design. Implementation. • COMMIT and ROLLBACK only work with data manipulation commands that are used to add. Rob & Coronel 28 .

all rows from the specified table will be deleted Database Systems: Design. Implementation. • WHERE condition is optional • If WHERE condition is not specified. 6th Edition.7 Deleting Table Rows • DELETE – Deletes a table row • Syntax – DELETE FROM tablename [WHERE conditionlist ]. Rob & Coronel 29 . & Management.

7 Deleting Table Rows – Example DELETE WHERE AND AND AND FROM EMP EMP_LNAME = 'Smithfield' EMP_FNAME = 'William' EMP_HIREDATE = '22-June-02' JOB_CODE = '500'. Rob & Coronel 30 . & Management. Implementation. Database Systems: Design. 6th Edition.

6th Edition. Implementation.7 Inserting Table Rows .Example Database Systems: Design. & Management. Rob & Coronel 31 .

Implementation. ’08-Nov98’. ‘502’). ‘H’. ’12-Jul87’. Rob & Coronel 32 . ‘501’). ‘David’. ‘G’. ‘John’.Example INSERT INTO EMP_1 VALUES (‘101’. ‘News’. ‘Senior’.7 Inserting Table Rows . & Management. INSERT INTO EMP_1 VALUES (‘102’. 6th Edition. Database Systems: Design.

Implementation.7 Inserting Table Rows with a Select Subquery • INSERT – Inserts multiple rows from another table (source) – Uses SELECT subquery • Query that is embedded (or nested) inside another query • Executed first • Syntax – INSERT INTO tablename SELECT columnlist FROM tablename Database Systems: Design. 6th Edition. & Management. Rob & Coronel 33 .

PART_PRICE) SELECT P_CODE. Rob & Coronel 34 . PART_DESCRIPT. & Management. Implementation. Database Systems: Design. 6th Edition.Example INSERT INTO PART (PART_CODE.7 Inserting Table Rows with a Select Subquery . P_DESCRIPT. P_PRICE FROM PRODUCT.

6th Edition.7 Selecting Rows with Conditional Restrictions • Select partial table contents by placing restrictions on rows to be included in output – Add conditional restrictions to the SELECT statement. Implementation. using WHERE clause • Syntax – SELECT columnlist FROM tablelist [ WHERE conditionlist ] . Rob & Coronel 35 . & Management. Database Systems: Design.

Database Systems: Design. & Management.7 Selected PRODUCT Table Attributes for VENDOR Code 21344 SELECT P_DESCRIPT. Rob & Coronel 36 . V_CODE FROM PRODUCT WHERE V_CODE = 21344. P_INDATE. Implementation. 6th Edition. P_PRICE.

Implementation. Rob & Coronel 37 . & Management.7 The Microsoft Access QBE and its SQL Database Systems: Design. 6th Edition.

& Management.7 Comparison Operators Database Systems: Design. 6th Edition. Implementation. Rob & Coronel 38 .

P_INDATE. & Management. Database Systems: Design. Rob & Coronel 39 . V_CODE FROM PRODUCT WHERE V_CODE <> 21344.7 Selected PRODUCT Table Attributes for VENDOR Codes Other than 21344 SELECT P_DESCRIPT. 6th Edition. P_PRICE. Implementation.

Rob & Coronel 40 . P_PRICE FROM PRODUCT WHERE P_PRICE <= 10. 6th Edition.7 Selected PRODUCT Table Attributes with a P_PRICE Restriction SELECT P_DESCRIPT. Database Systems: Design. P_ONHAND. Implementation. & Management. P_MIN.

6th Edition. P_MIN. & Management.7 Selected PRODUCT Table Attributes: The ASCII Code Effect SELECT P_CODE. P_DESCRIPT. P_ONHAND. P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558QW1’. Database Systems: Design. Rob & Coronel 41 . Implementation.

6th Edition. Implementation. P_ONHAND. Database Systems: Design. Rob & Coronel 42 . P_INDATE FROM PRODUCT WHERE P_INDATE >= ’20 – Jan – 2004’.7 Selected PRODUCT Table Attributes: Date Restriction SELECT P_DESCRIPT. P_PRICE. P_MIN. & Management.

P_ONHAND. & Management. Rob & Coronel 43 . P_ONHAND * P_PRICE FROM PRODUCT. Implementation. Database Systems: Design. 6th Edition. P_PRICE.7 SELECT Statement with a Computed Column SELECT P_DESCRIPT.

P_PRICE. P_ONHAND. 6th Edition.7 SELECT Statement with a Computed Column and an Alias SELECT P_DESCRIPT. Implementation. & Management. Rob & Coronel 44 . P_ONHAND * P_PRICE AS TOTVALUE FROM PRODUCT. Database Systems: Design.

& Management. Implementation. 6th Edition. Rob & Coronel 45 .7 Arithmetic Operators: The Rule of Precedence • Perform operations within parentheses • Perform power operations • Perform multiplications and divisions • Perform additions and subtractions Database Systems: Design.

P_PRICE.7 Selected PRODUCT Table Attributes: The Logical OR SELECT P_DESCRIPT. V_CODE FROM PRODUCT WHERE V_CODE = 21344 OR V_CODE = 24288. & Management. Database Systems: Design. Implementation. Rob & Coronel 46 . P_INDATE. 6th Edition.

7

Selected PRODUCT Table Attributes: The Logical AND

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE PRICE < 50 AND P_INDATE > ’15 – Jan – 2004’;

Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

47

7

Selected PRODUCT Table Attributes: The Logical AND and OR

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE (P_PRICE < 50 AND P_INDATE > ’15 – Jan – 2004’) OR V_CODE = 24288;

Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

48

7

Special Operators
• BETWEEN
– Used to check whether attribute value is within a range

• IS NULL
– Used to check whether attribute value is null

• LIKE
– Used to check whether attribute value matches a given string pattern

• IN
– Used to check whether attribute value matches any value within a value list

• EXISTS
– Used to check if a subquery returns any rows
Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

49

7

Advanced Data Definition Commands
• All changes in the table structure are made by using the ALTER command
– Followed by a keyword that produces specific change – Three options are available
• ADD

• MODIFY
• DROP
Database Systems: Design, Implementation, & Management, 6th Edition, Rob & Coronel

50

& Management. 6th Edition. Implementation. Rob & Coronel 51 .7 Changing a Column’s Data Type • ALTER can be used to change data type • Some RDBMSs (such as Oracle) do not permit changes to data types unless the column to be changed is empty Database Systems: Design.

7 Changing a Column’s Data Characteristics • Use ALTER to change data characteristics • If the column to be changed already contains data. changes in the column’s characteristics are permitted if those changes do not alter the data type Database Systems: Design. & Management. Implementation. 6th Edition. Rob & Coronel 52 .

7 Adding or Dropping a Column • Use ALTER to add a column – Do not include the NOT NULL clause for new column • Use ALTER to drop a column – Some RDBMSs impose restrictions on the deletion of an attribute Database Systems: Design. Implementation. Rob & Coronel 53 . & Management. 6th Edition.

Implementation. Rob & Coronel 54 . & Management.7 The Effect of Data Entry into the New P_SALECODE Column UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_CODE = ‘1546-QQ2’. Database Systems: Design. 6th Edition.

Database Systems: Design. Rob & Coronel 55 .7 Update of the P_SALECODE Column in Multiple Data Rows UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_CODE = ‘2232/QWE’ OR P_CODE = ‘2232/QTY’. & Management. 6th Edition. Implementation.

AND P_INDATE <= ’10-Feb-2004’. UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_INDATE >= ’16-Jan-2004’. Rob & Coronel 56 . Database Systems: Design.7 The Effect of Multiple Data Updates in the PRODUCT Table (MS Access) UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_INDATE < ’25-Dec-2003’. Implementation. & Management. 6th Edition.

Implementation. Rob & Coronel 57 . 6th Edition. & Management.7 Copying Parts of Tables • SQL permits copying contents of selected table columns so that the data need not be reentered manually into newly created table(s) • First create the PART table structure • Next add rows to new PART table using PRODUCT table rows Database Systems: Design.

PART_PRICE) SELECT P_CODE. Implementation. 6th Edition. Database Systems: Design. P_DESCRIPT. P_PRICE FROM PRODUCT. Rob & Coronel 58 .7 PART Attributes Copied from the PRODUCT Table INSERT INTO PART (PART_CODE. PART_DESCRIPT. & Management.

Rob & Coronel 59 . 6th Edition. & Management. Implementation.7 Advanced Select Queries • SQL provides useful functions – Count – Find minimum and maximum values – Calculate averages • SQL allows the user to limit queries to only those entries having no duplicates or entries whose duplicates may be grouped Database Systems: Design.

Rob & Coronel 60 . & Management. P_INDATE. P_PRICE FROM PRODUCT ORDER BY P_PRICE. 6th Edition. Database Systems: Design. Implementation. P_DESRIPT.7 Selected PRODUCT Table Attributes: Ordered by (Ascending) P_PRICE SELECT P_CODE.

& Management. Rob & Coronel 61 .7 Partial Listing of EMPLOYEE Table Contents Database Systems: Design. 6th Edition. Implementation.

EMP_INITIAL. 6th Edition. EMP_FNAME.7 Telephone List Query Results SELECT EMP_LNAME. Implementation. EMP_PHONE FROM EMPLOYEE ORDER BY EMP_LNAME. Rob & Coronel 62 . Database Systems: Design. EMP_INITIAL. EMP_LNAME. & Management. EMP_AREACODE. EMP_FNAME.

& Management. Rob & Coronel 63 .00 ORDER BY V_CODE. Database Systems: Design.7 A Query Based on Multiple Restrictions SELECT P_DESCRIPT. P_INDATE. P_PROCE FROM PRODUCT WHERE P_INDATE < ’21Jan-2004’ AND P_PRICE <= 50. V_CODE. P_PROCE DESC. 6th Edition. Implementation.

7 A Listing of Distinct (Different) V_CODE Values in the PRODUCT Table SELECT DISTINCT V_CODE FROM PRODUCT. Rob & Coronel 64 . 6th Edition. & Management. Database Systems: Design. Implementation.

& Management.7 Some Basic SQL Aggregate Functions Database Systems: Design. Rob & Coronel 65 . Implementation. 6th Edition.

& Management.7 COUNT Function Output Examples Database Systems: Design. Implementation. 6th Edition. Rob & Coronel 66 .

6th Edition. & Management. Implementation. Rob & Coronel 67 .7 MAX and MIN Function Output Examples Database Systems: Design.

7 The Total Value of All Items in the PRODUCT Table Database Systems: Design. Rob & Coronel 68 . Implementation. 6th Edition. & Management.

7 AVG Function Output Examples Database Systems: Design. Implementation. 6th Edition. Rob & Coronel 69 . & Management.

7 GROUP BY Clause Output Examples Database Systems: Design. 6th Edition. Rob & Coronel 70 . Implementation. & Management.

7 Incorrect and Correct Use of the GROUP BY Clause Database Systems: Design. Implementation. & Management. Rob & Coronel 71 . 6th Edition.

7 An Application of the HAVING Clause Database Systems: Design. 6th Edition. Implementation. Rob & Coronel 72 . & Management.

7 Joining Database Tables • Ability to combine (join) tables on common attributes is most important distinction between a relational database and other databases • Join is performed when data are retrieved from more than one table at a time • Join is generally composed of an equality comparison between the foreign key and the primary key of related tables Database Systems: Design. 6th Edition. & Management. Rob & Coronel 73 . Implementation.

7 Creating Links Through Foreign Keys Database Systems: Design. 6th Edition. Rob & Coronel 74 . & Management. Implementation.

P_PRICE. Rob & Coronel 75 .V_CODE. VENDOR. VENDOR WHERE PRODUCT. VENDOR.V_NAME.V_AREACODE.V_PHONE FROM PRODUCT.7 The Results of a Join SELECT PRODUCT. Database Systems: Design.V_CODE = VENDOR. VENDOR. VENDOR.V_CONTACT. PRODUCT. 6th Edition. Implementation. & Management.P_DESCRIPT.

V_NAME.7 An Ordered and Limited Listing After a JOIN SELECT P_DESCRIPT. P_PRICE. 6th Edition. & Management.V_CODE = VENDOR. V_PHONE FROM PRODUCT. VENDOR WHERE PRODUCT. Database Systems: Design. V_AREACODE. Rob & Coronel 76 . Implementation. V_CONTACT.V_CODE AND P_INDATE > ’15-Jan2004’.

& Management. 6th Edition. Rob & Coronel 77 . Implementation.7 The Contents of the EMP Table Database Systems: Design.

EMP_LNAME.EMP_NUM.EMP_MGR = M. M.EMP_NUM ORDER BY E. Rob & Coronel 78 . & Management.EMP_MGR.EMP_MGR.EMP_LNAME. FROM EMP E.7 Using an Alias to Join a Table to Itself SELECT E. EMP M WHERE E. E. E. Database Systems: Design. Implementation. 6th Edition.

7 Converting an ER Model into a Database Structure • Requires following specific rules that govern such a conversion • Decisions made by the designer to govern data integrity are reflected in the foreign key rules • Implementation decisions vary according to the problem being addressed Database Systems: Design. 6th Edition. Implementation. Rob & Coronel 79 . & Management.

& Management. 6th Edition. Rob & Coronel 80 . Implementation.7 The Ch06_Artist Database ERD and Tables Database Systems: Design.

7 A Data Dictionary for the Ch06_Artist Database Database Systems: Design. Implementation. & Management. Rob & Coronel 81 . 6th Edition.

Rob & Coronel 82 . 6th Edition. & Management.7 A Summary of Foreign Key Rules Database Systems: Design. Implementation.

& Management. indexes.7 Summary • SQL commands can be divided into two overall categories: – Data definition language commands – Data manipulation language commands • Basic data definition commands allow you to create tables. Implementation. and views • Many SQL constraints can be used with columns • Aggregate functions – Special functions that perform arithmetic computations over a set of rows Database Systems: Design. Rob & Coronel 83 . 6th Edition.

& Management. Rob & Coronel 84 . Implementation.7 Summary (continued) • ORDER BY clause – Used to sort output of a SELECT statement – Can sort by one or more columns and use either an ascending or descending order • Join output of multiple tables with SELECT statement • Natural join uses join condition to match only rows with equal values in specified columns • Right outer join and left outer join used to select rows that have no matching values in other related table Database Systems: Design. 6th Edition.