You are on page 1of 48

 The name SQL is expanded as Structured Query

Language.
 Originally, SQL was called SEQUEL ( Structured
English QUEry Language)
 SQL uses the terms table, row and column for the
formal relational model terms relation, tuple and
attribute.
 The main SQL command for data definition is the
CREATE statement, which can be used to create
schemas, tables, types, domain as well as other
constructs.
 SQL schema is identified by a schema name and
includes an authorization identifier to indicate the
user or account who owns the schema, as well as
descriptors for each element in the schema.
 Schema elements includes tables, types,
constraints, views, domains, and other constructs
that describe the schema.
 A schema is created via the CREATE SCHEMA
statement, which can include all the schema
elements definitions.

CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

The CREATE TABLE Command in SQL


 The CREATE TABLE command is used to specify a
new relation by giving it a name and specifying its
attributes and initial constraints.

CREATE TABLE COMPANY.EMPLOYEE


rather than
CREATE TABLE EMPLOYEE
 The relations declared through CREATE TABLE
statements are called base tables because the
table and its rows are actually created and stored
by the DBMS.
Attribute Data Types and Domains in SQL
1. Numeric : Integer, Float, Decimals
2. Character-string: char, varchar
3. Bit-string: BLOB
4. Boolean: True / False
5. DATE: date
6. Timestamp: Date and Time fields
 Creation of Domain

CREATE DOMAIN SSN_TYPE AS CHAR(9)

 We can use SSN_TYPE in place of data type


CHAR(9).
 Creation of data types

CREATE TYPE location FROM VARCHAR(100);


 Specifying Attribute Constraints and
Attribute Defaults
 Since SQL allows NULLs as attribute values, a
constraint NOT NULL may be specified if NULL is
not permitted.
 It is also possible to define a default value for an
attribute by appending the clause DEFAULT
<value> to an attribute definition.
 If no default clause is specified, the default
default value is NULL for the attributes that do not
have the NOT NULL constraint.
Example:
Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’
 Another type of constraint can restrict attribute or
domain values using the CHECK clause following
an attribute or domain definition.
Example:
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND
Dnumber < 21);

You can create your own domain as follows:

Example:
CREATE DOMAIN D_NUM AS INTEGER CHECK
(D_NUM > 0 AND D_NUM < 21);
 Specifying Key and Referential Integrity
Constraints
The PRIMARY KEY constraint uniquely identifies
each record in a database table. Primary keys must
contain unique values, and cannot contain NULL
values. A table can have only one primary key, which
may consist of single or multiple fields.
Dnumber INT PRIMARY KEY;
The UNIQUE clause specifies alternate
(secondary) keys, The UNIQUE constraint ensures
that all values in a column are different. Both the
UNIQUE and PRIMARY KEY constraints are similar.
A table can have many UNIQUE constraints , but
only one PRIMARY KEY constraint per table.

Dname VARCHAR(15) UNIQUE;


 A FOREIGN KEY is a key used to link two tables
together. A FOREIGN KEY is a field (or collection of
fields) in one table that refers to the PRIMARY KEY
in another table.
 A referential integrity constraint can be violated
when tuples are inserted or deleted, or when a
foreign key or primary key attribute value is
modified.
 The schema designer can specify an alternative
action to be taken by attaching a referential
triggered action clause to any foreign key
constraint.
 The options include SET NULL, CASCADE, and
SET DEFAULT. An option must be qualified with
either ON DELETE or ON UPDATE.
Example:

FOREIGN KEY(Super_ssn) references EMPLOYEE(SSN) ON


DELETE SET NULL ON UPDATE CASCADE.

FOREIGN KEY (Dnumber) references


DEPARTMENT(Dnumber) ON DELETE CASCADE ON
UPDATE CASCADE.
 The action taken by the DBMS for SET NULL and
SET DEFAULT is the same for both ON DELETE and
ON UPDATE.
 The value of the affected referencing attributes is
changed to NULL for SET NULL and to the specified
default value of the referencing attribute for SET
DEFAULT.
 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 attributes to the update
primary key value for all the referencing tuples.
Constraint fk1 FOREIGN KEY(Mgrssn) references
EMPLOYEE(SSN)
 Table constraints can be created through CHECK
clause at the end of the CREATE TABLE statement.
 These are called as Row based constraints.

CHECK (Dept_create_date <= Mgr_start_date)


 The SELECT-FROM-WHERE structure o
Basic SQL Queries

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 expression that
identifies the tuples to be retrieved by the query
 Operators like =,<=,>,>=,<> can be used in the
condition.

SELCT clause is similar to the Project operator


in relational algebra.
WHERE clause is similar to the Select operator
in relational algebra
 Query1
 Retrieve the birth date and address of the employee
whose name is ‘John B Smith’

SELECT BDATE, ADDRESS


FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’

 This query selects the individual EMPLOYEE tuples that


satisfy the condition of the WHERE clause, then projects
the result on the BDATE and Address attributes listed in
the SELECT clause.
 Query 2:
 Retrieve the name and address of all employees
who work for the 'Research' department.

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)
 Query 3:
 For every project located in 'Stafford', list the
project number, the controlling department
number, and the department manager's last
name, address, and birth date.
SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford'

 Here, there are two join conditions


 The join condition DNUM=DNUMBER relates a
project to its controlling department
 The join condition MGRSSN=SSN relates the
controlling department to the employee who
manages that department.
 SQL allows the same name to be used for attributes
in different tables.
 Assume that Dno and Fname attributes in
EMPLOYEE table was called Dnumber and Name
and the Dname attribute of DEPARTMENT table
was called as Name.

SELECT NAME, LNAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE NAME='Research' AND DNUMBER=DNUMBER
 Solution:

SELECT EMPLOYEE.NAME, LNAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.NAME='Research' AND
DEPARTMENT.DNUMBER=EMPLOYEE.DNUMBER
SELECT E.NAME, E.LNAME, E.ADDRESS
FROM EMPLOYEE as E, DEPARTMENT as D
WHERE D.NAME='Research' AND
D.DNUMBER=E.DNUMBER
 Some queries need to refer to the same relation twice
 In this case, aliases are given to the relation name
 Query :For each employee, retrieve the employee's
name, and the name of his or her immediate
supervisor.

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN

 In the query, 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.
 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 : Retrieve the SSN values for all employees.

SELECT SSN
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
 Example:

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
 To retrieve all the attribute values of the selected
tuples, a * is used, which stands for all the attributes
Examples:

Query: SELECT *
FROM EMPLOYEE
WHERE DNO=5

Query: SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER
 SQL treats a table as multiset rather than as a set.
 Duplicate tuples can appear more than once in a tuple.
 SQL doesn’t remove duplicate tuples automatically in the
results of queries.
 To eliminate duplicate tuples in a query result, the
keyword DISTINCT is used
 For example, the result of Q may have duplicate SALARY
values whereas Q11A does not have any duplicate
values

Q: SELECT SALARY
FROM EMPLOYEE
QA: SELECT DISTINCT SALARY
FROM EMPLOYEE
 SQL has directly incorporated some set operations
 There is a union operation (UNION), and in some
versions of SQL there are set difference (EXCEPT)
and intersection (INTERSECT) operations
 The resulting relations of these set operations are
sets of tuples; duplicate tuples are eliminated from
the result
 The set operations apply only to union compatible
relations; the two relations must have the same
attributes and the attributes must appear in the
same order
 Query : Make a list of all project numbers for projects
that involve an employee whose last name is 'Smith' as
a worker or as a manager of the department that
controls the project.

(SELECT DISTINCT Pnumber


FROM PROJECT,DEPARTMENT,EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND
Lname=‘Smith’)

UNION

(SELECT DISTINCT Pnumber


FROM PROJECT,WORKS_ON,EMPLOYEE
WHERE Pnumber=PnoAND Essn=Ssn AND
Lname=‘Smith’)
 SQL also has corresponding multiset operations,
which are followed by the keyword ALL (UNION
ALL, EXCEPT ALL, INTERSECT ALL).
 Their results are multisets.
 The LIKE comparison operator is used to compare
partial strings
 Two reserved characters are used: '%' replaces an
arbitrary number of zero or more characters, and '_'
replaces a single character.
Query: Retrieve all employees whose address is in
Houston, Texas.

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE ADDRESS LIKE
'%Houston,TX%'
 Query: Find all the employees who were born during the
1950’s

SELECT Fname,Lname
FROM EMPLOYEE
WHERE BDATE LIKE ‘_ _5 _ _ _ _ _ _ _’

 Here, ‘5’ must be the third character of the string as per the
DATE format.
 If an underscore or % is to be used as literal character in the
string, the character should be preceded by an escape
character.
 Example: AB\_CD\%EF
 The standard arithmetic operators '+', '-'. '*', and '/'
(for addition, subtraction, multiplication, and division,
respectively) can be applied to numeric values in an
SQL query result
 Query : Show the effect of giving all employees who
work on the 'ProductX' project a 10% raise.

SELECT FNAME, LNAME, 1.1*SALARY


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN AND PNO=PNUMBER AND
PNAME='ProductX’
 BETWEEN OPERATOR
 Retrieve all employees in department 5 whose
salary is between 30,000 and 40,000.

SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000)
AND Dno=5

 The condition (Salary BETWEEN 30000 AND


40000) is equivalent to the condition ((Salary
>=30000) AND (Salary <=40000))
 The ORDER BY clause is used to sort the tuples in a
query result based on the values of some attribute(s)
 Retrieve a list of employees and the projects each
works in, ordered by the employee's department, and
within each department ordered alphabetically by
employee last name.
SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE, WORKS_ON,
PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME
 The default order is in ascending order of values.
 We can specify the keyword DESC if the results are
to be arranged in the descending order.
 The keyword ASC can be used to specify
ascending order explicitly.
 INSERT is used to add a single tuple(row) to a
relation(table).
 We need to specify the relation name and a list of
values for the tuple.
 The values should be listed in the same order in
which the corresponding attributes were specified
in the CREATE TABLE command.

INSERT INTO EMPLOYEE VALUES ( ‘John’ ,’B’, ’Smith’,


’123456789’, ’1972-01-01’, ’Houston, Texas’, ’M’, 35000,
’888665555’ ,4 )
 An alternate form of INSERT specifies explicitly the
attribute names that correspond to the values in the
new tuple
 Attributes with NULL values can be left out
 Example:
Insert a tuple for a new EMPLOYEE for whom we
only know the FNAME, LNAME, and SSN attributes.

INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)


VALUES ('Richard', 'Marini', '653298653')
 Another variation of INSERT allows insertion of
multiple tuples resulting from a query into a
relation.
 Example:
 Suppose we want to create a temporary table that has
the name, number of employees, and total salaries
for each department.
CREATE TABLE DEPTS_INFO (
DEPT_NAME VARCHAR(10),
NO_OF_EMPS INTEGER,
TOTAL_SAL INTEGER);

INSERT INTO DEPTS_INFO (DEPT_NAME,


NO_OF_EMPS, TOTAL_SAL)
SELECT DNAME, COUNT (*), SUM (SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO
GROUP BY DNAME ;
 Removes tuples from a relation
 Includes a WHERE-clause to select the tuples to
be deleted
 Referential integrity should be enforced
 Tuples are deleted from only one table at a time
(unless CASCADE is specified on a referential
integrity constraint)
 A missing WHERE-clause specifies that all tuples
in the relation are to be deleted; the table then
becomes an empty table
 The number of tuples deleted depends on the
number of tuples in the relation that satisfy the
WHERE-clause
 Examples:

1. DELETE FROM EMPLOYEE


WHERE LNAME='Brown’

2. DELETE FROM EMPLOYEE


WHERE SSN='123456789’

3. DELETE FROM EMPLOYEE


WHERE DNO IN
(SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')

4. DELETE FROM EMPLOYEE


 Used to modify attribute values of one or more
selected tuples
 A WHERE-clause selects the tuples to be modified
 An additional SET-clause specifies the attributes to
be modified and their new values
 Each command modifies tuples in the same relation
 Referential integrity should be enforced
 Example:
Change the location and controlling department
number of project number 10 to 'Bellaire' and 5,
respectively.

UPDATE PROJECT
SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10
 Example:
 Give all employees in the 'Research'
department a 10% raise in salary.
UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE
DNAME='Research')

 In this request, the modified SALARY value


depends on the original SALARY value in each
tuple
 The reference to the SALARY attribute on the
right of = refers to the old SALARY value before
modification
 The reference to the SALARY attribute on the left
of = refers to the new SALARY value after
modification

You might also like