0% found this document useful (0 votes)
9 views56 pages

376421_LEC07_BasicSQL_sol

Uploaded by

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

376421_LEC07_BasicSQL_sol

Uploaded by

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

Structured Query Language (SQL)

Lecture 7
Learning Outcomes
 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 for useful
information

2 TDB2111 Database Systems December 24, 2024


Introduction to SQL
 SQL functions fit into two broad categories:
 Data definition language (DDL)
 Data manipulation language (DML)
 Basic command set has vocabulary of fewer
than 100 words
 American National Standards Institute (ANSI)
prescribes a standard SQL
 Several SQL dialects exist

3 TDB2111 Database Systems December 24, 2024


Data Definition Commands
 Example of DDL:
 Create
 Alter
 Truncate
 Drop
 The database model
 In this chapter, a simple database with these
tables is used to illustrate commands:
 CUSTOMER
 INVOICE
 LINE
 PRODUCT
 VENDOR
 Focus on PRODUCT and VENDOR tables
4 TDB2111 Database Systems December 24, 2024
5 TDB2111 Database Systems December 24, 2024
Creating the Database
 Two tasks must be completed:
 Create database structure
 Create tables that will hold end-user data
 First task:
 RDBMS creates physical files that will hold
database
 Differs substantially from one RDBMS to another
 Syntax:
 CREATE DATABASE <database_name>;
 Example: CREATE DATABASE Tiny_College;

6 TDB2111 Database Systems December 24, 2024


The Database Schema
 Authentication
 DBMS verifies that only registered users are able
to access database
 Log on to RDBMS using user ID and password
created by database administrator
 Schema
 Group of database objects that are related to each
other
 While creating tables, the relationship is
important.
 Must create Parent table before Child table

7 TDB2111 Database Systems December 24, 2024


Data Types
 Data type selection is usually dictated by
nature of data and by intended use
 Supported data types:
 Number(L,D), Integer, Smallint, Decimal(L,D)
 Char(L), Varchar(L), Varchar2(L)
 Date, Time, Timestamp
 Real, Double, Float
 Interval day to hour
 Many other types

8 TDB2111 Database Systems December 24, 2024


Creating Table Structures
 Use one line per column (attribute) definition
 Use spaces to line up 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 semicolon
9 TDB2111 Database Systems December 24, 2024
Integrity
 Primary key attributes contain both a NOT
NULL and a UNIQUE specification
 RDBMS will automatically enforce referential
integrity for foreign keys
 Rules of foreign key

10 TDB2111 Database Systems December 24, 2024


Referential Integrity Rules
• Delete Rules
(1) Restrict – Cannot delete a record if records
are found in both parent and dependent table
The check for dependent rows is performed immediately.
(2) No Action – Cannot delete a record if records
are found in both parent and dependent table.
The check for dependent rows is performed at the end of the statement.
(3) Cascade – Deleting row in parent table
automatically deletes any related rows in
dependent tables
(4) Set Null – Foreign key fields set to null, other
columns left unchanged

• Update rules?
 Restrict
 No Action
 Cascade (for MySQL)
11
SQL Constraints
 NOT NULL constraint
 Ensures that column does not accept nulls
 UNIQUE constraint
 Ensures that all values in column are unique
 DEFAULT constraint
 Assigns value to attribute when a new row is
added to table
 CHECK constraint
 Validates data when attribute value is entered

12 TDB2111 Database Systems December 24, 2024


SQL Indexes
 When primary key is declared, DBMS
automatically creates unique index
 Often need additional indexes
 Using CREATE INDEX command, SQL indexes
can be created on basis of any selected
attribute
 Composite index
 Index based on two or more attributes
 Often used to prevent data duplication

13 TDB2111 Database Systems December 24, 2024


Creating Table Structures
 CREATE TABLE <table name>( v_code v_name
<attribute1 name and attribute1 characteristics,
A1234 Pocopoint
attribute2 name and attribute2 characteristics,
A1231
attribute3 name and attribute3 characteristics, Vara
primary key designation,
foreign key designation and foreign key requirements>);

 Example:
 CREATE TABLE VENDOR
(v_code char(5) not null,
v_name varchar(20),
v_contact varchar(15),
v_areacode char(5),
v_phone varchar(10),
v_state char(2),
v_order char(1)
primary key (v_code));

14 TDB2111 Database Systems December 24, 2024


Creating Table Structures
 Example: MySQL format: user must input as
YYYY-MM-DD
 CREATE TABLE PRODUCT
(p_code varchar(10) not null,
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), Integer: round number
primary key (p_code),
Decimal: number with
foreign key (v_code) references vendor
decimal point, need to pre-
on delete set null);
set 2 parameters. Total
 Some RDBMS declare foreign numberkeyof digit,
as: and
FOREIGN KEY
number of decimal point
(v_code) REFERENCES VENDOR(v_code) ON DELETE SET
15 NULL TDB2111 Database Systems December 24, 2024
Advanced Data Definition Commands
 All changes in table structure are made by
using ALTER command
 Three options:
 ADD adds a column
 MODIFY changes column characteristics
 DROP deletes a column
 Can also be used to:
 Add/remove table constraints
 Includes check constraints, PK, FK

16 TDB2111 Database Systems December 24, 2024


Changing a Column’s Data Type
 ALTER can be used to change data type
 Some RDBMSs do not permit changes to data
types unless column is empty, such as Oracle

17 TDB2111 Database Systems December 24, 2024


Changing a Column’s Data
Characteristics
 Use ALTER to change data characteristics
 Example:
 ALTER TABLE <table name> MODIFY (<column name>
<new column characteristics>);

 Changes in column’s characteristics are permitted


if changes do not alter the existing data type
 Example:
 Changing a Column’s Data Type
 ALTER TABLE PRODUCT MODIFY (V_CODE CHAR(5));
 Changing Attribute Characteristics
 ALTER TABLE PRODUCT MODIFY (P_PRICE DECIMAL(9,2));

18 TDB2111 Database Systems December 24, 2024


Adding a Column
 Use ALTER to add column
 Do not include the NOT NULL clause for new column
 Adding a New Column to the Table
 ALTER TABLE PRODUCT ADD COLUMN P_SALECODE
CHAR(1);
 ALTER TABLE PRODUCT ADD COLUMN P_SALECODE
CHAR(1) AFTER P_DISCOUNT;
 More example:
 ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE);
 ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE)
REFERENCES VENDOR(V_CODE);
 ALTER TABLE `PRODUCT` ADD `P_SALECODE` CHAR(1)
AFTER `P_INDATE` ;
 Some other alternatives:
 ALTER TABLE PRODUCT ADD CONSTRAINT pk_code PRIMARY
KEY (P_CODE);
 ALTER TABLE PRODUCT ADD CONSTRAINT fk_vcode FOREIGN
KEY (V_CODE) REFERENCES VENDOR(V_CODE)
19 TDB2111 Database Systems December 24, 2024
Dropping a Column
 Use ALTER to drop column
 Some RDBMSs impose restrictions on the deletion
of an attribute
 Example:
 ALTER TABLE VENDOR
 DROP COLUMN V_ORDER;

20 TDB2111 Database Systems December 24, 2024


Data Manipulation Commands
 INSERT
 SELECT
 COMMIT
 UPDATE
 ROLLBACK
 DELETE

21 TDB2111 Database Systems December 24, 2024


Adding Table Rows
 INSERT
 Used to enter data into table
 Syntax:
 INSERT INTO tablename
VALUES (value1, value2, … , valueN);
 Example:
 INSERT INTO VENDOR VALUES(‘21225’, ’Bryson Inc.’,
’Smithson’, ’615’, ’223-3234’, ’TN’, ‘Y’);
 OR
 INSERT INTO VENDOR (v_code, v_name_v_areacode, v_state,
v_contact, v_phone, v_order) VALUES
(‘21225’, ’Bryson Inc.’,’615’,’TN’, ’Smithson’, ’223-
3234’, ‘Y’);

 INSERT INTO PRODUCT VALUES(‘11 QER/31’, ‘Power painter’,


22 ‘15 psi.’, ‘3-nozzle’, ’07-02-1999’,
TDB2111 8.5, 109.99, 0.00,
Database Systems ‘25595’);
December 24, 2024
Adding Table Rows (cont’d.)
 When entering values, notice that:
 Row contents are entered between parentheses
 Character and date values are entered between
apostrophes
 Numerical entries are not enclosed in apostrophes
 Attribute entries are separated by commas
 A value is required for each column
 Use NULL for unknown values

23 TDB2111 Database Systems December 24, 2024


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
 Some DBMS will automatically COMMIT the
query, such as phpMyAdmin in Xampp

24 TDB2111 Database Systems December 24, 2024


Listing Table Rows
 SELECT
 Used to list contents of table
 Syntax:
 SELECT columnlist
 FROM tablename;
 Columnlist represents one or more attributes,
separated by commas
 Example: SELECT p_code, p_descript, p_indate,
p_onhand, p_min, p_price, p_discount, v_code FROM
product;
 Asterisk can be used as wildcard character to
list all attributes
 Example: SELECT * FROM product;
25 TDB2111 Database Systems December 24, 2024
Updating Table Rows
 UPDATE
 Modify data in a table
 Syntax:
 UPDATE tablename
SET columnname = expression [, columnname =
expression]
[WHERE conditionlist];
 Example:
 UPDATE product
 SET p_indate = ‘12/11/96’
 WHERE p_code = ‘13-Q2/P2’;
 If more than one attribute is to be updated in row,
separate corrections with commas
 Example:
 UPDATE product
 SET P_INDATE = ‘12/11/96’, P_PRICE = 15.99,
P_MIN=10
 WHERE P_CODE = ‘13-Q2/P2’;
26 TDB2111 Database Systems December 24, 2024
Restoring Table Contents
 ROLLBACK
 Undoes changes since last COMMIT
 Brings data back to prechange values
 Syntax:
 ROLLBACK;
 COMMIT and ROLLBACK only work with
commands to add, modify, or delete table
rows

27 TDB2111 Database Systems December 24, 2024


Deleting Table Rows
 DELETE
 Deletes a table row
 Syntax:
 DELETE FROM tablename
[WHERE conditionlist ];
 WHERE condition is optional
 If WHERE condition is not specified, all rows
from specified table will be deleted
 example:s:
 DELETE FROM product WHERE p_code =
‘2238/QPD’;
 DELETE FROM product WHERE p_min = 5;
28 TDB2111 Database Systems December 24, 2024
Copying Parts of Tables
 SQL permits copying contents of selected
table columns
 Data need not be reentered manually into newly
created table(s)
 First create the table structure
 Next add rows to new table using table rows
from another table
 INSERT INTO table2(col1, col2, …) SELECT
col1, col2… FROM table1 WHERE condition;

29 TDB2111 Database Systems December 24, 2024


Copying Parts of Tables
 INSERT
 Inserts multiple rows from another table (source)
 Uses SELECT subquery
 Subquery: query embedded (or nested or inner)
inside another query
 Subquery executed first
 Syntax:
 INSERT INTO tablename SELECT columnlist FROM
tablename;

30 TDB2111 Database Systems December 24, 2024


Example: Inserting Columns from Table
Product into Table Part
 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;

31 TDB2111 Database Systems December 24, 2024


Copying PRODUCT Table into PART Table
- Result

32 TDB2111 Database Systems December 24, 2024


SELECT Queries
 Fine-tune SELECT command by adding
restrictions to search criteria using:
 Conditional restrictions
 Arithmetic operators
 Logical operators
 Special operators

33 TDB2111 Database Systems December 24, 2024


Selecting Rows with
Conditional Restrictions
 Select partial table contents by placing
restrictions on rows to be included in output
 Add conditional restrictions to SELECT statement,
using WHERE clause
 Syntax:
 SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;

34 TDB2111 Database Systems December 24, 2024


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

35 TDB2111 Database Systems December 24, 2024


Comparison Operators

36 TDB2111 Database Systems December 24, 2024


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;

37 TDB2111 Database Systems December 24, 2024


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

38 TDB2111 Database Systems December 24, 2024


Selected PRODUCT Table Attributes:
The ASCII Code Effect

SELECT P_CODE, P_DESCRIPT, P_QOH, P_MIN, P_PRICE


FROM PRODUCT
WHERE P_CODE < ‘1558-QW1’;

39 TDB2111 Database Systems December 24, 2024


Selected PRODUCT Table Attributes:
Date Restriction

SELECT P_DESCRIPT, P_QOH, P_MIN, P_PRICE, P_INDATE


FROM PRODUCT
WHERE P_INDATE >= ’20-Jan-2004’;

40 TDB2111 Database Systems December 24, 2024


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

41 TDB2111 Database Systems December 24, 2024


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

42 TDB2111 Database Systems December 24, 2024


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

43 TDB2111 Database Systems December 24, 2024


Logical Operators: AND, OR, and NOT
 Searching data involves multiple conditions
 Logical operators: AND, OR, and NOT
 Can be combined
 Parentheses enforce precedence order
 Conditions in parentheses are always executed first
 Boolean algebra: mathematical field
dedicated to use of logical operators
 NOT negates result of conditional expression

44 TDB2111 Database Systems December 24, 2024


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

45 TDB2111 Database Systems December 24, 2024


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

46 TDB2111 Database Systems December 24, 2024


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;

47 TDB2111 Database Systems December 24, 2024


Special Operators
 BETWEEN: checks whether attribute value is
within a range
 IS NULL: checks whether attribute value is null
 LIKE: checks whether attribute value matches
given string pattern
 IN: checks whether attribute value matches
any value within a value list
 EXISTS: checks if subquery returns any rows

48 TDB2111 Database Systems December 24, 2024


Special Operators: Examples
 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;

49 TDB2111 Database Systems December 24, 2024


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;

50 TDB2111 Database Systems December 24, 2024


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%’;

51 TDB2111 Database Systems December 24, 2024


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;

52 TDB2111 Database Systems December 24, 2024


Date & Time (Basic)
 Date function:
 SELECT date_format(curdate(), ‘%d/%m/%y’);
 Customize the date format when display

 SELECT DATEDIFF('2019-11-04','2018-12-04') days;


 Get the different in days between two dates

 Time function:
 It is one of the data type with format: HH:MM:SS
 SELECT time_format( current_time(), '%h:%i %p');
 h: refers to hour, from 0 – 12
 i: refers to minute, from0 – 60
 p: means AM or PM

53 TDB2111 Database Systems December 24, 2024


Advanced Data Updates
 UPDATE command updates only data in
existing rows
 If relationship between entries and existing
columns, can assign values to slots
 Arithmetic operators are useful in data
updates
 In Oracle, ROLLBACK command undoes
changes made by last two UPDATE statements

54 TDB2111 Database Systems December 24, 2024


Advanced Data Updates - Example
P_INDATE P_SALECODE
Before December 25 2
2009
Between January 16 1
2010 and 10 February
UPDATE2010
PRODUCT
SET P_SALECODE = ‘2’
WHERE P_INDATE < ‘2009-12-25’;

UPDATE PRODUCT
SET P_SALECODE = ‘1’
WHERE P_INDATE >= ‘2010-01-16’
AND P_INDATE <= ‘2010-02-10’;
55 TDB2111 Database Systems December 24, 2024
Advanced Data Updates - Results

56 TDB2111 Database Systems December 24, 2024

You might also like