1. 1
ISTE 230 - INTRODUCTION TO DATABASE & DATA
MODELING
Lifecycle Example with a Single Entity (con’t)
SQL Introduction
What is SQL?
Types of Statements (So Far)
Data Definition Language
CREATE
DROP
Data Manipulation Language
INSERT
SELECT
MySQL Introduction
Viewing Metadata
SHOW DATABASES|TABLES|CREATE TABLE
DESCRIBE, EXPLAIN
CREATE|DROP DATABASE
USE
Simple CREATE|DROP TABLE
Data Types
Character
CHAR
VARCHAR
Numeric
Integer
INTEGER|INT
Date/Time
DATE
PRIMARY KEY constraint
Scripts versus Command-Line Entry
INSERT
SELECT Statement Introduction
Required Clauses: SELECT and FROM
Column Alias
Optional Clause: WHERE
Logical Operators (NOT, AND, OR)
NULL values
Finding
Inserting
Common Mistakes
2. 2
Lifecycle Example: CONMAN
Is the CONTACT_INFO relation in 1NF?
Rows contain data about tuples or instances of the relation
Cells of the relation hold a single value (no arrays)
Columns are attributes of the relation
All entries in a column are of the same domain (physical and logical)
Each column has a unique name
The order of the attributes is unimportant
The order of the tuples is unimportant
No two tuples may be identical (Must have a primary key)
No repeating groups – more than one attribute from the same physical and logical domain
(ex. author1, author2, etc)
CONTACT_INFO(contactID, firstName, middleInitial, lastName, birthday, email, url, notes)
RECAP - Step #3: Normalize Relation(s)
3. 3
Expanded Database Development
Lifecycle
Summary of Steps
1. Create a Data Model from gathered requirements.
Entity-Relationship Model
2. Transpose Data Model into Relation(s)
3. Normalize Relations
4. Create the Relational Schema within Database Management System. (Metadata)
Create the database
Create the table(s)
5. Define forms, queries, reports, menus, if supported within DBMS or external application
programs. (Application Metadata)
Will not be covered in this course
6. Populate with User Data
The process and who is responsible (you or system users) depends on situation
7. Maintenance
Change happens…expect it…plan for it as best you can!
User Needs, DBMSs, Hardware
4. 4
DBMS - INDEPENDENT
DBMS - SPECIFIC
UoD
HIGH-LEVEL or conceptual level
(e.g., E-R diagram)
LOW-LEVEL or physical level
(e.g., file layouts/structures,
indexing, OS access strategies)
DBMS
REPRESENTATIONAL level
which (to access the data), uses
the ...
DBMS software
(Relational Model)
5. 5
Step #4: Create Relational Schema
within DBMS
Use a data access language within the DBMS to create metadata
In the late 70s and early 80s, each manufacturer used their own language
In 1986, American National Standards Institute (ANSI) embraced IBM’s Structured English
Query Language (SEQUEL) and transformed it into what is now Structured Query
Language (SQL)
Since then, ANSI has released the following standards:
SQL-89
SQL-92
SQL:1999
SQL:2003
SQL:2006
SQL:2008
SQL:2011
SQL:2016
6. 6
SQL Statement Categories (So Far…)
Data Definition Language (DDL)
Deals primarily with metadata
CREATE…
DROP…
Data Manipulation Language (DML)
Deals primarily with user data
INSERT
SELECT
Transaction Control Language (TCL)
Also referred to as Data Control Language
Commit
Rollback
7. 7
SQL
Today, SQL is used by many commercial DBMS
products:
DB2 Oracle Informix
Sybase SQLServer Access
Each manufacturer adds additional “features” to
differentiate their product (danger!)
8. 8
The DBMS for this course: MySQL
MySQL is the most popular Open Source database
Developed by MySQL AB and now Oracle
Commonly found in web applications
Could also be used as a departmental database server
Does not have all the features of a corporate database like
Oracle
You will be expected to use only the command-line
interface for all work in this course.
9. 9
Commands to View Metadata
SHOW DATABASES;
Shows the databases on the system
SHOW TABLES;
Shows the tables in the current database
DESCRIBE tableName;
Shows some of the metadata maintained for the
specified table
DESC tableName;
EXPLAIN tableName;
SHOW COLUMNS
FROM tableName;
SHOW CREATE TABLE tableName;
Shows the create table statement for the specified table
10. 10
Expanded Database Development
Lifecycle
Summary of Steps
1. Create a Data Model from gathered requirements.
Entity-Relationship Model
2. Transpose Data Model into Relation(s)
3. Normalize Relations
4. Create the Relational Schema within Database Management System. (Metadata)
Create the database
Create the table(s)
5. Define forms, queries, reports, menus, if supported within DBMS or external application
programs. (Application Metadata)
Will not be covered in this course
6. Populate with User Data
The process and who is responsible (you or system users) depends on situation
7. Maintenance
Change happens…expect it…plan for it as best you can!
User Needs, DBMSs, Hardware
11. 11
DDL: CREATE|DROP DATABASE
To create a database:
General Syntax Format: CREATE DATABASE databaseName;
Example: CREATE DATABASE test;
To remove a database:
General Syntax Format: DROP DATABASE databaseName;
Example: DROP DATABASE test;
Can add IF EXISTS to prevent the DROP DATABASE from executing if the
database does not exist.
Example: DROP DATABASE IF EXISTS test;
12. 12
USE command
Once a MySQL database is created, it isn’t automatically opened
for access within the session
“Open” a database through USE command
General Syntax Format: USE databaseName;
Example: USE test;
Only one MySQL database can be opened at a time in a session
To open a different database in the session, execute a USE
command
13. 13
Lifecycle Example: CONMAN
CREATE DATABASE conman;
What command can be entered to verify that the conman
database has been created?
USE conman;
What command can be entered to see if the system created any
tables in the database by default?
Step #4a: Create the Database
You have now created the database and it will remain on the computer until it
is deleted.
14. 14
Expanded Database Development
Lifecycle
Summary of Steps
1. Create a Data Model from gathered requirements.
Entity-Relationship Model
2. Transpose Data Model into Relation(s)
3. Normalize Relations
4. Create the Relational Schema within Database Management System. (Metadata)
Create the database
Create the table(s)
5. Define forms, queries, reports, menus, if supported within DBMS or external application
programs. (Application Metadata)
Will not be covered in this course
6. Populate with User Data
The process and who is responsible (you or system users) depends on situation
7. Maintenance
Change happens…expect it…plan for it as best you can!
User Needs, DBMSs, Hardware
16. 16
What is a constraint?
A constraint is a rule limiting the values
allowed for an attribute
A PRIMARY KEY is one example
Each value must be unique
A value must be specified; NULL values are not
allowed
There are other constraints that protect
data integrity
Constraints are specified in the CREATE
TABLE statement
17. 17
DDL: CREATE|DROP TABLE
To create a table within the current database (based on USE command)
Syntax Format (so far):
CREATE TABLE tableName(
attribute1 DATATYPE,
attribute2 DATATYPE,
…,
CONSTRAINT tableName_pk PRIMARY KEY (primary_key_attribute(s))
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Example:
CREATE TABLE employee(
employeeID CHAR(11) COMMENT “employeeID will be constrained to be the primary key”,
ssn CHAR(11),
name VARCHAR(35),
dob DATE,
CONSTRAINT employee_pk PRIMARY KEY(employeeID) <-without a primary key constraint
) ENGINE=InnoDB DEFAULT CHARSET=utf8; duplicate records could occur
What command(s) can be executed to view the table’s metadata? To view the CREATE TABLE statement?
To remove a table within the current database
DROP TABLE tableName;
18. 18
MySQL Scripts
MySQL allows you to specify more than one SQL statement at a time
Always use a semi-colon at the end of the statement
MySQL also allows you to run SQL statements that are contained in a text
file (also known as a script file)
Executing a script file has advantages over typing statements at the
command line
Typos are easily corrected
Scripts can be saved and reused
Commenting can be included
-- single line comment (space MUST be included after --)
# single line comment
/* block comment (can span multiple lines) */
COMMENT “Comment within an attribute specification”
See COMMENT for employeeID on previous slide
20. 20
Lifecycle Example: CONMAN
Execute a CREATE TABLE STATEMENT
Script: createCONTACT_INFO.sql
MyCourses, Content
What command can be entered to verify that the contactInfo
table has been created?
What command can be entered to view the metadata of the
contactInfo table?
Step #4b: Create the Tables
21. 21
Expanded Database Development
Lifecycle
Summary of Steps
1. Create a Data Model from gathered requirements.
Entity-Relationship Model
2. Transpose Data Model into Relation(s)
3. Normalize Relations
4. Create the Relational Schema within Database Management System. (Metadata)
Create the database
Create the table(s)
5. Define forms, queries, reports, menus, if supported within DBMS or external application
programs. (Application Metadata)
Will not be covered in this course
6. Populate with User Data
The process and who is responsible (you or system users) depends on situation
7. Maintenance
Change happens…expect it…plan for it as best you can!
User Needs, DBMSs, Hardware
22. 22
DML: INSERT
Adds user data to a table
The INSERT statement typically adds one record at a time
Most DBMS packages also have a bulk insert capability (e.g., Oracle has
SQLLoader)
General Syntax Format:
INSERT INTO tableName
(fieldlist) VALUES (valuelist);
tableName is the name of the table we’re adding to
fieldlist is a comma-separated list of attribute names
Provides a template so that the DBMS engine know which attributes you are
specifying values for and what attribute order the values will be given in
valuelist is a comma-separated list of values to be added for the
attribututes listed in the fieldlist
23. 23
INSERT Shortcut
INSERT INTO employee
(employeeID, ssn, name, dob)
VALUES('11111111111',
'121-21-2121', 'Jason Jones',
'1990-10-31');
INSERT INTO employee
VALUES( '22222222222',
'342-56-2454',
'Lisa Kellog',
'1984-01-15');
You may specify only the
values if you know
the correct order of the
attributes in the table AND
will be specifying a value for
each attribute.
24. 24
INSERT Shortcut
WRONG!
CORRECT
When using the shortcut and attributes are NOT specified,
ALL values must be specified in the CORRECT ORDER.
INSERT INTO employee
VALUES('12345678901','254-67-4563');
INSERT INTO employee (employeeID,
ssn) VALUES('12345678901',
'254-67-4563');
25. 25
Shows user data in a table
Basic Syntax:
SELECT *| attributes_to_include
FROM tableName;
Examples:
SELECT *
FROM employee;
SELECT name
FROM employee;
SELECT NAME, DoB, employeeID
FROM employee;
SELECT Name, dob AS "Date of Birth"
FROM employee;
DML: SELECT
Column Alias
26. 26
Lifecycle Example: CONMAN
Execute INSERT statements
Script: insertCONTACT_INFO.sql
MyCourses, Content
What statement can be executed to view the user data in the
contactInfo table?
Step #6: Populate database with User Data
27. 27
SELECT: WHERE clause
Allows the limitation of records that appear in the result set based
on condition(s) specified
Basic Syntax:
SELECT *| attributes_to_include
FROM tableName
WHERE condition(s);
Example: Please show the all the data from employee for the
employee with an ID of 12345678901.
SELECT employeeID, ssn, name, dob
FROM employee
WHERE employeeID='12345678901';
28. 28
Logical Operators
NOT – reverses the result
Example: Please show the all the data from employee for every employee, except for the
employee with an ID of 12345678901.
SELECT employeeID, ssn, name, dob
FROM employee
WHERE NOT employeeID= '12345678901';
AND – Conditions on both sides must evaluate to true to be in result set
Example: Please show name of the employee with an ID of 11111111111 and a date of birth of
1984-01-05.
SELECT name
FROM employee
WHERE employeeID='11111111111' AND dob='1984-01-05';
OR – One or both conditions must evaluate to true to be in result set
Example: Please show name of employees with an ID of 11111111111 or a date of birth of 1984-
01-05.
SELECT name
FROM employee
WHERE employeeID='11111111111' OR dob='1984-01-05';
29. 29
NULL values
Means unknown or nothing
Does NOT mean and empty string('') or a string of a space (' ')
Example: How to find NULL values
SELECT employeeID
FROM employee
WHERE name IS NULL;
30. 30
Inserting NULL values
To see if NULLs are allowed for an attribute, DESCRIBE the table it
is in
Can be used with or without field list
Examples:
INSERT INTO employee (employeeID, ssn, name)
VALUES('33333333333', '098-76-5432', NULL);
INSERT INTO employee VALUES('44444444444',
'555-44-3333', NULL, null);
31. 31
Common Mistakes with NULL
INSERT INTO employee VALUES('77777777777',
'656-56-5656','', NULL);
INSERT INTO employee VALUES('88888888888',
'444-99-1111',' ', NULL);
INSERT INTO employee VALUES('99999999999',
'777-55-0909','NULL', NULL);
SELECT * FROM employee WHERE name ='';
SELECT * FROM employee WHERE name = ' ';
SELECT * FROM employee WHERE name = 'NULL';
32. 32
Constraints (So far…)
PRIMARY KEY – constrains the attribute(s) to be the primary key
(unique, not null)
Can be attribute or table level
NOT NULL – a value is required to be entered
Attribute level only
CHECK – proposed value must meet specified conditions
Can be attribute or table level
DEFAULT – a value to be entered when a value is not specified
Attribute level only
33. 33
Data Integrity Checks
Two main types of data integrity checks:
“atomic” checks that look at the proposed field value
NOT NULL
CHECK (if validation only refers to itself)
“relative” checks that compare the proposed field value to other data
UNIQUE
CHECK (if validation refers to other attribute(s))
We say “proposed field value” because the data
check happens before the value goes into the
database
34. 34
Naming Constraints
Other than field names and data types, everything
we’ve discussed is called a “constraint”
Each table-level constraint can be given a name
This allows us to refer to the constraint later
For Primary Key constraint: tablename_pk
35. 35
Example
CREATE TABLE film (
filmID INT,
title VARCHAR(255) NOT NULL,
description varchar(1000),
releaseYear SMALLINT,
length SMALLINT UNSIGNED,
replacementCost DECIMAL(5,2) NOT NULL DEFAULT 19.99,
rating VARCHAR(5) NOT NULL,
CONSTRAINT film_pk PRIMARY KEY (filmID),
CONSTRAINT film_replacementCost_ck CHECK (replacementCost > 9.99)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
36. 36
SELECT Statement - Review
Shows user data in a table
Basic Syntax (Required clauses):
SELECT *| attributes_to_include
FROM tableName;
Basic Syntax (with optional clauses discussed so far):
SELECT *| attributes_to_include
FROM tableName
WHERE condition(s);
37. 37
WHERE Clause
Relational Operators
> Greater Than
>= Greater Than or Equal To
< Less Than
<= Less Than or Equal To
= Equal To
<> Not Equal To
!= Not Equal To
IN (list) Contained in comma-separated list
LIKE string Matches string pattern
38. 38
Logical Operators
Review:
NOT – reverses the result
AND – Conditions on both sides must evaluate to true to be in
result set
OR – One or both conditions must evaluate to true to
be in result set
BETWEEN – will include values that are greater than, or
equal to, the minimum value and less than, or equal to,
the maximum value specified
SELECT *|attribute(s)
FROM table
WHERE attribute BETWEEN min_value AND max_value;
39. 39
LIKE: Pattern Matching
To specify our pattern we use characters and wildcards
Characters must be present
Wildcards are placeholders for characters
_ means exactly 1 character
% means 0 or more characters
40. 40
Calculations
Calculations can be performed in the SELECT clause of a SELECT
statement
Example:
Show the title of each film, the total length in minutes, as well as in hours and
minutes.
SELECT title, length, TRUNCATE(length/60, 0), length MOD 60
FROM film;
SELECT title, length AS ‘Total Minutes’, TRUNCATE(length/60,0) AS “Hours”,
length MOD 60 AS “Minutes”
FROM film;
41. 41
SQL Statement Categories (So Far…)
Data Definition Language (DDL)
Deals primarily with metadata
CREATE…
DROP…
ALTER …
Data Manipulation Language (DML)
Deals primarily with user data
INSERT
SELECT
UPDATE
DELETE
42. 42
DML: UPDATE
Modifies existing user data
General Syntax Format:
UPDATE tableName
SET field1 = value1, …, fieldN = valueN
WHERE condition; <- WHERE clause is optional
tableName is the name of the table we’re updating
condition is an expression to limit which records are updated
field1…fieldN are the names of the fields to be updated
value1…valueN are the new values
Example:
UPDATE film
SET replacementCost = replacementCost +5
WHERE replacementCost=9.99;
43. 43
DML: DELETE
Removes record(s) from a table
General Syntax Format:
DELETE
FROM tableName
WHERE condition(s); <- WHERE clause is optional
tableName is the name of the table we’re deleting records from
condition is an expression to limit which records are deleted (similar to
WHERE in the SELECT statement)
Without WHERE all data is deleted from the table
Example:
DELETE
FROM film
WHERE rating=‘R’;
44. 44
ALTER TABLE
Now that you can create a table, if you need to change
the structure, you can alter it instead of dropping and
creating again.
Databases are no different than programs
Version 1 is just the starting point
There will be many versions as time goes on
There are lots of changes that can be made through ALTER TABLE.
The syntax is shown in MySQL Help System
https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
45. 45
What to Alter?
You can use the ALTER TABLE statement to:
Add/Drop a primary key constraint
Add/Modify/Drop a column
Add/Drop/Modify a default value
You cannot modify a table level constraint…
46. 46
Altering Primary Key
Let’s get rid of the PRIMAY KEY constraint:
ALTER TABLE film
DROP PRIMARY KEY;
Add it back
ALTER TABLE film
ADD PRIMARY KEY film_pk (filmID);
47. 47
ADD|DROP Columns
General Syntax Format:
ALTER TABLE tableName
{ADD|DROP} COLUMN columnspec;
Example: What if we wanted to add a “URL”
column to the film table:
ALTER TABLE film
ADD COLUMN url VARCHAR(50);
Example: What if we wanted to remove the
replacement cost from the film table:
ALTER TABLE film
DROP COLUMN replacementCost;
48. 48
Altering Defaults
Defaults are the only “property” you can alter.
We will see in the next slide how to change data types.
Let’s add a default value of ‘Not entered.’ to the
description column in the table:
ALTER TABLE film
ALTER description SET DEFAULT ‘Not entered.’;
And if we change our mind and don’t want it after all:
ALTER TABLE film
ALTER description DROP DEFAULT;
49. 49
ALTER TABLE…MODIFY COLUMN
Through the ALTER TABLE…MODIFY statement, you can edit an existing attribute’s
specification including changing the data type or adding/removing a not null constraint
or default value
ALTER TABLE tableName
MODIFY attribute DATATYPE [NOT NULL] [DEFAULT];
CHANGE (instead of modify) can also be used:
CHANGE currAttrName newAttrName newDATATYPE;
Read more: https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
Note that we need to state the FULL attribute specification, not just what
we want to change
Example: Let’s modify releaseYear to require a value and set a
default value to 2020.
ALTER TABLE film
MODIFY COLUMN releaseYear SMALLINT NOT NULL DEFAULT 2020;
50. 50
Storing an Output Table
Check out to how to CREATE TABLE from SELECT.
https://dev.mysql.com/doc/refman/8.0/en/create-table-select.html
51. 51
MISC
To clear the screen in the MySQL command prompt:
mysql> system cls;
To log results, use T as follows:
mysql> T <fullLogFilePath.txt>
To check which database is being used
mysql> SELECT DATABASE();
To create a table from the result of a SELECT statement:
CREATE TABLE IF NOT EXISTS destTblName
SELECT … FROM …;
Remember to precede it with “DROP TABLE IF EXISTS tblName” if you want to
store an update result of SELECT.