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 -
INTInteger (machine-dependent)
-
SMALLINTSmall integer (machine-dependent)
-
NUMERIC(p, d)Fixed-point number, with user-specified precision of
pdigits (plus a sign), withddigits to the right of the decimal pointNUMERIC(3, 1)allows44.5to be stored exactly, but neither444.5or0.32can be stored exactly.
-
REAL,DOUBLE PRECISIONFloating-point and double precision floating-point numbers (machine-dependent precision)
-
FLOAT(n)Floating-point number, with user-specified precision of at least
ndigits
Basic schema definition
An SQL relation is defined using the CREATE TABLE command.
CREATE TABLE r
(
A_1 D_1,
... ,
A_n D_n,
[Integrity Constraint 1],
... ,
[Integrity Constraint k]
)r: Name of the relationA_i: Attribute name in the schema of the relationrD_i: Data type of values in the domain of attributeA_i
Example
CREATE TABLE instructor
(
ID CHAR(5),
name VARCHAR(20) NOT NULL,
dept_name VARCHAR(20),
salary NUMERIC(8, 2),
PRIMARY KEY(ID),
FOREIGN KEY(dept_name) REFERENCES department
);Integrity Constraints
PRIMARY KEY(A_1, ... , A_n)- Attributes
A_1, … ,A_nform 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 withUNIQUEconstraint specified) of some tuple in relations
- Values of attributes
NOT NULLNULLvalue is not allowed for that attribute
Updates to Tables
-
INSERT INTO s t- Inserts tuple
tinto the relations - e.g.,
INSERT INTO instructor VALUES('10211', 'Smith', 'Biology', 66000)
- Inserts tuple
-
DELETE FROM s t- Deletes tuple
tfrom the relationr - e.g.,
DELETE FROM studentdeletes all tuples from the relationstudent
- Deletes tuple
-
DROP TABLE r- Deletes all information of
r, including the table itself, from the database - After
ris dropped, no tuples can be inserted into it unless it is re-created with theCREATE TABLEcommand
- Deletes all information of
-
ALTER-
ALTER TABLE r ADD A D
Ais the name of the attribute to be added to relationr, andDis the domain ofAAll existing tuples in the relation are assigned
NULLas the value for the new attribute -
ALTER TABLE r DROP A
Ais the name of an attribute of relationr
-