Вы находитесь на странице: 1из 38

Structured Query Language

SQL
Ch.4
Part 1
DBMS Architecture
DBMS Languages
In DBMSs where a clear separation is maintained between the conceptual and internal levels,
• the data definition language (DDL), is used to specify the conceptual schema only.

• the storage definition language (SDL), is used to specify the internal schema. In most
relational DBMSs today, there is no specific language that performs the role of SDL. Instead,
defining physical storage structures to fine-tune the performance of the database system,
which is usually done by the DBA staff.

• For a true three-schema architecture, we would need a third language, the view definition
language (VDL), to specify user views and mappings to the conceptual schema, but in most
DBMSs the DDL is used to define both conceptual and external schemas.

• data manipulation language (DML) : used to manipulate the database after the database
schemas are compiled and the database is populated with data. Typical manipulations
include retrieval, insertion, deletion, and modification of the data.

• In current DBMSs, a comprehensive integrated language such as SQL is used that includes
constructs for conceptual schema definition, view definition, and data manipulation.
Structured Query Language SQL
• the SQL language provides a higher-level
declarative language interface, so the user
only specifies what the result is to be, leaving
the actual optimization and decisions on how
to execute the query to the DBMS.
History
• Originally, SQL was called SEQUEL (Structured
English QUEry Language) and was designed
and implemented at IBM Research as the
interface for an experimental relational
database system called SYSTEM R.

• SQL is now the standard language for


commercial relational DBMSs.
SQL Data Definition and Data Types
• SQL is a comprehensive database language: It
has statements for data definitions, queries,
and updates. Hence, it is both a DDL and a
DML.
• The storage definition part (SDL) was included
in SQL’s early versions, but is now typically
implemented as special commands for the
DBA in relational DBMSs.
SQL Data Definition and Data Types
• Terminology:
– Table, row, and column used for relational model
terms relation, tuple, and attribute
• CREATE statement
– Main SQL command for data definition
– can be used to create schemas, tables (relations),
and domains (as well as other constructs such as
views, assertions, and triggers).
SQL Schema and Catalog
• An SQL schema is identified by a schema name, and
includes an authorization identifier to indicate the
user or account who owns the schema,

CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

• As well as descriptors for each element in the schema.


Schema elements include tables, constraints, views,
domains, and other constructs (such as authorization
grants) that describe the schema.
SQL Schema and Catalog
• Catalog
– Named collection of schemas in an SQL environment
– contains a special schema called INFORMATION_SCHEMA,
which provides information on all the schemas in the catalog
and all the element descriptors in these schemas.
– Integrity constraints such as referential integrity can be defined
between relations only if they exist in schemas within the same
catalog. Schemas within the same catalog can also share certain
elements, such as domain definitions.

• SQL environment
– Installation of an SQL-compliant RDBMS on a computer system
The CREATE TABLE Command in SQL
• Specify a new relation
– Provide name
– Specify attributes and initial constraints
• Can optionally specify schema:
– CREATE TABLE COMPANY.EMPLOYEE ...
or
– CREATE TABLE EMPLOYEE ...

the SQL schema in which the relations are declared is implicitly specified
in the environment in which the CREATE TABLE statements are executed.
The CREATE TABLE Command in SQL
• The attributes are specified first, and each
attribute is given a name, a data type to specify
its domain of values, and any attribute
constraints, such as NOT NULL.

• The key, entity integrity, and referential integrity


constraints can be specified within the CREATE
TABLE statement after the attributes are
declared, or they can be added later using the
ALTER TABLE command (Chapter 5).
The CREATE TABLE Command in SQL:
Example
create table my_table (
column_a integer,
column_b integer,
column_c char(50),
column_d char(10),
(;
The CREATE TABLE Command in SQL
• Base tables (base relations)
– Created through CREATE Table statements
– Relation and its tuples are actually created and
stored as a file by the DBMS
• Virtual relations (CH.5(
– Created through the CREATE VIEW statement
– may or may not correspond to an actual physical
file
The CREATE TABLE Command in SQL
• In SQL, the attributes in a base table are
considered to be ordered in the sequence in
which they are specified in the CREATE
TABLE statement. However, rows (tuples)
are not considered to be ordered within a
relation.
The DROP Command in SQL
• Objects that are created in SQL can be deleted with
DROP command
• DROP command delete the structure and the
contents of the object

CREATE TABLE STUDENT( … );


DROP TABLE STUDENT

CREATE VIEW TRANSCRIPT as …


DROP VIEW CUSTOMER
Attribute Data Types and Domains in
SQL
• Basic data types
– Numeric data types
• Integer numbers: INTEGER, INT, and SMALLINT
• Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
– Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR
VARYING(n), CHARACTER VARYING(n)
Attribute Data Types and Domains in
SQL (cont’d.)
– Bit-string data types
• Fixed length: BIT(n)
• Varying length: BIT VARYING(n)
– Boolean data type
• Values of TRUE or FALSE or NULL
– DATE data type
• Ten positions
• Components are YEAR, MONTH, and DAY in the form
YYYY-MM-DD

Source: Ramez El-Masri and Shamkant Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
• Additional data types
– Timestamp data type (TIMESTAMP)
• Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal fractions of
seconds
• Optional WITH TIME ZONE qualifier
– INTERVAL data type
• Specifies a relative value that can be used to increment
or decrement an absolute value of a date, time, or
timestamp
Source: Ramez El-Masri and Shamkant Navathe
Attribute Data Types and Domains in
SQL (cont’d.)
• Domain
– Name used with the attribute specification
– Makes it easier to change the data type for a
domain that is used by numerous attributes
– Improves schema readability
– Example:
• CREATE DOMAIN SSN_TYPE AS CHAR(9);

Source: Ramez El-Masri and Shamkant Navathe


DATE Type
CREATE TABLE dates(
birthdate date ,
today date,
yesterday date,
lastyear date
)

insert into dates(birthdate,today,yesterday,lastyear)


values('2005-10-29',GETDATE(), GETDATE()-1, GETDATE()-365)

• select * from dates


Example: Company Database
Note: here some
foreign keys that may
cause errors because
they are specified
either via circular
references
(Super_ssn in the
EMPLOYEE table) or
because they refer to
a table that has not
yet been created
(Dno in the
EMPLOYEE table).

Solution:
ALTER TABLE
CONSTRAINTS
Specifying Constraints in SQL
• Basic constraints:
– Key and referential integrity constraints
– Restrictions on attribute domains and NULLs
– Constraints on individual tuples within a relation
Specifying Attribute Constraints and
Attribute Defaults
• NOT NULL
– The value cannot be empty
– NULL is not permitted for a particular attribute
• Default value
– DEFAULT <value>

create table my_table (


column_a integer default 0,
column_b integer not null,
column_c char(50) not null default 'ABC',
column_d char(10)
);
Specifying Constraints on Tuples Using
CHECK
• CHECK clause

– Apply to each tuple individually (be called tuple-based)


– is checked whenever a tuple is inserted or modified.

– Dnumber INT NOT NULL CHECK (Dnumber > 0 AND


Dnumber < 21);
– CHECK (Dept_create_date <= Mgr_start_date);
CHECK Clause Examples
create table gradereport(
studentID int primary key,
grade int CHECK(grade>=0 and grade <=100)
(;

insert into gradereport values (3,101) --error

create table numbers(


number1 int,
mumber2 int,
CHECK(number1 > number2 ),
CHECK(number1 > 0)
(;
ENUM type
CREATE TABLE shirts (
productID int primary key,
size VARCHAR(40) not null CHECK (size IN('x-small', 'small',
'medium', 'large', 'x-large')),
sex char not null CHECK(sex in ('F','M'))
)

INSERT INTO shirts VALUES (1, 'small', 'F')


INSERT INTO shirts VALUES (2, 'Small', 'F')
INSERT INTO shirts VALUES (3, 'Medium', 'M')
select * from shirts
Specifying Key and Referential Integrity
Constraints
• PRIMARY KEY clause
– Specifies one or more attributes that make up the
primary key of a relation
– Dnumber INT PRIMARY KEY;
• UNIQUE clause
– Specifies alternate (secondary) keys
– Dname VARCHAR(15) UNIQUE;
Specifying Key and Referential Integrity
Constraints (cont’d.)
• FOREIGN KEY clause
– Default operation: reject update on violation
– Attach referential triggered action clause
• Options include SET NULL, CASCADE, and SET
DEFAULT
• Action taken by the DBMS for SET NULL or SET
DEFAULT is the same for both ON DELETE and ON
UPDATE
• CASCADE option suitable for “relationship” relations
Composite Primary Key
create table my_table (
column_a integer not null,
column_b integer not null,
column_c char(50),
column_d char(10),
primary key (column_a, column_b)
(;
Composite Foreign Key
CREATE TABLE PTable (
Key1 varchar(20) not null,
Key2 date not null,
constraint PK_PTable PRIMARY KEY (Key1,Key2)
)

CREATE TABLE STable (


AutoID int IDENTITY(1,1) not null primary key,
Key1 varchar(20) not null,
Key2 date not null,
constraint FK_STable_PTable FOREIGN KEY
(Key1,Key2) references PTable (Key1,Key2))
)
Giving Names to Constraints
• Keyword CONSTRAINT
– Name a constraint
– Useful for later altering
– (Chapter 5)
Referential Triggered Action :Example
• ON DELETE SET NULL and ON UPDATE CASCADE
for the foreign key Super_ssn of EMPLOYEE means that :

• if the tuple for a supervising employee is deleted, the value


of Super_ssn is automatically set to NULL for all employee
tuples that were referencing the deleted employee tuple.

• If the Ssn value for a supervising employee is updated, the


new value is cascaded to Super_ssn for all employee tuples
referencing the updated employee tuple.
Referential Triggered Action
• In general, the action taken by the DBMS for SET NULL
or SET DEFAULT is the same for both ON DELETE
and ON UPDATE.

• The action for CASCADE ON DELETE is to delete all the


referencing tuples, whereas the action for CASCADE ON
UPDATE is to change the value of the referencing foreign
key attribute(s) to the updated (new) primary key value for
all the referencing tuples.

• is the responsibility of the database designer to choose the


appropriate action and to specify it in the database
schema.

Вам также может понравиться