0% found this document useful (0 votes)
9 views

06 SQL1 Create

The document provides an introduction to using MySQL to create and manage database tables. It discusses using SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, and DELETE to respectively create tables, modify existing tables, remove tables, add data to tables, and remove data from tables. Specific topics covered include defining table structure with data types and constraints, adding and modifying columns, specifying primary keys and foreign key relationships between tables.

Uploaded by

danelozano23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

06 SQL1 Create

The document provides an introduction to using MySQL to create and manage database tables. It discusses using SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, and DELETE to respectively create tables, modify existing tables, remove tables, add data to tables, and remove data from tables. Specific topics covered include defining table structure with data types and constraints, adding and modifying columns, specifying primary keys and foreign key relationships between tables.

Uploaded by

danelozano23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Master in Information Technology

ICT - 209
Database Applications
Introduction to MySQL

Creating Tables

1
Contents
• Introduction to MySQL
• Create a table
• Specify keys and relations
• Empty and Drop tables

2
Introduction

• SQL is a declarative language for manipulating a


relational database
• Use it to issue commands to the database for tasks
such as:
– Creating and managing tables
– Inserting data into tables
– Searching for and retrieving data from tables
– Deleting data and tables
• MySQL is a particular version of SQL

3
Online Resource

http://dev.mysql.com/doc/refman/5.0/en/index.html

• Is Oracle’s MySQL documentation site – note the 5.0 is the version we will
use in practicals here. You will need:

• Chapter 12 – Statement Syntax


• Chapter 10 – Data Types

• The search facility is awful – use Google instead

4
Database Engines

• MySQL supports a number of database


engines, each designed for databases with
different needs
• We will use the InnoDB engine as it supports
inter-table constraints (Foreign keys)
• For more on Storage Engines, see:

http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html

5
Making MySQL Statements

• We tend to use UPPER CASE for reserved words


• Strings are enclosed in forward single ‘quotes’ or double “quotes”
• Names of database elements such as tables and fields are enclosed in
backwards `quotes`
• Statements are separated by semi-colons ;

E.G

SELECT `name` from `mytable` WHERE `name`=‘John’

• You can drop the use of quotes if it is safe to do so, for example for names
with no spaces or special characters.

SELECT name from mytable WHERE name=‘John’

6
SQL: CREATE TABLE
• The simplest form of CREATE TABLE looks like this:
CREATE TABLE IF NOT EXISTS tablename
(colname datatype,
... )

CREATE TABLE Staff


(Sno NUMBER,
Sname CHAR(20),
Dept CHAR(20),
Grade CHAR(7))

• See http://dev.mysql.com/doc/refman/5.0/en/create-table.html for full details of


CREATE TABLE

7
Data Types

• MySQL is strict about the use of data types. They include:

• VARCHAR
• INT
• DECIMAL
• DATE
• TEXT
• BOOL
• And others that you can read about here

http://dev.mysql.com/doc/refman/5.0/en/data-types.html

8
Table Constraints

• The specification of a column can include some extras:


– default value (used if an insertion doesn't supply a value)
– and a column constraint (see below)

• And we can add table constraint(s) before the closing bracket. Both types of
constraint are used to protect integrity (next slide)

9
SQL: CREATE TABLE: Integrity

• Column constraints: enforcing entity and referential integrity


[NOT NULL | NULL]
[DEFAULT default_value]
[AUTO_INCREMENT]
[UNIQUE [KEY] | [PRIMARY] KEY]
[COMMENT 'string']
PRIMARY KEY (only one per table)
REFERENCES table (column)

• The last of these declares a foreign key.


CREATE TABLE Staff
( ...
Dept VARCHAR(20) REFERENCES Depts (Dname),
Grade VARCHAR(7) REFERENCES Paytable
)
– The referenced column must be the key of its table
– We shall not be allowed to insert a row into Staff unless it contains a valid value (one found in
the other table) or null
– we can miss out the bracketed column-name if it is the same in both tables

10
SQL: CREATE TABLE: integrity (continued): cascaded
deletion
• We can add ON DELETE CASCADE to the REFERENCES part
• This means that if a row in the other table is deleted, all matching
rows in this table should be deleted too

• For example, the Dependant table in the ER tutorial (for the


dependants of employees) might declare the column
Enum REFERENCES Employee ON DELETE CASCADE

• So if we delete employee 123 from the Employee table, then then all
his/her dependants are deleted from the Dependant table, thus
protecting referential integrity
• We should only do this for weak entities
– it would be a disaster if we deleted (say) student records as a
result of deleting an Adviser of Studies

11
SQL: CREATE TABLE: integrity (continued)

• Notice that we cannot


– declare the Staff table until we have declared Depts and Paytable
– insert any data into Staff until we have matching data in Depts and
Paytable

• This can form a deadly embrace


– suppose the Depts table references the Staff table (for Head of
Dept, for example)
– then we cannot declare the Depts table until we have declared Staff
; and we cannot declare the Staff table until we have declared
Depts
– the solution to this problem comes later

12
SQL: CREATE TABLE: integrity (continued)

• After the last field, we can add table-constraints

– these look like column-constraints, but they can reference more than
one column
CREATE TABLE HTR
(Hour char(6),
Teacher char(3),
Room char(4),
PRIMARY KEY (Hour, Teacher)) ;

– obviously, this is how to declare composite primary keys

– we can declare (possibly composite) foreign keys in the same sort of


way, e.g. the Staff table could be rewritten to put the constraints at
the end (next slide):

13
SQL: CREATE TABLE: Integrity (continued)

CREATE TABLE Staff


(Sno NUMBER PRIMARY KEY,
Sname VARCHAR(20) NOT NULL,
Dept VARCHAR(20) REFERENCES Depts (Dname),
Grade VARCHAR(7) REFERENCES Paytable) ;

could be written as
CREATE TABLE Staff
(Sno NUMBER,
Sname VARCHAR(20) NOT NULL,
Dept VARCHAR(20),
Grade VARCHAR(7),
PRIMARY KEY(Sno),
CONSTRAINT FOREIGN KEY (Dept) REFERENCES Depts (Dname),
CONSTRAINT FOREIGN KEY (Grade) REFERENCES Paytable)

14
SQL: ALTER TABLE

• We can change tables, using ALTER TABLE, even after they contain data
• Amongst other possibilities, we can add or modify columns
ALTER TABLE Staff ADD
(StreetAddress VARCHAR(20),
TownAddress VARCHAR(20)) ;

ALTER TABLE Staff MODIFY


(TownAddress DEFAULT 'Stirling') ;

(we can enter staff before departments, then switch on the constraint)

15
SQL: ALTER TABLE, continued

• We can use ALTER TABLE to add a constraint


• This gets us out of the “deadly embrace” mentioned earlier
CREATE TABLE Dept
(Dname VARCHAR(20) PRIMARY KEY,
Head NUMBER) ;

CREATE TABLE Staff


(Sno NUMBER PRIMARY KEY,
Sname VARCHAR(20) NOT NULL
Dept VARCHAR(20)
CONSTRAINT DeptExist
REFERENCES Dept (Dname)

ALTER TABLE Dept ADD


FOREIGN KEY (Head) REFERENCES Staff(Sno)

16
Dropping and deleting

• We can completely remove a table: both its data (if any) and its definition
DROP TABLE tablename ;
DROP TABLE tablename CASCADE CONSTRAINTS ;
– the second form removes Foreign Key constraints in associated tables
(which otherwise could not be updated)

• Removing the data alone (not the definition):


DELETE FROM tablename ;
DELETE FROM tablename WHERE condition ;

– we shall deal with conditions later

17
Getting data into tables

• There are two ways of using SQL to get data into tables
• Firstly, with the values in the SQL statement
INSERT INTO Staff VALUES
(123,'Lee','CompSci','II.7') ;

– if we are not loading all the columns, use this form:


INSERT INTO Staff (Sno, Sname) VALUES
(456, 'Waldenstein') ;

• Secondly, by extracting the data from existing tables


INSERT INTO Loan
SELECT DISTINCT Sno, Bno, Date_out
FROM Staff_Borrower ;

• We can also use a bulk-loader utility (PHPMyAdmin has one)

18
Getting More Data In

• INSERT INTO `books` (`Name` ,`Number`)


VALUES ('book1', '1'), ('book2', '2'), ('book3', ‘3');

• See http://dev.mysql.com/doc/refman/5.0/en/insert.html for more details of


the INSERT syntax

19
Changing Data in a Table

• Use UPDATE table SET field=value, field=value WHERE condition

• See http://dev.mysql.com/doc/refman/5.0/en/update.html for full syntax

20

You might also like