Domain types in SQL
-
CHAR(n)
Fixed-length character string, with user-specified length
n
-
VARCHAR(n)
Variable-length character string, with user-specified maximum length
n
-
INT
Integer (machine-dependent)
-
SMALLINT
Small integer (machine-dependent)
-
NUMERIC(p, d)
Fixed-point number, with user-specified precision of
p
digits (plus a sign), withd
digits to the right of the decimal pointNUMERIC(3, 1)
allows44.5
to be stored exactly, but neither444.5
or0.32
can be stored exactly.
-
REAL
,DOUBLE PRECISION
Floating-point and double precision floating-point numbers (machine-dependent precision)
-
FLOAT(n)
Floating-point number, with user-specified precision of at least
n
digits
Basic schema definition
An SQL relation is defined using the CREATE TABLE
command.
r
: Name of the relationA_i
: Attribute name in the schema of the relationr
D_i
: Data type of values in the domain of attributeA_i
Example
Integrity Constraints
PRIMARY KEY(A_1, ... , A_n)
- Attributes
A_1
, … ,A_n
form the primary key for the relation. - Required to be non-null and unique.
- Attributes
FOREIGN KEY(A_1, ... , A_n) REFERENCES s
- Values of attributes
(A_1, ... , A_n)
for any tuple in the relation must correspond to values of the primary key attributes (or any attributes withUNIQUE
constraint specified) of some tuple in relations
- Values of attributes
NOT NULL
NULL
value is not allowed for that attribute
Updates to Tables
-
INSERT INTO s t
- Inserts tuple
t
into the relations
- e.g.,
INSERT INTO instructor VALUES('10211', 'Smith', 'Biology', 66000)
- Inserts tuple
-
DELETE FROM s t
- Deletes tuple
t
from the relationr
- e.g.,
DELETE FROM student
deletes all tuples from the relationstudent
- Deletes tuple
-
DROP TABLE r
- Deletes all information of
r
, including the table itself, from the database - After
r
is dropped, no tuples can be inserted into it unless it is re-created with theCREATE TABLE
command
- Deletes all information of
-
ALTER
-
ALTER TABLE r ADD A D
A
is the name of the attribute to be added to relationr
, andD
is the domain ofA
All existing tuples in the relation are assigned
NULL
as the value for the new attribute -
ALTER TABLE r DROP A
A
is the name of an attribute of relationr
-