Chapter 3

Structured Query Language (SQL)

Introduction to SQL
• SQL functions fit into two broad categories:
1. 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
2

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
3

SQL Data Definition Commands

4

Data Manipulation Commands

5

Data Definition Commands
• Examine the simple database model (Figure 6.1) and the database tables that will form the basis for the many SQL examples • Understand the data environment

6

The Database Model

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
8

Creating Database Structures
CREATE DATABASE <database name>; • Example:
– CREATE DATABASE SAMPLE1;

9

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

10

Some Common SQL Data Types
Data Type Format Description

Numeric

INTEGER

SMALLINT DECIMAL (L,D) Characte CHAR(L) r

-2 147 483 648 +2 147 483 647 -32 768 32 767 DECIMAL(5,2) 123.45 CHAR(5)
If ‘Ali’, database keeps ‘Ali__’ 2 space wasted.

VARCHAR( VARCHAR(5) L) If ‘Ali’, database keeps 3 space
only.

Date

DATE

Year 0001 – 9999 Month 01 –12 Day 01 - 31

11

Some Common SQL Data Types

12

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
13

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
14

SQL Indexes
• When a primary key is declared, DBMS automatically creates a unique index • Often need additional indexes • Using the CREATE INDEX command, 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
15

Creating Table Structures
CREATE TABLE <table name>( <attribute1 name and attribute1 characteristics, attribute2 name and attribute2 characteristics, attribute3 name and attribute3 characteristics, primary key designation, foreign key designation and foreign key requirements>); • Example:
CREATE TABLE VENDOR (v_code varchar(5) not null primary key, v_name varchar(20), v_contact varchar(15), v_areacode integer, v_phone varchar(10), v_state char(2), v_order Char(1));
16

Creating Table Structures
• Example:
CREATE TABLE PRODUCT( (p_code varchar(10) not null primary key,
p_descript varchar(50), p_indate date, p_onhand integer, p_min integer, p_price decimal(5,2), p_discount decimal (3,2), v_code varchar(5), foreign key (v_code) references vendor on delete restrict);

17

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
18

Common SQL Data Manipulation Commands

19

A Data View and Entry Form

20

Inserting Table Rows
• Data Entry
INSERT INTO <table name> VALUES (attribute 1 value, attribute 2 value, … etc.);

Examples:
– INSERT INTO VENDOR VALUES(‘21225, ’Bryson, Inc.’, ’Smithson’, ’615’, ’223-3234’, ’TN’, ’Y’); – INSERT INTO PRODUCT VALUES(‘11 QER/31’, ’Power painter’, ‘15 psi.’, ‘3-nozzle’, ’07-021999’, 8.5, 109.99, 0.00, 25595);

21

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 [table names] – Example: COMMIT PRODUCT;

• Will permanently save any changes made to any table in the database.

22

Listing Table Rows
• SELECT
– Used to list contents of table

• Syntax
– SELECT columnlist FROM tablename

• Columnlist represents one or more attributes, separated by commas • Asterisk can be used as wildcard character to list all attributes
23

Listing Table Rows
• Examples:
SELECT * FROM PRODUCT; SELECT P_CODE, P_DESCRIPT, P_INDATE, P_ONHAND, P_MIN, P-PRICE, P_DISCOUNT, V_CODE FROM PRODUCT;

24

Updating Table Rows
• UPDATE
– Modify data in a table

• Syntax
– UPDATE tablename SET columnname = expression [, columname = expression] [WHERE conditionlist]; – Examples:
UPDATE PRODUCT SET P_INDATE = ‘12/11/96’ WHERE P_CODE = ‘13-Q2/P2’;

• If more than one attribute is to be updated in the row, separate corrections with commas.
– Examples:
UPDATE PRODUCT SET P_INDATE = ‘12/11/96’, P_PRICE = 15.99, P_MIN=10 WHERE P_CODE = ‘13-Q2/P2’; 25

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;

• COMMIT and ROLLBACK only work with data manipulation commands that are used to add, 26 modify, or delete table rows

Deleting Table Rows
• DELETE
– Deletes a table row

• Syntax
– DELETE FROM tablename [WHERE conditionlist ];

– Examples:
• DELETE FROM PRODUCT WHERE P_CODE = ‘2238/QPD’; • DELETE FROM PRODUCT WHERE P_MIN = 5;

• WHERE condition is optional • If WHERE condition is not specified, all rows from the specified table will be deleted.
27

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
28

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, using WHERE clause

• Syntax
– SELECT columnlist FROM tablelist [ WHERE conditionlist ] ;
29

Selected PRODUCT Table Attributes for VENDOR Code 21344
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE = 21344;

30

Comparison Operators

31

Selected PRODUCT Table Attributes for VENDOR Codes Other than 21344
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344;

32

Selected PRODUCT Table Attributes with a P_PRICE Restriction
SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_PRICE <= 10;

33

Selected PRODUCT Table Attributes: The ASCII Code Effect
SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558-QW1’;

34

Selected PRODUCT Table Attributes: Date Restriction
SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE, P_INDATE FROM PRODUCT WHERE P_INDATE >= ’20-Jan-2004;

35

SELECT Statement with a Computed Column
SELECT P_DESCRIPT, P_ONHAND, P_PRICE, P_ONHAND* P_PRICE FROM PRODUCT;

36

SELECT Statement with a Computed Column and an Alias
SELECT P_DESCRIPT, P_ONHAND, P_PRICE, P_ONHAND* P_PRICE AS TOTAL VALUE FROM PRODUCT;

37

Arithmetic Operators: The Rule of Precedence
Arithmetic Operator + * / ^ Description Add Substract Multiply Divide Raise to the power of (Some applications use ** instead of ^. Table 6.9 The Arithmetic Operators

38

Arithmetic Operators: The Rule of Precedence
• Perform operations within parentheses • Perform power operations • Perform multiplications and divisions • Perform additions and subtractions

39

Selected PRODUCT Table Attributes: The Logical OR
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE = 21344 OR V_CODE = 24288;

40

Selected PRODUCT Table Attributes: The Logical AND
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE < 50 AND P_INDATE > ’15-Jan-2004’;

41

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_DATE > ’15-Jan-2004’) OR V_CODE = 24288;

42

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
43

Special Operators
• • BETWEEN is used to define range limits. Examples:
SELECT * FROM PRODUCT WHERE P_PRICE BETWEEN 50.00 AND 100.00;

SELECT * FROM PRODUCT WHERE P_PRICE > 50.00 AND P_PRICE < 100.00;
44

Special Operators
• IS NULL is used to check whether an attribute value is null.
Examples:
SELECT P_CODE, P_DESCRIPT, V_CODE FROM PRODUCT WHERE V_CODE IS NULL;

SELECT P_CODE, P_DESCRIPT, P_INDATE FROM PRODUCT WHERE P_INDATE IS NULL;

45

Special Operators
• LIKE is used to check for similar character strings. • Examples:
SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM VENDOR WHERE V_CONTACT LIKE ‘Smith%’;

SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM VENDOR WHERE V_CONTACT LIKE ‘SMITH%’;

46

Special Operators
• IN is used to check whether an attribute value matches a value contained within a (sub)set of listed values.
SELECT * FROM PRODUCT WHERE V_CODE IN (21344, 24288);

• EXISTS is used to check whether an attribute has value.
DELETE FROM PRODUCT WHERE P_CODE EXISTS; SELECT * FROM PRODUCT WHERE V_CODE EXISTS;
47

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
48

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

49

Changing a Column’s Data Characteristics
• Use ALTER to change data characteristics
– ALTER TABLE <table name> MODIFY (<column name> <new column 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 • Examples:

– –

Changing a Column’s Data Type
ALTER TABLE PRODUCT MODIFY (V_CODE CHAR(5));

Changing Attribute Characteristics ALTER TABLE PRODUCT MODIFY (P_PRICEDECIMAL(9,2)); Adding a New Column to the Table ALTER TABLE PRODUCT ADD (P_SALECODE CHAR(1));

50

The Effect of Data Entry into the New P_SALECODE Column
UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_CODE = ‘1546-QQ2’;

51

Update of the P_SALECODE Column in Multiple Data Rows
UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_CODE IN (‘2232/QWE’, ‘2232/QTY’);

52

The Effect of Multiple Data Updates in the PRODUCT Table (MS Access)
UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_INDATE < ’25-Dec-2003’; UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_INDATE >= 16-Jan-2004’ AND P_INDATE < ’10-Feb-2004’;
53

The Effect of Multiple Data Updates in the PRODUCT Table (MS Access)

54

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
55

PART Attributes Copied from the PRODUCT Table
CREATE TABLE PART ( PART_CODE CHAR(8) NOT NULL, PART_DESCRIPT CHAR(35), PART_PRICE DECIMAL(8,2), PRIMARY KEY(PART_CODE)); INSERT INTO PART ( PART_CODE, PART_DESCRIPT, PART_PRICE) SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT;
56

PART Attributes Copied from the PRODUCT Table

57

Adding or Dropping a Column
• Use ALTER to add a column
– Do not include the NOT NULL clause for new column – Examples:
ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE); ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR; ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE) ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR;

58

Adding or Dropping a Column
• Use ALTER to drop a column • Some RDBMSs impose restrictions on the deletion of an attribute • DROP TABLE <table name>; • Example:
DROP TABLE PART;
59

References
• ROB, P. AND CORONEL, C., 2004, Database Systems. 6th Ed., Thomson Course Technology

60

Sign up to vote on this title
UsefulNot useful