Lecture 9: SQL-DDL: Reference: Read Chapter 4.1-4.2 of The Textbook
Lecture 9: SQL-DDL: Reference: Read Chapter 4.1-4.2 of The Textbook
Lecture 9: SQL-DDL
Reference:
1
Announcements
2
SQL
History
– SEQUEL for IBM System R
=> SQL1 (1986) => SQL 1989 (minor variation)
=> SQL2 (1992)
=> SQL3 (1999)
=> SQL 2003, SQL 2006, and SQL 2008
3
SQL
– Every relation must have a primary key; yet SQL allows some
tables not to have any key attributes
4
SQL DDL
Examples:
– CREATE DATABASE
(not needed unless you’re the system administrator)
– CREATE TABLE
– DROP TABLE
– ALTER TABLE
5
CREATE TABLE
8
MySQL Data Type Examples
9
Attribute Constraints
10
Attribute Constraints
11
CREATE TABLE By Copying
Example:
CREATE TABLE empl AS SELECT * FROM Employee;
12
REFERENTIAL INTEGRITY OPTIONS
We can specify RESTRICT, CASCADE, SET NULL or SET
DEFAULT on referential integrity constraints (foreign keys)
13
Example for DELETE
FK PK
S
R x
x
Request to delete
FOREIGN KEY (FK) REFERENCES S(PK) row in B
ON DELETE [ACTION]
FK PK
S
R x
x
Request to modify
PK in S
FOREIGN KEY (FK) REFERENCES S(PK)
ON UPDATE [ACTION]
15
Exercise
16
Exercise
17
Exercise
18
DROP TABLE
Example:
19
ALTER TABLE
20
TRUNCATE TABLE
21
MySQL
You can log on to the server from any machine that has
the mysql command line interpreter installed (e.g.,
arctic.cse.msu.edu)
– Username is your MSU NetID
– Password is your PID
22
Summary of useful MySQL commands
set password=password(‘new password’);
show databases; -- show the list of databases available to you
use dbname; -- use the database called dbname
show tables; -- show tables available
create table student (
id integer not null,
name varchar(50) );
describe student;
insert into student values (30, ‘john doe’);
select * from student;
truncate table student;
drop table student;
source script-file; -- executing SQL commands from a script-file
load data infile /path/file.txt into table skr;
23
MySQL Storage Engines
24
MySQL Databases
25
MySQL Storage Engines
InnoDB
– provides transaction-safe tables
– provides support for row locking and FOREIGN KEY constraints
26
Example
Employee Department
N 1
Works_For
27
Example
Employee Department
N 1
Works_For
28
Example
Employee Department
N 1
Works_For
29
Example
No dnumber = 3 in department
table
30
Foreign key constraints in MySQL
31
Example
32
Example
33
Example
34
Example
35