0% found this document useful (0 votes)
53 views46 pages

SQL 1 - Data Type, DDL: Pham Thai Ky Trung

The document discusses SQL data types, how to define database schemas using data definition statements like CREATE DATABASE, CREATE TABLE, ALTER TABLE, and DROP TABLE. It also covers specifying constraints, modifying data using INSERT, DELETE, and UPDATE statements, and maintaining referential integrity between tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views46 pages

SQL 1 - Data Type, DDL: Pham Thai Ky Trung

The document discusses SQL data types, how to define database schemas using data definition statements like CREATE DATABASE, CREATE TABLE, ALTER TABLE, and DROP TABLE. It also covers specifying constraints, modifying data using INSERT, DELETE, and UPDATE statements, and maintaining referential integrity between tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

SQL 1 – Data type, DDL

Pham Thai Ky Trung


Objectives

• SQL Data Definition and Data Types


• Specifying Constraints in SQL
• Schema Change Statements in SQL
• Basic Queries in SQL

• Reference: Chapter 4

Database Management System 2/35


Overview of SQL

• Structured Query Language (SQL)


▪ DDL + DML
• Data Definition Languages
• Data Manipulation Languages
• SQL: standard language for commercial relation
DBMSs.
• Evolution
▪ ANSI and ISO: SQL (ANSI 1986)
called SQL-86 or SQL1
▪ SQL2 (SQL-92)
▪ SQL3 (SQL-99)

Database Management System 3/35


Attribute Data Types - Domains

• Attribute Data Types


▪ Numeric:
• Integer/Int, Smallint,
• Float/Real, Double Precision
• Decimal(i,j)/Dec(i,j), Numeric(i,j)
▪ Character-string
• Char(n)/Character(n)
• Varchar(n)/Char Varying(n)/Character Varying(n)
• Character Large Object (Clob): large text value
(document)
• nChar(n); nVarchar(n)

Database Management System 4/35


Attribute Data Types – Domains (2)

▪ Bit-string
• Bit(n)
• Bit Varying(n)
• Binary Large Object (Clob)
▪ Boolean: True/False – Null (Unknown)

Database Management System 5/35


Additional Data Types in SQL2 and
SQL-99
Has DATE, TIME, and TIMESTAMP data types
• DATE:
▪ Made up of year-month-day in the format
yyyy-mm-dd
• TIME:
▪ Made up of hour:minute:second in the format
hh:mm:ss
• TIME(i):
▪ Made up of hour:minute:second plus i additional
digits specifying fractions of a second
▪ format is hh:mm:ss:ii...i
Database Management System 6/35
Additional Data Types in SQL2 and
SQL-99 (2)
• TIMESTAMP:
▪ Has both DATE and TIME components
• INTERVAL:
▪ Specifies a relative value that can be used to
increment or decrement an absolute value
▪ Can be DAY/TIME intervals or YEAR/MONTH
intervals
▪ Can be positive or negative when added to or
subtracted from an absolute value, the result is
an absolute value

Database Management System 7/35


Domains

• To specify the data type of each attribute directly


• Syntax:
▪ CREATE DOMAIN <domain_name> AS <type>
• Ex: Create Domain Ssn_Type AS Char(9)
▪ DROP DOMAIN <domain_name>
Ex: Drop Domain Ssn_Type

Database Management System 8/35


Data Definition, Constraints, and
Schema Changes
• CREATE, DROP DATABASE.
• CREATE, DROP, and ALTER the descriptions of
the tables (relations) of a database.
• CREATE, DROP Database Schema.

Database Management System 9/35


Relational Database Schema

Database Management System 10/35


CREATE DATABASE

CREATE DATABASE <DB_Name>


DROP DATABASE <DB_Name>
EX: CREATE DATABASE Company
or: CREATE DATABASE Company ON PRIMARY
( NAME = 'Company',
FILENAME = 'D:\DATA\Company.mdf' ,
SIZE = 3072KB ,
MAXSIZE = UNLIMITED,
FILEGROWTH = 1024KB )
LOG ON
( NAME = 'Company_log',
FILENAME = 'C:\DATA\Company_log.ldf' ,
SIZE = 1024KB ,
MAXSIZE = 2048KB ,
FILEGROWTH = 10%)
Database Management System 11/35
CREATE TABLE

• Specifies a new base relation by giving it a name, and specifying each of


its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j),
CHAR(n), VARCHAR(n))
• A constraint NOT NULL may be specified on an attribute. The attributes
that are part of the primary key of each relation allways NOT NULL
CREATE TABLE <TABLE NAME> (
<Attribute1> <data type> [<constraint>],
<Attribute2> <data type> [<constraint>],

[<constraint>])
• Constraint:
NOT NULL PRIMARY KEY
UNIQUE
NULL FOREIGN KEY/REFERENCES
DEFAULT
CHECK
Database Management System 12/35
CREATE TABLE

Ex1: CREATE TABLE DEPARTMENT (


DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE DATE )

Database Management System 13/35


CREATE TABLE (2)

• In SQL2, can use the CREATE TABLE command for specifying


the primary key attributes, secondary keys, and referential
integrity constraints (foreign keys).
• Key attributes can be specified via the PRIMARY KEY and
UNIQUE phrases
Ex2: CREATE TABLE DEPT (
DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE DATE,
[Constraint PK_DNu] PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (Mgrssn) REFERENCES Employee(SSN))
Lưu ý: Khóa ngoại có thể chưa có ở table liên quan, nên có thể tạo sau
trong lệnh Alter Table.
Database Management System 14/35
DROP TABLE

• Used to remove a relation (base table) and its


definition
• The relation can no longer be used in queries,
updates, or any other commands since its
description no longer exists
• Example:
DROP TABLE DEPENDENT;
Lệnh Drop xóa bảng (cả DL + cấu trúc) ra khỏi CSDL. Lưu ý: nếu có
chứa tham chiếu thì phải xóa bảng tham chiếu trước. Nếu có tham
chiếu vòng thì phải xóa khóa để mất tham chiếu vòng trước rồi mới xóa
bảng.

Database Management System 15/35


ALTER TABLE

• Used to add an attribute to one of the base relations


ALTER TABLE <Table Name> ADD <Col name> <Data
Type> [<Constraint>]
▪ The new attribute will have NULLs in all the tuples of
the relation right after the command is executed;
hence, the NOT NULL constraint is not allowed for
such an attribute
• Ex: ALTER TABLE EMPLOYEE ADD JOB
VARCHAR(12);
The database users must still enter a value for the new
attribute JOB for each EMPLOYEE tuple.
▪ This can be done using the UPDATE command.
Database Management System 16/35
ALTER TABLE

• Used to delete an attribute.


ALTER TABLE <Table Name> DROP <Column Name>
[CASCADE| RESTRICT]
Ex: ALTER TABLE EMPLOYEE DROP Address CASCADE

• Used to Edit an attribute.


ALTER TABLE <Table Name> ALTER COLUMN <Column
Name> [SET DEFAULT <value>] [<New Data type>] […]
Ex: ALTER TABLE DEPARTMENT ALTER COLUMN
Mgr_ssn SET DEFAULT ‘333445555’
ALTER TABLE DEPARTMENT ALTER COLUMN Mgr_ssn
Char(10)

Database Management System 17/35


ALTER TABLE

• Used to add, drop constraint


ALTER TABLE <Table name> ADD CONSTRAINT
[<Constraint Name>] <Constraint>;
Ex: ALTER TABLE Employee ADD CONSTRAINT
fk_EmpDNo FOREIGN KEY(DNo) REFERENCES
Department(DNumber);
• ALTER TABLE <Table name> DROP
CONSTRAINT <Constraint Name> [CASCADE];
Ex: ALTER TABLE Employee DROP CONSTRAINT
fk_EmpDNo

Database Management System 18/35


Create Schema

• Specifies a new database schema by giving it a


name
▪ Authorization identifier
▪ Descriptors
• Schema elements: tables, constraints, views,
domains, …
• Statement create a schema:
▪ CREATE SCHEMA COMPANY
AUTHORIZATION Jsmith

Database Management System 19/35


Drop Schema

• If a whole schema is no longer needed.


• Syntax:
Drop Schema <schema_name> [Cascade|Restrict]
▪ Cascade: remove the database schema and all
its table, domains, and others elements
▪ Restrict: the schema is dropped only if it has no
elements in it.
• Example:
Drop Schema COMPANY Cascade;

Database Management System 20/35


Constraints in SQL

• Primary Key
• Foreign Key
• Null – Not Null
• Default <value>
• Check
• Ex: Dnumber Int Not Null Check (Dnumber > 0 And
Dnumber < 21)
Or
Create Domain D_Num as Integer Check (D_Num >
0 And D_Num < 21)
Dnumber D_Num Not Null

Database Management System 21/35


Referential Integrity Options

• We can specify RESTRICT, CASCADE, SET NULL or


SET DEFAULT on referential integrity constraints (foreign
keys)
CREATE TABLE DEPT (
DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9) DEFAULT ‘888665555’,
MGRSTARTDATE DATE,
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES
Emp(SSN) ON DELETE SET DEFAULT
ON UPDATE CASCADE);
Database Management System 22/35
Referential Integrity Options (2)

CREATE TABLE EMP (


ENAME VARCHAR(30) NOT NULL,
ESSN CHAR(9),
BDATE DATE,
DNO INTEGER DEFAULT 1,
SUPERSSN CHAR(9),
PRIMARY KEY (ESSN),
FOREIGN KEY (DNO) REFERENCES DEPT
ON DELETE SET DEFAULT
ON UPDATE CASCADE,
FOREIGN KEY (SUPERSSN) REFERENCES Emp(SSN)
ON DELETE SET NULL
ON UPDATE CASCADE)

Database Management System 23/35


Update Data

• There are three SQL commands to modify the


database:
▪ INSERT
▪ DELETE
▪ UPDATE

Database Management System 24/35


INSERT

• In its simplest form, it is used to add one or more tuples


to a relation
• Attribute values should be listed in the same order as the
attributes were specified in the CREATE TABLE
command
INSERT INTO <Table name> VALUES [(column_list)]
<value list>
• EX: INSERT INTO Employee VALUES
(Fname,init,lname) ('Richard','K','Marini‘)

• , '653298653', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M',


37000, '987654321', 4 )
Database Management System 25/35
Delete

• Removes tuples from a relation.


• Referential integrity should be enforced. Tuples are
deleted from only one table at a time (unless CASCADE
is specified on a referential integrity constraint)
• The number of tuples deleted depends on the number of
tuples in the relation that satisfy the WHERE-clause
DELETE FROM <Table name> [WHERE <conditions>]
• EX: DELETE FROM Employee
WHERE Lname='Brown’

Database Management System 26/35


Update

• Used to modify attribute values of one or more selected


tuples
UPDATE <Table name>
SET column_name1 = value, column_name2= value,…
[WHERE <conditions>]
Ex1: UPDATE Department
SET Mrg_SSN = '333445555'
WHERE DNo = 5

Database Management System 27/35


Retrieval Queries in SQL

• SQL has one basic statement for retrieving information


from a database; the SELECT statement
▪ This is not the same as the SELECT operation of the
relational algebra
• Important distinction between SQL and the formal
relational model:
▪ SQL allows a table (relation) to have two or more tuples
that are identical in all their attribute values
▪ Hence, an SQL relation (table) is a multi-set (sometimes
called a bag) of tuples; it is not a set of tuples
• SQL relations can be constrained to be sets by
specifying PRIMARY KEY or UNIQUE attributes, or by
using the DISTINCT option in a query

Database Management System 28/35


Retrieval Queries in SQL (2)

• A bag or multi-set is like a set, but an element


may appear more than once.
▪ Example: {A, B, C, A} is a bag. {A, B, C} is also a
bag that also is a set.
▪ Bags also resemble lists, but the order is
irrelevant in a bag.
• Example:
▪ {A, B, A} = {B, A, A} as bags
▪ However, [A, B, A] is not equal to [B, A, A] as lists

Database Management System 29/35


Retrieval Queries in SQL (3)

• Basic form of the SQL SELECT statement is called a


mapping or a SELECT-FROM-WHERE block

SELECT <attribute list>


FROM <table list>
WHERE <condition>
▪ <attribute list> is a list of attribute names whose values are
to be retrieved by the query
▪ <table list> is a list of the relation names required to
process the query
▪ <condition> is a conditional (Boolean) expression that
identifies the tuples to be retrieved by the query

Database Management System 30/35


Populated Database — Figure 5.6

Query 0:
Select BDate, Address
From Employee
Where FName = ‘John’
And MInit = ‘B’ And
LName = ‘Smith’;

BDate, Address
( FName = ‘John’ And MInit
= ‘B’ And LName =
‘Smith’(EMPLOYEE)))

Database Management System 31/35


Simple SQL Queries

• Basic SQL queries correspond to using the


following operations of the relational algebra:
▪ SELECT
▪ PROJECT
▪ JOIN
• All subsequent examples use the COMPANY
database

Database Management System 32/35


Simple SQL Queries (2)

• Example of a simple query on one relation


Query 0: Retrieve the birthdate and address of the
employee whose name is 'John B. Smith'.
Q0: SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname='John' AND Minit='B’ AND
Lname='Smith’

• Similar to a SELECT-PROJECT pair of relational algebra


operations:
• The SELECT-clause specifies the projection attributes and the
WHERE-clause specifies the selection condition
BDate, Address  FName = ‘John’ And MInit = ‘B’ And LName = ‘Smith’(EMPLOYEE)))
• However, the result of the query may contain duplicate tuples
Database Management System 33/35
Simple SQL Queries (3)

• Query 1: Retrieve the name and address of all employees


who work for the 'Research' department.

Q1: SELECT Fname, Lname, Address


FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=DNO

Similar to a SELECT-PROJECT-JOIN sequence of relational


algebra operations
▪ (Dname='Research') is a selection condition (corresponds to
a SELECT operation in relational algebra)
▪ (Dnumber=DNO) is a join condition (corresponds to a JOIN
operation in relational algebra)

Database Management System 34/35


Simple SQL Queries (4)

• Query 2: For every project located in 'Stafford', list the


project number, the controlling department number, and
the department manager's last name, address, and
birthdate.
Q2: SELECT Pnumber, Dnum, Lname, Bdate, Address
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn
AND Plocation='Stafford’

In Q2, there are two JOIN conditions:


▪ The join condition Dnum=Dnumber relates a project to its
controlling department
▪ The join condition Mgr_ssn=Ssn relates the controlling
department to the employee who manages that department

Database Management System 35/35


Aliases, * and DISTINCT, Empty
WHERE-clause
• In SQL, we can use the same name for two (or
more) attributes as long as the attributes are in
different relations
• A query that refers to two or more attributes with
the same name must qualify the attribute name
with the relation name by prefixing the relation
name to the attribute name
• Example:
EMPLOYEE.Lname,
DEPARTMENT.Dname

Database Management System 36/35


Aliases
• Some queries need to refer to the same relation twice. In this
case, aliases are given to the relation name
• Query 8: For each employee, retrieve the employee's name,
and the name of his or her immediate supervisor.

Q8: SELECT E.Fname, E.Lname, S.Fname, S.Lname


FROM EMPLOYEE E S
WHERE E.Super_ssn = S.Ssn
In Q8, the alternate relation names E and S are called aliases
or tuple variables for the EMPLOYEE relation
▪ We can think of E and S as two different copies of
EMPLOYEE; E represents employees in role of
supervisees and S represents employees in role of
supervisors
Database Management System 37/35
Aliases (2)

• Aliasing can also be used in any SQL query for convenience


(Alias cũng được sử dụng trong SQL để được thuận tiện – đơn giản và có thể
dùng từ khóa AS để chỉ alias)
• Can also use the AS keyword to specify aliases:

Q8: SELECT E.Fname, E.Lname, S.Fname, S.Lname


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn

Database Management System 38/35


UNSPECIFIED WHERE-clause

• A missing WHERE-clause indicates no condition;


hence, all tuples of the relations in the FROM-clause are
selected. This is equivalent to the condition WHERE TRUE
• Query 9: Retrieve the SSN values for all employees.
Q9: SELECT Ssn, Lname
FROM EMPLOYEE

• If more than one relation is specified in the FROM-clause


and there is no join condition, then the CARTESIAN
PRODUCT of tuples is selected

Database Management System 39/35


UNSPECIFIED WHERE-clause (2)

• Example:
Q10: SELECT Ssn, Dname
FROM EMPLOYEE, DEPARTMENT

▪ It is extremely important not to overlook


specifying any selection and join conditions in the
WHERE-clause; otherwise, incorrect and very
large relations may result

Database Management System 40/35


Use Of *

• To retrieve all the attribute values of the selected tuples,


a * is used, which stands for all the attributes
• Examples:
Q1C: SELECT *
FROM EMPLOYEE
WHERE Dno=5
Q1D: SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND
Dno=Dnumber

Database Management System 41/35


Use Of DISTINCT

• SQL does not treat a relation as a set; duplicate tuples


can appear.
• To eliminate duplicate tuples in a query result, the
keyword DISTINCT is used.
• For example, the result of Q11 may have duplicate
SALARY values whereas Q11A does not have any
duplicate values
Q11: SELECT Salary
FROM EMPLOYEE
Q11A: SELECT DISTINCT Salary
FROM EMPLOYEE

Database Management System 42/35


Use the LIKE

• Query 12: Retrieve all employees whose address is in


Houston.
Q12: SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘Houston%’;
• Query 14: Retrieve all employees in department 5 whose
salary is between $30,000 and $40,000.
Q14: SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000) AND Dno =5;

Database Management System 43/35


SQL Queries statement

• A query in SQL can consist of up to six clauses,


but only the first two, SELECT and FROM, are
mandatory. The clauses are specified in the
following order:

SELECT <attribute list>


FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>
[HAVING <group condition>]]
[ORDER BY <attribute list>]

Database Management System 44/36


SQL Queries statement

• The SELECT-clause lists the attributes or functions to be


retrieved
• The FROM-clause specifies all relations (or aliases) needed in
the query but not those needed in nested queries
• The WHERE-clause specifies the conditions for selection and
join of tuples from the relations specified in the FROM-clause
• GROUP BY specifies grouping attributes
• HAVING specifies a condition for selection of groups
• ORDER BY specifies an order for displaying the result of a
query
▪ A query is evaluated by first applying the WHERE-clause,
then GROUP BY and HAVING, and finally the SELECT-
clause
Database Management System 45/36
Q&A

Database Management System 46/35

You might also like