Sunteți pe pagina 1din 21

CSC271 Database Systems

Data Definition Language

Dr. Khalid Latif


Creating a Database Instance

Syntax: Create Database <database-name>;


Example: Create Database Movies;
Variation: prevent error if database already exists.
Create Database IF NOT EXISTS <database-name>;
Example: Create Database IF NOT EXISTS Movies;
Another Variant
Syntax: Create Schema <database-name>
Example: Create Schema Movies

2
Deleting a Database Instance

Syntax: Drop Database <database-name>


Example: Drop Database CrickInfo
Variation: Prevent error if database does not exist.
Drop Database IF EXISTS <database-name>
Example: Drop Database IF EXISTS CrickInfo
Another Variant
Drop Schema <database-name>
Example: Drop Schema CrickInfo
Note: Be very careful, DROP DATABASE deletes all
tables in the database and the database.

3
Other DDL Commands

Selecting a database for further operations


Syntax: Use <database-name>
Example: Use Movies
Listing tables in a database
Syntax: Show Tables
Outcome: List of tables in the selected database
Structure/Metadata of a table
Syntax: Describe <Table-Name>
Example: Describe Friends
Syntax Variation: Show Columns From Friends

4
Steps in Creating a Table

1.Identify the attributes for the table.


2.Identify data types for attributes (Next Slide).
3.Identify constraints on columns.
1.Identify columns that can and cannot be null.
2.Identify columns that must be unique
(candidate keys).
3.Determine default values if any.
4.Identify primary keyforeign key combinations.
5.Create the table.
5
Common Data Types in SQL

date, datetime, time, real. Floating point and


year: Different date and double-precision floating
point numbers, with
time values machine-dependent
integer. A finite subset of
precision.
the integers that is float(n). Floating point
number, with user-
machine-dependent. specified precision of at
smallint, tinyint. Small least n digits.
and tiny integer. char(n). Fixed length
character string, with
numeric(p,d). Fixed user-specified length n.
point number, with user- varchar(n). Variable
specified precision of p length character strings,
digits, with n digits to the with user-specified
maximum length n.
right of decimal point.

6
Create Table Construct

An SQL relation is defined using the create table


command:
create table r (A1 D1 [constraint1], A2 D2, ...,
(integrity-constrainti), ...,)
r is the name of the relation
each Ai is an attribute name in the schema of relation r
Di is the data type of values in the domain of attribute Ai
Example:
create table Student
(id integer,
name char (30),
email varchar (50),
cgpa float)

7
Integrity Constraints

Domain integrity specifies that all columns in a relation


must be declared upon an atomic domain/datatype.
Entity integrity states that every table must have a
primary key and that the column or columns chosen to
be the primary key should be unique and not null.
Referential integrity states that any foreign-key value
refers to a primary key value of some table in the
database.
Depending on the application needs, a foreign-key
value may also be null meaning that the relationship
is optional (no relationship between instances).

8
Domain Integrity Constraints

Data type and length


Not Null: Attribute value cant be null
Example: name char(30) not null
Unique: Attribute value is unique throughout the table
Example: email char(30) unique
Example: email char(15) not null unique
Auto Increment: Attribute value automatically
incremented, only applicable for numeric values.
Example: id integer auto_increment
Default: Used to specify a default attribute value
Example: city char(30) default Islamabad
9
Entity Integrity Constraint

Primary key declaration automatically ensures


unique and not null for the specified set of
attributes.
primary key (A1, ..., An )
Example: Declare id as the primary key for
Student relation.
create table Student
(id integer AUTO_INCREMENT,
name char (30),
email varchar (50) not null,
primary key (id))

10
Referential Integrity Constraint

A column (or columns) from a database


table can reference the primary key of
another table to create relationships
between rows of the two tables.











11
Referential Integrity Constraint
Ensures that foreign key values of a table must match
primary key values of a related table.
[CONSTRAINT] FOREIGN KEY (col_name,...)
REFERENCES targer_table_name
(target_table_primary_column,...)
Example
createtable Student
(sid integer AUTO_INCREMENT,
name char (30), Column names could
pid integer, be different
primary key (id),
foreign key (pid) references Program (pid))

Column in Table and column


Student table referred by FK
12
Update and Delete Restrictions

 What to do with




 tuples of Student

 if relevant

 Program tuple is

deleted

Restrict: dont allow changes in primary side if related


rows exist in referred side
Cascade: automatically change referred side rows
that correspond with the changed primary side row
Set Null: set the foreign key in the referred side to null
if primary side is changed
Not allowed for weak entities (alternate: No Action)

13
Complete Foreign Key Declaration

[CONSTRAINT] FOREIGN KEY (col_name,...)


REFERENCES tbl_name (primary_col_name,...)
[ON DELETE {RESTRICT | CASCADE |
SET NULL | NO ACTION} ]
[ON UPDATE {RESTRICT | CASCADE |
SET NULL | NO ACTION} ]
create table Student (
Example

sid integer AUTO_INCREMENT,


name char (30),
pid integer,
primary key (id),
foreign key (pid) references Program (pid)
on delete RESTRICT on update CASCADE )
14
Schema (Pine Valley Furniture Company)

Referential
integrity
constraints are
drawn via arrows
from dependent
to primary table

15
Drop and Alter Table Constructs

The drop table command deletes all information


about the relation from the database and the alter
table command allows to change column
specifications.
Add attribute to an existing relation (null values)
alter table r add Attribute Domain
Drop attributes of a relation
alter table r drop Attribute
Change order of columns
alter table r modify Attribute1 after Attribute2

16
Views

Consider a sales agent who only needs to know details


of customers from Lahore.
SELECT * FROM Customer c WHERE c.city=Lahore
In some cases, it is not desirable for all users to see the
entire logical model (that is, all the actual relations stored
in the database.)
A view provides a mechanism to define data views;
rights and privileges can be defined for certain users.
So, a view is a virtual relation not originally belonging to
the conceptual model.

17
View Definition

A view is defined using the create view statement:


create view v as < query expression >
where <query expression> is any legal SQL expression.
The view name is represented by v.
A view consisting of customers from Lahore.
CREATEVIEW LahoriCustomers AS
SELECT * FROM Customer c
WHERE c.city=Lahore

18
View Usage

The view name can be used to refer to the virtual relation


that the view generates.
When a view is created, the query expression is stored in
the database; the expression is substituted into queries
involving the view.
Among Customers from Lahore, find the ones living in
Gulberg.
SELECT
name FROM LahoriCustomers
WHERE address LIKE %Gulberg%

19
View Types

Dynamic View
Avirtual table created dynamically
No data actually stored; data from the base table is
made available to user on request.
Based on SELECT statement on base tables or other
views
Materialized View (Supported in Oracle, for instance)
Copy or replication of data
Data actually stored on the disk
Refreshed periodically (or on every change) to match
the corresponding base table data

20
More on Views

A database cannot contain a base table and a view that


have the same name.
Views must have unique column names with no
duplicates.
By default, the names of the columns retrieved by the
SELECT statement are used for the view column
names.
To define explicit names for the view columns, a list of
comma-separated names should be provided.
create view v (column1, column2, ...) as <query>

21

S-ar putea să vă placă și