0% found this document useful (0 votes)
217 views67 pages

Chapter 7 PDF

The document provides an introduction to Structured Query Language (SQL) and database design. It discusses the two main categories of SQL functions: data definition language (DDL) for creating and modifying database objects and data manipulation language (DML) for inserting, updating, deleting, and retrieving data. The document uses examples to demonstrate how to create tables with constraints, indexes, and relationships between tables. It also provides examples of DML commands for inserting, selecting, updating, deleting rows and committing or rolling back changes to the database.

Uploaded by

osama malloh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
217 views67 pages

Chapter 7 PDF

The document provides an introduction to Structured Query Language (SQL) and database design. It discusses the two main categories of SQL functions: data definition language (DDL) for creating and modifying database objects and data manipulation language (DML) for inserting, updating, deleting, and retrieving data. The document uses examples to demonstrate how to create tables with constraints, indexes, and relationships between tables. It also provides examples of DML commands for inserting, selecting, updating, deleting rows and committing or rolling back changes to the database.

Uploaded by

osama malloh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Database Design and Programming

Dr.Amjad Hawash
An-Najah National University
Database Design and Programming

Chapter 7
Introduction to Structured Query Language (SQL)
7.1 INTRODUCTION TO SQL


SQL functions fit into two broad categories:
– data definition language (DDL): SQL includes
commands to create database objects such as tables,
indexes, and views, as well as commands to define
access rights to those database objects.
7.1 INTRODUCTION TO SQL
7.1 INTRODUCTION TO SQL


data manipulation language (DML): SQL includes
commands to insert, update, delete, and retrieve data
within the database tables.
7.1 INTRODUCTION TO SQL
7.2 DATA DEFINITION COMMANDS


let’s first examine the simple database model and the
database tables that will form the basis for the many SQL
examples you’ll explore in this chapter.
7.2.1 The Database Model
7.2.1 The Database Model


The database model in Figure 7.1 reflects the following business rules:

A customer may generate many invoices. Each invoice is generated by one
customer.

An invoice contains one or more invoice lines. Each invoice line is associated with
one invoice.

Each invoice line references one product. A product may be found in many invoice
lines. (You can sell more than one hammer to more than one customer.)

A vendor may supply many products. Some vendors do not (yet?) supply
products. (For example, a vendor list may include potential vendors.)

If a product is vendor-supplied, that product is supplied by only a single vendor.

Some products are not supplied by a vendor. (For example, some products may
be produced in-house or bought on the open market.)
7.2.1 The Database Model
7.2.1 The Database Model
7.2.2 Creating the Database


Two tasks:
– create the database structure (physical files, data
dictionary tables – metadata)
– create the tables that will hold the end-user data (real
data).
7.2.3 The Database Schema


A schema is a group of database objects—such as tables
and indexes—that are related to each other.
– CREATE SCHEMA AUTHORIZATION JONES;

For most RDBMSs, the CREATE SCHEMA
AUTHORIZATION is optional.
7.2.4 Data Types
7.2.4 Data Types
7.2.5 Creating Table Structures


CREATE TABLE tablename (
column1 data type [constraint] [,
column2 data type [constraint] ] [,
PRIMARY KEY (column1 [, column2]) ] [,
FOREIGN KEY (column1 [, column2]) REFERENCES
tablename] [,CONSTRAINT constraint ] );
7.2.5 Creating Table Structures


CREATE TABLE VENDOR (
V_CODE INTEGER NOT NULL UNIQUE,
V_NAME VARCHAR(35) NOT NULL,
V_CONTACT VARCHAR(15) NOT NULL,
V_AREACODE CHAR(3) NOT NULL,
V_PHONE CHAR(8) NOT NULL,
V_STATE CHAR(2) NOT NULL,
V_ORDER CHAR(1) NOT NULL,
PRIMARY KEY (V_CODE));
7.2.5 Creating Table Structures


CREATE TABLE PRODUCT (
P_CODE VARCHAR(10) NOT NULL UNIQUE,
P_DESCRIPT VARCHAR(35) NOT NULL,
P_INDATE DATE NOT NULL,
P_QOH SMALLINT NOT NULL,
P_MIN SMALLINT NOT NULL,
P_PRICE NUMBER(8,2) NOT NULL,
P_DISCOUNT NUMBER(5,2) NOT NULL,
V_CODE INTEGER,
PRIMARY KEY (P_CODE),
FOREIGN KEY (V_CODE) REFERENCES VENDOR ON UPDATE CASCADE);
7.2.6 SQL Constraints


PRIMARY KEY (V_CODE)

That foreign key constraint definition ensures that:
– You cannot delete a vendor from the VENDOR table if
at least one product row references that vendor. This is
the default behavior for the treatment of foreign keys.
– On the other hand, if a change is made in an existing
VENDOR table’s V_CODE, that change must be
reflected automatically in any PRODUCT table
V_CODE reference (ON UPDATE CASCADE).
7.2.6 SQL Constraints


Besides the PRIMARY KEY and FOREIGN KEY constraints, the ANSI SQL
standard also defines the following constraints:

The NOT NULL constraint ensures that a column does not accept nulls.

The UNIQUE constraint ensures that all values in a column are unique.

The DEFAULT constraint assigns a value to an attribute when a new row is added
to a table. The end user may, of course, enter a value other than the default value.

The CHECK constraint is used to validate data when an attribute value is entered.
The CHECK constraint does precisely what its name suggests: it checks to see
that a specified condition exists.

Examples of such constraints include the following:

- The minimum order value must be at least 10.

- The date must be after April 15, 2010.
7.2.6 SQL Constraints


CREATE TABLE CUSTOMER (
CUS_CODE NUMBER PRIMARY KEY,
CUS_LNAME VARCHAR(15) NOT NULL,
CUS_FNAME VARCHAR(15) NOT NULL,
CUS_INITIAL CHAR(1),
CUS_AREACODE CHAR(3) DEFAULT '615' NOT NULL
CHECK(CUS_AREACODE IN ('615','713','931')),
CUS_PHONE CHAR(8) NOT NULL,
CUS_BALANCE NUMBER(9,2) DEFAULT 0.00,
CONSTRAINT CUS_UI1 UNIQUE (CUS_LNAME, CUS_FNAME));
7.2.6 SQL Constraints


CREATE TABLE INVOICE (
INV_NUMBER NUMBER PRIMARY KEY,
CUS_CODE NUMBER NOT NULL REFERENCES
CUSTOMER(CUS_CODE),
INV_DATE DATE DEFAULT SYSDATE NOT NULL,
CONSTRAINT INV_CK1 CHECK (INV_DATE >
TO_DATE('01-JAN-2010','DD-MON-YYYY')));
7.2.6 SQL Constraints


CREATE TABLE LINE (
INV_NUMBER NUMBER NOT NULL,
LINE_NUMBER NUMBER(2,0) NOT NULL,
P_CODE VARCHAR(10) NOT NULL,
LINE_UNITS NUMBER(9,2) DEFAULT 0.00 NOT NULL,
LINE_PRICE NUMBER(9,2) DEFAULT 0.00 NOT NULL,
PRIMARY KEY (INV_NUMBER, LINE_NUMBER),
FOREIGN KEY (INV_NUMBER) REFERENCES INVOICE ON DELETE
CASCADE,
FOREIGN KEY (P_CODE) REFERENCES PRODUCT(P_CODE),
CONSTRAINT LINE_UI1 UNIQUE(INV_NUMBER, P_CODE));
7.2.7 SQL Indexes


CREATE [UNIQUE] INDEX indexname ON
tablename(column1 [, column2])
CREATE INDEX P_INDATEX ON PRODUCT(P_INDATE);

A common practice is to create an index on any field that is
used as a search key, in comparison operations in a
conditional expression, or when you want to list rows in a
specific order.
7.2.7 SQL Indexes


Such duplication could have been avoided through the use
of a unique composite index, using the attributes

EMP_NUM, TEST_CODE, and TEST_DATE: CREATE
UNIQUE INDEX EMP_TESTDEX ON TEST(EMP_NUM,
TEST_CODE, TEST_DATE);

CREATE INDEX PROD_PRICEX ON
PRODUCT(P_PRICE DESC);

DROP INDEX indexname

DROP INDEX PROD_PRICEX;
7.3 DATA MANIPULATION
COMMANDS

In this section, you will learn how to use the basic SQL
data manipulation commands INSERT, SELECT, COMMIT,
UPDATE, ROLLBACK, and DELETE.
7.3.1 Adding Table Rows


INSERT INTO tablename VALUES (value1, value2, ... ,
valuen)

INSERT INTO VENDOR VALUES (21225,'Bryson,
Inc.','Smithson','615','223-3234','TN','Y');

INSERT INTO VENDOR VALUES (21226,'Superloo,
Inc.','Flushing','904','215-8995','FL','N');

INSERT INTO PRODUCT VALUES ('11QER/31','Power
painter, 15 psi., 3-nozzle','03-Nov-09',8,5,109.99,0.00,25595);

INSERT INTO PRODUCT VALUES ('13-Q2/P2','7.25-in. pwr.
saw blade','13-Dec-09',32,15,14.99, 0.05, 21344);
Inserting Rows with Null Attributes


INSERT INTO PRODUCT VALUES ('BRT-345','Titanium
drill bit','18-Oct-09', 75, 10, 4.50, 0.06, NULL);
Inserting Rows with Optional
Attributes

INSERT INTO PRODUCT(P_CODE, P_DESCRIPT)
VALUES ('BRT-345','Titanium drill bit');
7.3.2 Saving Table Changes


COMMIT;
7.3.3 Listing Table Rows


The SELECT command is used to list the contents of a
table.

The syntax of the SELECT command is as follows:
SELECT columnlist FROM tablename
7.3.4 Updating Table Rows


UPDATE tablename SET columnname = expression [,
columnname = expression] [WHERE conditionlist ];
7.3.5 Restoring Table Contents


If you have not yet used the COMMIT command to store
the changes permanently in the database, you can restore
the database to its previous condition with the ROLLBACK
command.


Rollback;
7.3.6 Deleting Table Rows


DELETE FROM tablename [WHERE conditionlist ];
7.3.7 Inserting Table Rows with a
Select Subquery

INSERT INTO tablename SELECT columnlist FROM
tablename;

A subquery, also known as a nested query or an inner
query, is a query that is embedded (or nested) inside
another query.

7.4 SELECT QUERIES


In this section, you will learn how to fine-tune the SELECT
command by adding restrictions to the search criteria.
7.4.1 Selecting Rows with
Conditional Restrictions

SELECT columnlist FROM tablelist [WHERE conditionlist ];
7.4.1 Selecting Rows with
Conditional Restrictions

SELECT columnlist FROM tablelist [WHERE conditionlist ];

Using Comparison Operators on Character Attributes

Using Comparison Operators on Dates

SELECT P_DESCRIPT, P_QOH, P_PRICE, P_QOH *
P_PRICE FROM PRODUCT;
7.4.1 Selecting Rows with
Conditional Restrictions

SELECT P_DESCRIPT, P_QOH, P_PRICE, P_QOH *
P_PRICE AS TOTVALUE FROM PRODUCT;

SELECT P_CODE, P_INDATE, DATE() - 90 AS

CUTDATE FROM PRODUCT WHERE P_INDATE <=
DATE() - 90;
7.4.2 Arithmetic Operators: The Rule
of Precedence
7.4.3 Logical Operators: AND, OR,
and NOT

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE
FROM PRODUCT WHERE (P_PRICE < 50 AND
P_INDATE > '15-Jan-2010') OR V_CODE = 24288;


SELECT * FROM PRODUCT WHERE NOT (V_CODE =
21344);
7.4.4 Special Operators


BETWEEN: Used to check whether an attribute value is
within a range

IS NULL: Used to check whether an attribute value is null

LIKE: Used to check whether an attribute value matches a
given string pattern

IN: Used to check whether an attribute value matches any
value within a value list

EXISTS: Used to check whether a subquery returns any
rows
7.4.4 Special Operators


SELECT * FROM PRODUCT WHERE P_PRICE
BETWEEN 50.00 AND 100.00;

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

SELECT V_NAME, V_CONTACT, V_AREACODE,
V_PHONE FROM VENDOR WHERE V_CONTACT LIKE
'Smith%';
7.4.4 Special Operators


SELECT * FROM PRODUCT WHERE P_PRICE
BETWEEN 50.00 AND 100.00;

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

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
UPPER(V_CONTACT) LIKE 'SMITH%';
7.4.4 Special Operators


SELECT V_NAME, V_CONTACT, V_AREACODE,
V_PHONE FROM VENDOR WHERE V_CONTACT NOT
LIKE 'Smith%';

SELECT * FROM PRODUCT WHERE V_CODE IN
(21344, 24288);

SELECT V_CODE, V_NAME FROM VENDOR WHERE
V_CODE IN (SELECT V_CODE FROM PRODUCT);
7.4.4 Special Operators


SELECT * FROM VENDOR WHERE EXISTS (SELECT *
FROM PRODUCT WHERE P_QOH <= P_MIN);

The EXISTS special operator can be used whenever there
is a requirement to execute a command based on the
result of another query.

That is, if a subquery returns any rows, run the main
query; otherwise, don’t.
7.5 ADDITIONAL DATA DEFINITION
COMMANDS

ALTER TABLE tablename {ADD | MODIFY} ( columnname
datatype [ {ADD | MODIFY} columnname datatype] ) ;

ALTER TABLE tablename ADD constraint [ ADD constraint
];

ALTER TABLE tablename DROP{PRIMARY KEY |
COLUMN columnname | CONSTRAINT constraintname };
7.5.1 Changing a Column’s Data
Type

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

ALTER TABLE PRODUCT MODIFY (P_PRICE
DECIMAL(9,2));
7.5.3 Adding a Column


ALTER TABLE PRODUCT ADD (P_SALECODE
CHAR(1));
7.5.4 Dropping a Column


ALTER TABLE VENDOR DROP COLUMN V_ORDER;
7.5.5 Advanced Data Updates


UPDATE PRODUCT SET P_SALECODE = '2' WHERE
P_CODE = '1546-QQ2';

UPDATE PRODUCT SET P_SALECODE = '1' WHERE
P_CODE IN ('2232/QWE', '2232/QTY');

UPDATE PRODUCT SET P_SALECODE = '1' WHERE
P_CODE = '2232/QWE' OR P_CODE = '2232/QTY';

SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE,
P_SALECODE FROM PRODUCT;

UPDATE PRODUCT SET P_QOH = P_QOH + 20 WHERE
P_CODE = '2232/QWE';
7.5.6 Copying Parts of Tables


CREATE TABLE PART AS SELECT P_CODE AS
PART_CODE, P_DESCRIPT AS PART_DESCRIPT,
P_PRICE AS PART_PRICE, V_CODE FROM PRODUCT;
7.5.7 Adding Primary and Foreign
Key Designations

ALTER TABLE PART ADD PRIMARY KEY (PART_CODE);

ALTER TABLE PART ADD FOREIGN KEY (V_CODE)
REFERENCES VENDOR;

ALTER TABLE PART ADD PRIMARY KEY (PART_CODE)
ADD FOREIGN KEY (V_CODE) REFERENCES
VENDOR;
7.5.8 Deleting a Table from the
Database

DROP TABLE PART;
7.6 ADDITIONAL SELECT QUERY
KEYWORDS

One of the most important advantages of SQL is its ability
to produce complex free-form queries.
7.6.1 Ordering a Listing


SELECT columnlist FROM tablelist [WHERE conditionlist ]
[ORDER BY columnlist [ASC | DESC] ] ;

SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE
FROM PRODUCT ORDER BY P_PRICE;

SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE
FROM PRODUCT ORDER BY P_PRICE DESC;

SELECT EMP_LNAME, EMP_FNAME, EMP_INITIAL,
EMP_AREACODE, EMP_PHONE FROM EMPLOYEE
ORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL;
7.6.2 Listing Unique Values


SELECT DISTINCT V_CODE FROM PRODUCT;
7.6.3 Aggregate Functions
7.6.3 Aggregate Functions


SELECT COUNT(*) FROM (SELECT DISTINCT V_CODE
FROM PRODUCT WHERE V_CODE IS NOT NULL)

SELECT P_CODE, P_DESCRIPT, P_PRICE FROM
PRODUCT WHERE P_PRICE = (SELECT
MAX(P_PRICE) FROM PRODUCT);

SELECT SUM(CUS_BALANCE) AS TOTBALANCE FROM
CUSTOMER;
7.6.4 Grouping Data


SELECT columnlist
FROM tablelist
[WHERE conditionlist ]
[GROUP BY columnlist ]
[HAVING conditionlist ]
[ORDER BY columnlist [ASC | DESC] ] ;
7.6.4 Grouping Data


SELECT V_CODE, P_CODE, P_DESCRIPT, P_PRICE
FROM PRODUCT
GROUP BY V_CODE;

SELECT V_CODE, SUM(P_QOH * P_PRICE) AS TOTCOST
FROM PRODUCT
GROUP BY V_CODE
HAVING (SUM(P_QOH * P_PRICE) > 500)
ORDER BY SUM(P_QOH * P_PRICE) DESC;
7.7 VIRTUAL TABLES: CREATING A
VIEW

CREATE VIEW viewname AS SELECT query

CREATE VIEW PROD_STATS AS
SELECT V_CODE, SUM(P_QOH*P_PRICE) AS
TOTCOST,
MAX(P_QOH) AS MAXQTY, MIN(P_QOH) AS MINQTY,
AVG(P_QOH) AS AVGQTY
FROM PRODUCT
GROUP BY V_CODE;
7.8 JOINING DATABASE TABLES


SELECT P_DESCRIPT, P_PRICE, V_NAME,
V_CONTACT, V_AREACODE, V_PHONE
FROM PRODUCT, VENDOR
WHERE PRODUCT.V_CODE = VENDOR.V_CODE;
7.8.1 Joining Tables with an Alias


SELECT P_DESCRIPT, P_PRICE, V_NAME,
V_CONTACT, V_AREACODE, V_PHONE
FROM PRODUCT P, VENDOR V
WHERE P.V_CODE = V.V_CODE
ORDER BY P_PRICE;
7.8.2 Recursive Joins


SELECT E.EMP_MGR, M.EMP_LNAME, E.EMP_NUM,
E.EMP_LNAME
FROM EMP E, EMP M
WHERE E.EMP_MGR=M.EMP_NUM
ORDER BY E.EMP_MGR;
7.8.3 Outer Joins


SELECT P_CODE, VENDOR.V_CODE, V_NAME
FROM VENDOR LEFT JOIN PRODUCT
ON VENDOR.V_CODE = PRODUCT.V_CODE;

SELECT PRODUCT.P_CODE, VENDOR.V_CODE,
V_NAME
FROM VENDOR RIGHT JOIN PRODUCT
ON VENDOR.V_CODE = PRODUCT.V_CODE;

You might also like