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

More SQL Data Definitions: Database Systems Lecture 6

The document discusses more SQL data definition and manipulation commands. It covers dropping and altering tables using DROP TABLE and ALTER TABLE. It also covers inserting, updating, and deleting data using INSERT, UPDATE, and DELETE statements. Examples are provided for each command to illustrate their proper syntax and usage. Readers are warned to be careful when using commands like DROP TABLE that permanently remove data.

Uploaded by

SowlSnatcha
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

More SQL Data Definitions: Database Systems Lecture 6

The document discusses more SQL data definition and manipulation commands. It covers dropping and altering tables using DROP TABLE and ALTER TABLE. It also covers inserting, updating, and deleting data using INSERT, UPDATE, and DELETE statements. Examples are provided for each command to illustrate their proper syntax and usage. Readers are warned to be careful when using commands like DROP TABLE that permanently remove data.

Uploaded by

SowlSnatcha
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

More SQL Data Definitions

Database Systems Lecture 6


Covered Last Lecture
• SQL
• The SQL language
• CREATE TABLE
• Columns
• Primary Keys
• Foreign Keys

• For more information: Connolly and Begg


chapter 6
More SQL Data Definition
In today’s Bonanza
• Starting SQL
• DROP TABLE
• ALTER TABLE
• INSERT, UPDATE, and DELETE
• Sequences

• For more information


• Connolly and Begg chapters 5 and 6

More SQL Data Definition


Creating Relations
• From last lecture.. CREATE TABLE

CREATE TABLE <name>


(
<column definitions>,
<constraints>
)

• Column definitions are made up of a:


Name, type (domain), and any column
constraints you want to add.

More SQL Data Definition


Column Constraints
• NOT NULL
• PRIMARY KEY [AUTO_INCREMENT]
• FOREIGN KEY
• UNIQUE
• DEFAULT value
• CHECK (expression)
• COLLATE collation-name

More SQL Data Definition


Last Lecture’s Question
Write the SQL that would Create a new table called
“Reviews” which should have the following columns:
rID, an integer that will be the primary key
cID, an integer that will be a foreign key to the CD table
Title, a string of up to 100 characters
Text, a string of up to 5000 characters
(5 marks)

More SQL Data Definition


Solution

CREATE TABLE Reviews


Student
(
rID INT
INT,NOT NULL,
cID INT
INT,NOT NULL,
Title VARCHAR(100)
VARCHAR(100),NOT NULL,
Text VARCHAR(5000)
VARCHAR(5000),NOT NULL,
CONSTRAINT PRIMARY KEY (rID),
CONSTRAINT FOREIGN KEY (cID)
)

More SQL Data Definition


Deleting Tables
• To
BE delete
CAREFUL a table
with
useany SQL statement with
DROP in it
DROP
• You TABLE
will delete any information in the table as well
• [IF EXISTS]
You won’t normally be asked to confirm
There is no easy way to undo the changes
• <name>

• Example:

DROP TABLE Module

More SQL Data Definition


Changing Tables
• Sometimes
ALTER TABLE youcan
want to change the structure
of
• an
Addexisting table
a new column
• Remove
One wayan existing
is to DROP column
it then rebuild it
• Add
This ais new constraint
dangerous, so there is the ALTER TABLE
• command
Remove aninstead
existing constraint

More SQL Data Definition


ALTERing Columns
To add or remove columns
Examples:
use
ALTER TABLE <table>
ADD COLUMN <col> ALTER TABLE Student
ADD COLUMN
ALTER TABLE <table> Degree VARCHAR(50)
DROP COLUMN <name>
ALTER TABLE Student
DROP COLUMN Degree

More SQL Data Definition


ALTERing Constraints
To add or remove constraints use:

ALTER TABLE <table>


ADD CONSTRAINT <definition>

ALTER TABLE <table>


DROP CONSTRAINT <name>

More SQL Data Definition


ALTERing Constraints
Examples:

ALTER TABLE Module


ADD CONSTRAINT ck UNIQUE (title)

ALTER TABLE Module


DROP CONSTRAINT ck

More SQL Data Definition


INSERT, UPDATE, DELETE
UPDATE and
• INSERT - addDELETE
a row tousea ‘WHERE
table clauses’ to
specify which rows to change or remove
• UPDATE - change row(s) in a table
• BE CAREFUL with these - an incorrect WHERE
• clause
DELETEcan destroyrow(s)
- remove lots offrom
dataa table

More SQL Data Definition


INSERT
• The INTO
INSERT number of columns and values must be the
same
<table>
(col1, col2,
• If you are …)
adding a value to every column, you don’t
have to list them
VALUES
(val1, val2, …)
• SQL doesn’t require that all rows are different
(unless a constraint says so)

More SQL Data Definition


INSERT example:
INSERT into Muppets
VALUES (‘Sven-Goran Erikkson’,
‘White’,
‘Human’);

• Note that you have to remember the correct


order for the attributes if you don’t specify
them, to pair up with the values you are
putting in. This can get very confusing.

More SQL Data Definition


INSERT illustration
Student

INSERT INTO Student ID Name Year


(ID, Name, Year) 1 John 1
VALUES (2, ‘Mary’, 3) 2 Mary 3

Student Student

ID Name Year INSERT INTO Student ID Name Year


(Name, ID) 1 John 1
1 John 1 VALUES (‘Mary’, 2) 2 Mary NULL

Student
INSERT INTO Student
VALUES (2, ‘Mary’, ID Name Year
3) 1 John 1
2 Mary 3
More SQL Data Definition
Duplicates?
• Remember that a relation (table) is just a set.

• Every table must have at least one key, so


each row can be identified.

• However SQL, not being a perfect


implementation, allows duplicates and tables
with no primary keys.

More SQL Data Definition


Duplicates. Just say no.
• Remember that a relation (table) is just a set.

• A set such as: {1, 2, 3, 3 } is illegal – an element


appears twice. This makes no sense in set theory.

• Just the same for databases. No row may appear twice


– you would simply be recording the same fact again,
wasting space.

• Never, ever create duplicate rows.

More SQL Data Definition


UPDATE
• All rows where the condition is true have the
columns set to the given values
UPDATE <table>
• If no condition is given all rows are changed so BE
SET col1
CAREFUL = val1
• Values =
[,col2 areval2…]
constants or can be computed from
columns
[WHERE
<condition>]

More SQL Data Definition


UPDATE illustration
Student
ID Name Year
UPDATE Student
SET Year = 1, 1 John 1
Student Name = 2 Mark 3
‘Jane’ 3 Anne 2
ID Name Year 4 Jane 1
WHERE ID = 4
1 John 1
2 Mark 3
3 Anne 2 Student
4 Mary 2 ID Name Year
UPDATE Student 1 John 2
SET Year = Year + 1 2 Mark 4
3 Anne 3
4 Mary 3
More SQL Data Definition
UPDATE dangers
• An update can change one row, or many rows
depending on how you specify the statement.

• The following will change every tuple (row):


UPDATE Muppets SET colour = ‘Brown’;

• So make sure you specify your WHERE


statement:
UPDATE Muppets SET colour = ‘Brown’
WHERE name=‘Fozzy’;

More SQL Data Definition


DELETE
• Removes all rows
• If no condition which
is given satisfy
then theare
ALL rows condition
deleted -
BE CAREFUL

DELETE FROM
• Some versions of SQL also have TRUNCATE TABLE <T>
<table>
which is like DELETE FROM <T> but it is quicker as it
doesn’t record its actions
[WHERE
<condition>]

More SQL Data Definition


DELETE illustration

Student
DELETE FROM ID Name Year
Student Student 1 John 1
ID Name Year WHERE Year = 2 2 Mark 3
1 John 1
2 Mark 3
3 Anne 2
4 Mary 2
Student
DELETE FROM Student
or ID Name Year
TRUNCATE TABLE Student

More SQL Data Definition


Being Careful Again
• When using DELETE andBefore
UPDATErunning
• You need to be careful to have the right WHERE
clause DELETE FROM Student
• You can check it by running aWHERE
SELECTYear
statement
= 3
with the same WHERE clause first
run
SELECT * FROM Student
WHERE Year = 3

More SQL Data Definition


A table or a table variable?
• When you create a table you are actually
creating a variable, with a name.

• This is what Codd called a time-dependent


relation.

• Updates, Inserts and Deletes replace the


value in that variable.

More SQL Data Definition


Back to Set Theory
• What are INSERT, UPDATE and DELETE
actually doing?

• They replace the whole of the previous table


with a whole new table.

• Or really they replace one relation value with


another.

• A table is a relation variable (a relvar) and


any change to it replaces the whole thing.
More SQL Data Definition
Replacing Relation Values
Muppets1 = { (Kermit, Green, Frog)
(Miss Piggy, Pink, Pig)
(Fozzy, Orange, Bear) }

INSERT into Muppets


VALUES (Robin, Green, Frog);

Muppets2 = { (Kermit, Green, Frog)


(Miss Piggy, Pink, Pig)
(Fozzy, Orange, Bear)
(Robin, Green, Frog) }

More SQL Data Definition


Update Confusion
• It is easy to see with inserts and deletes that
they are replacing the old relation (table) with
a larger or smaller one.

• However it is vital to realise with updates the


system is in theory:

- Memorizing some row in the old table


- Altering that memorized row
- Deleting the original row from the old table
- Creating a new table with the new altered row added.

More SQL Data Definition


Sequences
• Often
In most
weversions
want each
of SQL
tuplewetocan
have
use
a unique
number
autoincrementing fields to do this:

• Detailsare
These differ
useful
between
as primary
versions
keys
• Using integers
Usually the firsttoentry
reference
is assigned
rows is1,more
the next
efficient
2, and
• so
Weon.
would like the DBMS to do this

More SQL Data Definition


AUTO_INCREMENT
• Auto_increment keeps track of an id
number, adding one for each new statement
you add to your database.

CREATE TABLE Students (


student_ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(32) NOT NULL,
age INT NOT NULL )

• Then to add a statement:


INSERT INTO Students VALUES (NULL, ‘Gonzo’, 25 )

More SQL Data Definition


Sequences
• In Oracle we can also use a Sequence

• Autoincrements just go up in integers.

• A sequence is a user-defined source of numbers.

• We can declare several sequences, giving each a


name, a start point, and a step size.

• We can then generate unique numbers by asking for


the next element from a sequence.
More SQL Data Definition
Sequences in Oracle
• To declare a sequence:

CREATE SEQUENCE <name>


[START WITH <value>]
[INCREMENT BY <value>]

• If no START WITH or INCREMENT BY values are given


they default to 1

• To get the next value from a sequence


<sequence name>.nextVal

More SQL Data Definition


Sequence Example
• Creating a sequence
CREATE SEQUENCE mySeq START WITH 1

• Using a sequence
SELECT mySeq.nextVal FROM DUAL;

INSERT INTO Student


(stuID, stuName, stuAddress)
VALUES
(mySeq.nextVal, 'Steve Mills',
'13 Elm Street')

More SQL Data Definition


This Lecture in Exams
Track CD
cID Num Title Time aID cID Title Price
1 1 Violent 2391 1 Mix 9.99
1 2 Every Girl 4101 2 Compilation 12.99
2 3 Breather 2171
1 4 Part of Me 2791 Artist
2 1 Star 3621
2 2 Teaboy 4172 aID Name
1 Stellar
2 Cloudboy

More SQL Data Definition


This Lecture in Exams
Add £2.50 to the price of all CDs that cost more than £10.00.
(2 marks)
Add a new column, Genre, to the CD table. This column should
hold a string of up to 100 characters, and if no genre is provided
then it should default to the value “Unknown”.
(3 marks)
Add a track titled “Runnin” by the artist “Fat Freddy’s Drop”
which is 12 minutes and 27 second long to the CD titled
“Compilation”. For this part only, you may assume that the
tables contain exactly the information shown above.
(3 marks)

More SQL Data Definition


Next Lecture
• SQL SELECT
• WHERE clauses
• SELECT from multiple tables

• The genius of JOINS

• For more information


• Connolly and Begg Chapter 5

More SQL Data Definition

You might also like