3 - Chapter 2 - Relational Model of Data - P2
3 - Chapter 2 - Relational Model of Data - P2
Session 3
Chapter 2 - Relational Model of Data - Part 2
Defining a Relation Schema in SQL
Objectives
2
2.3. Defining a relation Schema in SQL
2.3. Defining a Relation Schema in SQL
Every SQL Server database has at least two operating system files: a data file
and a log file.
- Data files contain data and objects (tables, stored procedures, and views,…)
- Log files contain the information that is required to recover all transactions
in the database.
2.3.3a Create Database
Example:
Create a database named QLSV with 10MB at the
beginning for the primary file and 5MB at the
beginning for the log file. Size of primary file and
log file can be up to 50 MB and 25 MB. The files
are stored in D:\DBI202.
2.3.3a Create Database
Syntax:
DROP DATABASE DatabaseName
Example:
DROP DATABASE QLSV
2.3.3c Modify Database Name
Syntax:
ALTER DATABASE database_name
Modify Name = new_database_name
Example:
ALTER DATABASE QLSV
Modify Name = QLSV_new
2.3.3d Modify Database File
[Use Database_Name]
CREATE TABLE TableName(
Attribute1 datatype [options],
Attribute2 datatype [options],
...
AttributeN datatype [options]
)
Example
Delete table:
[USE Database_Name]
DROP TABLE TableName;
Add attribute:
[USE Database_Name]
ALTER TABLE TableName
ADD
Attribute1 Datatype [Options],
Attribute2 Datatype [Options],
…;
2.3.5. Modifying Relation Schemas
Modify attribute:
[USE Database_Name]
ALTER TABLE TableName
ALTER COLUMN Attribute Datatype [Options];
Delete attribute:
[USE Database_Name]
ALTER TABLE TableName
DROP COLUMN Attribute1, Attribute2,…;
2.3.6. NULL Option
)
2.3.7. Default values
PRIMARY KEY:
[USE DatabaseName]
CREATE TABLE Table_Name(
Attribute1_Name Datatype PRIMARY KEY,
Attrbute2_Name DataType [OPTIONS],
…
);
Or
[USE DatabaseName]
CREATE TABLE Table_Name(
Attribute1_Name Datatype [OPTIONS],
…
PRIMARY KEY(AttributeKey1, AttributeKey2,…)
);
Or
[USE DatabaseName]
ALTER TABLE Table_Name ADD PRIMARY KEY(AttributeKey1, AttributeKey2,
…);
2.3.8. Declaring Keys
UNIQUE KEY:
[USE DatabaseName]
CREATE TABLE Table_Name(
Attribute1_Name Datatype [OPTIONS],
Attrbute2_Name DataType [OPTIONS] UNIQUE, …);
Or
[USE DatabaseName]
CREATE TABLE Table_Name(
Attribute1_Name Datatype [OPTIONS],
Attrbute2_Name DataType [OPTIONS],
…
UNIQUE(UniqueAttribute1, UniqueAttributeKey2,…)
);
Or
[USE DatabaseName]
ALTER TABLE Table_Name ADD UNIQUE(UniqueAttribute1,
UniqueAttributeKey2,…));
2.3.9. Identity option
IDENTITY:
IDENTITY (seed_value, increment_value);
Seed_value: initial value
Increment_value: increment step
INSERT:
INSERT into Table_Name(Attribute1, Attribute2, …)
VALUES (Attribute1_value1, Attribute2_value1, …),
(Attribute1_value2, Attribute2_value2, …),
…;
Example
2.3.10. UPDATE data in table
UPDATE:
UPDATE Table_Name
SET AttributeName = value,
[,…, Attribute_k= value_k]
[FROM ...]
[WHERE Conditions]
Example
2.3.10. DELETE data in table
DELETE:
DELETE From Table_Name
[FROM ...]
[WHERE Conditions]
Example