_ SQL Statement Categories: DDL
Lesson 4: Data Definition
gpennoge (001) Pat
‘Statements for querying Statements for gsfning Statements for assigning
andmodiying daa database objects: securty permissions,
sseuecT CREATE GRANT
INSERT + ALTER, REVOKE
Sukanya Suranauwarat 2 teoate que
Graduate School of Applied Statistics, NIDA + DELETE
Focus of this lesson
16101 Date Design and Mamogemen!: Practical Agroch
* Databases _ Databases (2)
= Adatabase Is effectively a container for tables and = Example:
related metadata,
= Alayer of access security, AENTE DATABASE university
= In MySQL, a database is implemented as a file system
directory or folder that contains the files that represent
the tables in the database.
= Syntax
create database statement,i Tables ae Tables (2)
+ Each table has heading or defniton part and a body or + Besides column defintions, table definition can contains
content part ‘overal able options, index specifications, constraint
coun defons declaration and othor toms.
_— Syntax
CREATE TABLE (IF NO? SXISTS) (
s"type> {ceolund eptiona>]
{ae =
a Seed alee eats
cotimn
mettle 3) metitles (4)
Example + In MySOL, table definition i keptin «fxm fle in
talabese dreciory
( CREATE TABLE course ( = In MySQL 5.6.6 and higher, each InnoDB table and its
Zoorsehe Sanco), indexos are stored ina separlo ba daa fle by
Ceanitis — vancaanassy, eee
al sawane = Each such . ihc data fle represents an individual
tablespace
+ In MySQL 57.6, InnoDB invoduced genera
ano> or Descars= tablespaces, which ae shared tablespaces created
pate? fused io vow ie table definition eee eee eon ayia
980" CREATE. TABLE is used fo view the MySQL They canbe created outside of the MySQL data
creat able statement directory, aro capable of holding multiple tables, and
se ‘support tables of all row formats, sidespaecormon SQL Data Types
CHARIL)
\VARCHAR(L)
INTEGER
FLOATIP)
= DECIMAL(W, R)
= Date/Time: DATE, TIME, TIMESTAMP
= BOOLEAN
Data Type Options (2)
‘= ZEROPILL
+ Pads the displayed value with zeros up to the
display width
invoice INTEGER(6) Z8ROPILL NOT NULL
‘Can the data type options be placed
after the column options?
det!
= Data Type Options
‘= UNSIGNED
«= Prevents the negative part of a range from being
Used.
+ Additionally for integers the positive side of the
range is effectively doubled.
age TINYINT UNSIGNED No? NULL
price DECTMAL(S,2) UNSIGNED NOT NULL
DECIAL(2) can store any wt fr ot and tdci,
as Constraints
= Aconstraint isa rule that a relational database must,
satisfy in order to be valid
= Types:
«= Primary Key (PK)
«= Foreign Key (FK)
= Unique
= Required (NOT NULL)
= Check
= Placement:
«= Inline (as part ofa column definition)
«= External (after column definitions)
ieConstraint Placement Examples:
Oracle
+ Inine: constraint keyword and constraint namo are optional
isso, CUAR/C) GOWSYRAIIT PRCouree PRIMARY MOY (Coureeto)
SEES VRIGIAK 2S8) CONSTHAIDT Dntquatratieie
‘Durgue (crenssie),
+ Extomat: constraint keyword and constant name aro optional
Eestitle VARCHAR (255),
EONSTHAINY Uniqueceatitie UNIQUE (CeeTatie)
Constraint Syntax Examples
= Inline / Extemal:
sie)
+ cousreaiu ex0fSe=N0 KEY (0fFe=No)
(-Staclase 1m (°#R', "80", "IR, 188") )
coustaarie offvearvalid cus ( offYoar > 1970)
sles
Constraint Placement Examples:
= MySQL
+ nine: constant keyword and constant namo are ot alowed
+ Extornat: constant keyword and consraint name are optional
| SOMBAAIOT Gniguecratieke IgEN(Geenitaa)
ae constrint Syntax Examples (2)
Inline Only:
= External Only:
PRIMARY KEY OEferto, StdNoy
ies Sample Tables
Student
Offering
Enrollment
= Constraint Examples: student
(Gesciaee Gm CMR, $0"
sam, 8m 9 9,
Gick(sedcen serwe! om '6)
slide 19
pefesreotical Depiction
ae constrint Examples: enrollment
(CREATE TASLE Enzoliaent (
stave CHARAaL)
Barcrade DECIMAL (3,2),
(c#fenio, stato),
(CONSTRAINT FKOEterio FOREIGN KEY (OfferHo)
[REFERENCES Offering (OfferNo),
(CONSTRAINT FKStANo FOREIGN KEY (Sto)
REFERENCES Student (StaNo)
ie 20i Constraint Examples: offering
caenne, nasi offering
Goureeio GARE)" now won,
‘CONSTRAINT TRCourueWo FOREIGN XEY (CourseNo}
SGEPERINGES Couese (Coueeeno).
Sinrenunces racaley” (Fecho}
* Foreign Key Constraints
= AFK is a column or combination of columns that is used
to establish and enforce a link between the data in two
tables.
= AF constraint does not have to be linked only to a PK
constraint in another table (i. parent table); can also
be defined to reference the columns of a UNIQUE
constraint in another table.
= AFK constraint can contain null values
‘= however, if any column of a composite FK constraint
contains nul values, verification of all values that
‘make up the FK constraint is skipped.
= We can create a foreign key by defining a FK constraint
when we create or modify a table, slide 28
ae Primary Key Constraints
= APKis a column or combination of columns that contain
values that uniquely identify each row in the table
= A table can have only one PK constraint
= Accolumn that participates in the PK constraint cannot
‘accept null values (Entity integrity constrain’).
= If PK constraint is defined on more than one column,
values may be duplicated within one column, but each
combination of values from all the columns in the PK
constraint definition must be unique.
= We can create a primary key by defining a PK constraint
when we create or modify a table.
+ Unique Constraints
= We can use UNIQUE constraints to make sure that no
duplicate values are entered in specific columns that do
‘not participate in a primary key.
= Although both a UNIQUE constraint and a PK constraint
‘enforce uniqueness, use a UNIQUE constraint instead
of a PK constraint when you want to enforce the
Uniqueness of a column, or combination of columns, that
is not the PK.
‘= Multiple UNIQUE constraints can be defined on a table,
‘whereas only one PK constraint can be defined on a
tablei Unique Constraints (2)
= A’so, unlike PK constraints, UNIQUE constraints allow
for the value NULL.
= AUNIQUE constraint can be referenced by a FOREIGN
KEY constraint
a Check Constraints
= CHECK constrains limits the values that are accepted
by one or more columns.
1 We can create a CHECK constraint with any Boolean
expression
= We can apply multiple CHECK constraints to a single
column.
= We can also apply a single CHECK constraint to
‘multiple columns by creating it atthe table level
= All columns must be from the table defined in the
CREATE TABLE statement
i NOT NULL Constraints
‘= NULL means that no entry has been made,
«= implies thatthe value Is either unknown or undefined.
= We can disallow nul values for a column by using the
NOT NULL constraints.
Notes on INSERT STATEMENT:
‘owe NULL
a Check Constraints (2)
‘+ SQL compilers wll not permit check constraints that
involve columns from a tebe diferent than table
+ MySOL does not support check consrant.
* We can define them in our DDL statement for
compaiiy reasons but they ae just ignored_ Referential Integrity Constraint
1 Referential integrity constraint:
‘The value ofa foreign key
‘must either:
+ match one of the values
ofthe primary key in the
referred table, or
+ be nul
= Referentialintogrity constraint
places an ordering on:
+ insertion of rows from
diferent tables, and
+ dropping related tables.
= Delete Cascade
= Delete Set-to-Null
= Update:
1 Update Restrict
= Update Cascade
= Update Setto-Nul
slide 31
Referential Integrity Constraint (2)
‘= Operations on child table (Le. table with a FK)
Insert
= update
that violate the constraint, then an error is generated,
and that modification is not allowed,
= Operations on parent table (i, table with a PK)
= delete
= update
that violates the constraint and ifthe referential integrity
‘was defined initially with some special options then itis.
possible for tho DBMS to automatically modify the child
table so that the constraint isnot violated, “des
as Delete / Update Restrict Option
1» The delete restrict option (default option) does not allow
‘a record to be deleted if its PK value is referred to by
FK value,
'= The update restrict option (default option) does not allow
the PK value of a record to be changed ifits PK value is
referred by a FK value.
a sidesDelete Cascade Option
ARE emoioyee
SS
Update Cascade Option
he: Set-to-Null Option
uaa 20)
Ser ae.
mtan FEY (pels) aaranencrs gpersnee
ies
_s epee Set-to-Null Option
Fonston SEY (Gupela} RECERENCES daparenen=
Ve
sie
ie= Index.
‘= An indexis used to improve the speed of retrieval for
‘queries that take advantage of it
«= tis the difference between full table scans and
immediate location of tuples
+= Orders of magnitude performance difference
= Undertying data structures
+= Balanced trees (B trees, B+ trees)
= Hash tables
Index: Conceptual View
(CREATE TWOEK eustaane index OM eustoner (custnanel +
———— ie 9
Full Table Scan
maetnden: B-Tree
sie 8
se
deomaetncex Issues ets of Indexes
‘= Slows data manipulation operations because itis ‘= Single-Column Indexes
‘dynamically maintained «= Index on a single column of a table
+ Index creation can be a faily time consuming operation Unique inden,
= Also requires additional storage space = Perform the same way as regular index
1» Too many indexes are a bad thing += Disallow duplicate values
+= Composite Indexes
«= Index on two or more columns of a table.
‘Implicit Indexes
= Are automaticaly created
= Ex: PK and unique constraints
= Why are indexes automatically created for thes
site constraints? sheet
Index Syntax as Autoincrement
‘CREATE INDEX ON + Example!
(«column_name>) ;
= CREATE INDEX ON name YARGHAR(ZSS) ~
(, ) 2 gee ee
state CHARIZ),
sip CHAR(20}
= CREATE UNIQUE INDEX ON vs )
(): ~ ~
1» Only one column can be given AU20_INCREMENT and
that column must be:
+ an integer of some types, and
slide a3 + an index dese
= DROP INDEX ON yvate” Table: Add / Drop a Column
‘9D [COUN] {eoluan_option]
[eaner | APTER Zeolname>
Dade" (COLUMN)
matter Table: Add / Drop a Constraint
ALTER TABLE. s
straint name>]
slide 7
vette” Table: Alter a Column
Caer feos) Zola colame_cane>
complete nov colusn definitions (E28Gt T AMIEN-cevinene>)
X J
as View
1 Aview is a saved query,
‘= A view looks like a table and acts like a table as far as a
user is concemed. It contain no data,
= Aviowis stored as a . Frm fle just lke any table in the
database directory.
= Definition and properties stored as plain text.
«= Its check sum must be correct for view to be useable.
1 Syntax:
eas+ Why Use Views
= To reuse SQL statements.
= To simplify complex SQL operations. After the query is
written, it can be reused easily, without having to know
the details of the underlying query itself.
= To expose parts ofa table instead of complete tables.
1 To secure data. Users can be given access to specific
sub-sets of tables instead of to entire tables,
= To change data formatting and representation, Views
can retum data formatted and presented differently from
their underlying tables.