BASIC SQL
BASIC SQL
Structured Query Language
Statements for data definitions, queries, and updates (both DDL
and DML)
Each statement in SQL ends with a semicolon
WHAT CAN BE DONE USING SQL
execute queries on a database
retrieve data from a database
insert records in a database
update records in a database
delete records from a database
create new databases
create new tables in a database
create stored procedures in a database
create views in a database
set permissions on tables, procedures, and views
RELATIONAL ALGEBRA VS SQL
SELECT DISTINCT A1, A2, …… An
FROM R1, R2, …. Rn
WHERE P
========================
π A1, A2, ...... An (σ P ( R1 x R2 x ……….. x Rn)
COMPANY DATABASE
CREATE TABLE COMMAND
To create a new table in a database.
Specify each attributes and their data types (eg. INTEGER, FLOAT,
DECIMAL(i,j), CHAR(n), VARCHAR(n))
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE COMMAND
A constraint NOT NULL may be specified on an attribute
Can specify the primary key attributes, secondary keys and referential
integrity constraints (foreign keys).
CREATE TABLE DEPT
( DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9),
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP );
CREATE TABLE COMMAND EXAMPLE
CREATE TABLE COMMAND EXAMPLE
ATTRIBUTE DATA TYPES AND
DOMAINS
or
YYYY-MM-DD
or
or
ATTRIBUTE DATA TYPES AND
DOMAINS
ATTRIBUTE DATA TYPES AND
DOMAINS
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);
use SSN_TYPE in place of CHAR(9)
SPECIFYING ATTRIBUTE
CONSTRAINTS & ATTRIBUTE
DEFAULTS
NULL is not
permitted for
CREATE TABLE DEPT DNAME
( DNAME VARCHAR(10) NOT NULL,
MGRSSN CHAR(9) DEFAULT ‘N.A.’, Set Default
value for
MGRSTARTDATE CHAR(9), MGRSSN
UNIQUE (DNAME),
DNUMBER INT NOT NULL CHECK(DNUMBER > 0
AND DNUMBER <
21);
PRIMARY KEY (DNUMBER),
Limit
FOREIGN KEY (MGRSSN) the value range of EMP );
REFERENCES
DNUMBER
SPECIFYING CONSTRAINTS ON
TUPLES USING CHECK
CREATE TABLE DEPT
( DNAME VARCHAR(10) NOT NULL,
MGRSSN CHAR(9) DEFAULT ‘N.A.’,
MGRSTARTDATE DATE,
UNIQUE (DNAME), • Specified at the end of
CREATE TABLE
DNUMBER INT NOT NULL, command
• Apply to each tuple
D_CREATE_DATE DATE,
individually
PRIMARY KEY (DNUMBER),
FOREIGN KEY (MGRSSN) REFERENCES EMP,
CHECK (D_CREATE_DATE <= MGRSTARTDATE);
);
SPECIFYING KEY AND REFERENTIAL
INTEGRITY CONSTRAINTS
CREATE TABLE DEPARTMENT
( Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL, To specify Dnumber is a
Mgr_start_date DATE, Primary Key
PRIMARY KEY (Dnumber), To specify Dname is an
alternate/secondary key
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );
SPECIFYING KEY AND REFERENTIAL
INTEGRITY CONSTRAINTS (CONT.)
CREATE TABLE DEPT_LOCATIONS
It implies Dnumber of
( Dnumber INT NOT NULL,
DEPT_LOCATIONS table is
Dlocation VARCHAR(15) NOT NULL, referencing Dnumber of
DEPARTMENT table
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT (Dnumber)
ON DELETE CASCADE ON UPDATE CASCADE);
If a value is deleted/updated in Dnumber of DEPARTMENT table, what action is to
be taken for Dnumber of DEPT_LOCATIONS table.
Options include SET NULL, CASCADE, and SET DEFAULT
DML COMMANDS
THE INSERT COMMAND
CREATE TABLE EMPLOYEE
( Fname VARCHAR(15) NOT NULL,
Minit CHAR,
Lname VARCHAR(15) NOT NULL,
Ssn CHAR(9) NOT NULL,
Bdate DATE,
Address VARCHAR(30), Creating new
Sex CHAR, table in
Salary DECIMAL(10,2), database
Super_ssn CHAR(9),
Dno INT NOT NULL,
PRIMARY KEY (Ssn),
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn),
Inserting
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) );
entries in
EMPLOYEE
table
INSERT INTO EMPLOYEE VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’, ‘1962-
12-30’, ‘98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );
INSERT COMMAND (CONT.)
INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)
VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’); values must include all attributes
with NOT NULL specification
and no default value.
INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno)
rejected as EMPLOYEE Dno is
VALUES (‘Robert’, ‘Hatcher’, ‘980760540’, 2); foreign key of DEPARTMENT
table and there is no department
2
INSERT INTO EMPLOYEE (Fname, Lname, Dno)
VALUES (‘Robert’, ‘Hatcher’, 5); rejected as Ssn is defined NOT
NULL
BASIC RETRIEVAL QUERIES -
SELECT
Dname Dnumber Dlocation
Headquarters 1 Houston
Two or more
Administration 4 Stafford tuples that are
identical in all
Research 5 Bellaire
their attribute
Research 5 Sugarland values are
allowed in SQL
Administration 4 Stafford
Research 5 Houston
SELECT-FROM-WHERE STRUCTURE
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.
EXAMPLE
Query: Retrieve the birth date and address of the employee(s) whose
name is ‘John B. Smith’.
SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname= ‘John’ AND Minit =‘B’ AND Lname
=‘Smith’;
Output:
EXAMPLE
Query: 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;
Output:
EXAMPLE
Query: 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, Address, Bdate
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND
Plocation=‘Stafford’;
Output:
AMBIGUOUS ATTRIBUTE NAMES
Same name can be used for two (or more) attributes as long as the
attributes are in different relations
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name = ‘Research’ AND
DEPARTMENT.Dnumber = EMPLOYEE.Dnumber;
Specify table name along with attribute name whenever two tables
have same attribute names
ALIASING, RENAMING AND TUPLE
VARIABLES
Query: For each employee, retrieve the employee’s first and last name and the first
and last 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.Super_ssn = S.Ssn; Aliasing table
names.
Output:
Table & Attribute Aliasing: EMPLOYEE AS E (Fn, Mi, Ln, Ssn, Bd, Addr,
Sex, Sal, Sssn, Dno)
UNSPECIFIED WHERE CLAUSE
Query: Select all EMPLOYEE Ssns
SELECT Ssn
no condition on tuple
FROM EMPLOYEE; selection
Ssn
Output: 123456789
333445555
999887777
453453453
666884444
987654321
987987987
888665555
UNSPECIFIED WHERE CLAUSE (CONT.)
Query: Select all combinations of EMPLOYEE Ssn and DEPARTMENT
Dname in the database.
CROSS PRODUCT -
SELECT Ssn, Dname
All possible tuple
FROM EMPLOYEE, DEPARTMENT; combinations
Output:
USE OF THE ASTERISK
Query: Retrieve all the attribute values of any EMPLOYEE who
works in DEPARTMENT number 5
SELECT *
Retrieve all the attribute
FROM EMPLOYEE values of the selected
tuples
WHERE Dno=5;
Output:
WHAT IS OUTPUT?
Query 1:
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname = ‘Research’ AND Dno = Dnumber;
Query 2:
SELECT *
FROM EMPLOYEE, DEPARTMENT;
SOLUTION
Query 1 Output:
Super_ Mgr_ Mgr_
Fname Minit Lname Ssn Bdate Address Sex Salary Dno Dname Dnumber
ssn ssn start_date
… … … … … … … … … 5 Research 5 … …
… … … … … … … … … 5 Research 5 … …
… … … … … … … … … 5 Research 5 … …
… … … … … … … … … 5 Research 5 … …
… … … … … … … … … 5 Research 5 … …
Query 2 Output:
Super_ Mgr_ Mgr_
Fname Minit Lname Ssn Bdate Address Sex Salary Dno Dname Dnumber
ssn ssn start_date
… … … … … … … … … … … … … …
… … … … … … … … … … … … … …
… … … … … … … … … … … … … …
… … … … … … … … … … … … … …
… … … … … … … … … … … … … …
VARIATION OF INSERT COMMAND
CREATE TABLE WORKS_ON_INFO
( Emp_name VARCHAR(15),
Proj_name VARCHAR(15),
Hours_per_week DECIMAL(3,1) );
INSERT INTO WORKS_ON_INFO ( Emp_name, Proj_name,
Hours_per_week )
SELECT E.Lname, P.Pname, W.Hours
FROM PROJECT P, WORKS_ON W, EMPLOYEE E
WHERE P.Pnumber = W.Pno AND W.Essn = E.Ssn;
TABLES AS SETS
Query: Retrieve the salary of every employee.
SELECT ALL Salary
FROM EMPLOYEE;
Output:
SQL does not automatically
eliminate duplicate tuples in
query results
TABLES AS SETS (CONT.)
Query: Retrieve all distinct salary values.
SELECT DISTINCT Salary
FROM EMPLOYEE; Allows only distinct
tuples in the result
Output:
Applicable to union-compatible
relations i.e. the two relations
TABLES AS SETS (CONT.) should have the same attributes and
in the same order in both relations.
SET OPERATIONS
Operation Relational Algebra SQL
Difference - EXCEPT
Union U UNION
Intersection ∩ INTERSECT
EXAMPLE
Query: Make a list of all project numbers for projects that involve an employee whose
last name is ‘Smith’, either 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=Pno AND Essn=Ssn AND Lname=‘Smith’ );
Output:
Pnumber
1
2
TABLES AS SETS (CONT.)
Corresponding multiset operations: UNION ALL, EXCEPT ALL,
INTERSECT ALL)
Multiset Operations: duplicates are not eliminated
Example:
Relations R UNION ALL S R EXCEPT ALL S R INTERSECT ALL S
SUBSTRING PATTERN MATCHING
Query: Retrieve all employees whose address is in Houston, Texas.
SELECT Fname, Lname
Used for string pattern
FROM EMPLOYEE matching
WHERE Address LIKE ‘%Houston,TX%’;
Output: replaces an arbitrary
Fname Lname number of zero or
John Smith
more characters
Franklin Wong
Joyce English
Ahmad Jabbar
James Borg
SUBSTRING PATTERN MATCHING
(CONT.)
Query: Find all employees who were born during the 1950s.
Used for string pattern
SELECT Fname, Lname matching
FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 5 _ _ _ _ _ _ _’;
replaces a single
character
Output: Fname Lname
Franklin Wong
ARITHMETIC OPERATORS
Query: Show the resulting salaries if every employee working on the
‘ProductX’ project is given a 10 percent raise.
SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal
FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND
P.Pname=‘ProductX’;
Output:
Fname Lname Increased_sal
John Smith 33000
Joyce English 27500
ARITHMETIC OPERATORS (CONT.)
Query: Retrieve all employees in department 5 whose salary is between
$30,000 and $40,000.
((Salary >= 30000) AND (Salary <= 40000))
SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;
Output:
ORDERING OF QUERY RESULTS
Query: Retrieve a list of employees and the projects they are working on, ordered by department and, within each department,
ordered alphabetically by last name, then first name.
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE D.Dnumber=E.Dno AND E.Ssn=W.Essn AND W.Pno=
P.Pnumber
ORDER BY D.Dname, E.Lname, E.Fname;
• Default order is ascending.
• First order on Dname, if Dname same then on Lname, if Lname same then on
Fname
• Use ASC or DESC to change default order: ORDER BY D.Dname DESC,
E.Lname ASC, E.Fname ASC
ORDERING OF QUERY RESULTS (CONT.)
SUMMARY
SELECT <attribute list>
FROM <table list>
[ WHERE <condition> ]
[ ORDER BY <attribute list> ];
OPTIONAL
THE DELETE COMMAND
DELETE FROM EMPLOYEE
WHERE Lname=‘Brown’;
To specify the tuples to be
deleted
DELETE FROM EMPLOYEE
WHERE Ssn=‘123456789’;
missing WHERE clause
specifies that all tuples in the
DELETE FROM EMPLOYEE; relation are to be deleted. The table
remains in the database as an
empty table.
THE UPDATE COMMAND
Modify attribute
values of one or more
selected tuples
UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber=10;
To specify attributes to
be modified and new
values
UPDATE EMPLOYEE
SET Salary = Salary * 1.1
WHERE Dno = 5;
THANKS!!