Introduction To SQL
Introduction To SQL
INTRODUCTION TO
Outline
• Overview of The SQL Query Language
REAL
DOUBLE PRECISION
• Required data
• Domain constraints
• Entity integrity
• Referential integrity
• Enterprise constrains
Syntax:
columnName dataType [NOT NULL | NULL]
Example:
position VARCHAR(10) NOT NULL
Example:
sex CHAR NOT NULL
CHECK (sex In (‘M’, ‘F’))
bno INT
CHECK ( bno IN (SELECT branchno FROM branch) )
Example:
• RESTRICT, domain must not be used in any existing table, view or assertion.
• CASCADE, any column based on the domain is automatically changed to use the
underlying data type, column constraint and default clause.
Example:
• SQL rejects any operations that attempt to create duplication in the PK column.
• PK forbids NULL value.
Syntax:
• UNIQUE(attribute (,…))
• columnName dataType [NOT NULL| NULL] [UNIQUE]
Example:
cno VARCHAR(5) NOT NULL;
pno VARCHAR(5) NOT NULL;
UNIQUE(cno, pno);
pno VARCHAR(5) NOT NULL UNIQUE;
5/16/2017 AAU-School of Commerce 19
Referential Integrity
FOREIGN KEY
FOREIGN KEY clause is defined in the CREATE & ALTER TABLE statements.
Syntax:
FOREIGN KEY (FK column (,…))
REFERENCES table_name [(CK column (,…))]
Example:
FOREIGN KEY (bno) REFERENCES branch ;
FOREIGN KEY (bno) REFERENCES branch (branchNo);
• SQL rejects any INSET or UPDATE operation that attempts to create a foreign
key value without a matching CK value key.
• UPDATE or DELETE operation for a CK clause that has matching rows in
another table is dependent on the referential action specified using ON UPDATE
& ON DELETE subclauses.
• CASCADE: automatically delete/update the CK row & all matching (FKs) rows in child table.
• SET NULL: delete/update the CK row & set the FK values to NULL. Valid only if
NOT NULL clause is not specified for the FK.
• SET DEFAULT: delete/update the CK row & set the FK values to default. Valid only if
DEFAULT clause is specified for the FK.
• NO ACTION: rejects the delete/update operation.
Syntax:
FOREIGN KEY ( FK column (,…) )
REFERENCES tablename [ ( CK column (,…) ) ]
[ ON UPDATE [ CASCADE | SET NULL| SET DEFAULT| NO ACTION ] ]
[ ON DELETE [ CASCADE | SET NULL| SET DEFAULT| NO ACTION ] ]
Example:
Proceed the constraint by the CONSTRIANT clause then specify a name for the
constraint.
Example:
CONSTRAINT IDISKey
PRIMARY KEY (SSN)
Syntax
CREATE DATABASE database_name;
Example:
Syntax
DROP DATABASE database_name;
Example
DROP DATABSE company;
CONSTRAINT EmpFK
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber)
ON DELETE SET DEFAULT ON UPDATE CASCADE
);
• CASCADE, drop operation drops all column from objects it is referenced by.
Example:
Remove the address attribute from the staff table.
Example:
Change the staff table by removing the default of ‘Assistant’ for the position column
and setting the default for the sex column to female.
Example:
Change the employee table by making name a primary key other than Id.
Example:
Change the Client table by adding a new column representing the preferred number
of rooms.
Syntax
DROP TABLE tablename [RESTRICT | CASCADE];
• RESTRICT, drop operation is rejected if there are any other objects that depend for
their existence upon the existence of the table to be dropped.
Syntax
CREATE [UNIQUE] INDEX IndexName
ON tableName (columnName [ASC | DESC] [,…])
Example:
Syntax
DROP INDEX Indexname;
SELECT
INSERT INTO
UPDATE
DELETE FROM
OR
SELECT *
FROM staff;
List salaries of all staff, showing only the staff number, the first and last
name, and salary.
Syntax
SELECT [DISTINCT|ALL] {* | column |column_expression [,…]}
FROM table_name;
Manager Manager
Assistant Assistant
Supervisor Supervisor
Assistant
SELECT DISTINCT position
Manager
FROM staff;
SELECT position
FROM staff;
Syntax
SELECT {* | column| column_expression [AS new_name] [,…]}
FROM table_name;
List the monthly salaries for all staff, showing the staff number, the first and last
names.
SELECT sno, fname, lname, salary/12 AS MonthlySalary
FROM staff;
▪ Range: Test whether the value of an expression falls within a specified range of
values (BETWEEN/ NOT BETWEEN).
▪ Set membership: Test whether the value of an expression equals one of a set of
values (IN/ NOT IN).
▪ Pattern match: Test whether a string matches a specified pattern (LIKE/ NOT
LIKE).
▪ NULL: Test whether a column has null value (IS NULL/ IS NOT NULL).
Syntax
SELECT [DISTINCT|ALL] {* | column| [column_expression [AS
new_name]] [,…]}
FROM table_name
[WHERE condition];
List all staff with a salary greater than 10,000. showing number, name and
salary.
Order of evaluation:
• Expression is evaluated left to right
• Between brackets
• NOT
• AND
• OR
Example:
▪ Address LIKE ‘H%’ means that the first character must be H, but the rest can be
anything.
▪ Address LIKE ‘H_ _ _’ means that there must be exactly four characters in the
string, the first of which must be H.
▪ Address LIKE ‘%e’ means any sequence of characters, of length at least 1, with
the last character an e.
▪ Address LIKE ‘%Glasgow%’ means a sequence of characters of any length
containing Glasgow.
▪ Address
5/16/2017
NOT LIKE ‘H%’ meansAAU-School
the firstofcharacter
Commerce
can not be H. 53
Simple Queries
LIKE/ NOT LIKE
If the search string can include the pattern-matching character itself, we can
use an escape character to represent the pattern matching character.
Example: STAFF(sno, fname, lname, position, sex, dob, salary, address, bno)
Example:
List the details of all viewing on property PG4 where a comment has not been
supplied.
SELECT clientno, ViewDate
FROM viewing
WHERE PropertyNo= ‘PG4’ AND comment IS NULL;
List all employees in department 5 whose salary is between Birr 30,000 &
Birr40,000.
Syntax
SELECT {* | [column_expression] [,…]}
FROM table_name
[ORDER BY column_list [ASC|DESC] ]
Produce a list of salaries for all staff, arranged in descending order of salary.
SELECT sno, fname, lname, salary
FROM staff
ORDER BY salary DESC;
List all employees, ordered by department and, within each department, ordered
alphabetically by last name, first name.
Examples:
count
Find the total number of Managers and the sum of their salaries.
count sum
2 54000
Example:
STAFF(sno, fname, lname, position, sex, dob, salary, bno)
Find the number of staff working in each branch and the sum of their
salaries.
SELECT bno, COUNT(sno) AS count, SUM(salary) AS sum
FROM staff
bno count sum
GROUP BY bno;
B003 3 54000
B005 2 39000
B007 1 9000
5/16/2017 AAU-School of Commerce 65
Simple Queries
GROUP BY clause
Example:
For each branch office with more than one member of staff, find the number of
staff working in each branch and the sum of their salaries.
SELECT bno, COUNT(sno) AS count, SUM(salary) AS sum
FROM staff
bno count sum
GROUP BY bno
HAVING COUNT(sno) > 1; B003 3 54000
B005 2 39000
For each project on which more than two employees work, retrieve the project
number and the number of employees who work on the project.
A subselect can be used in the WHERE and HAVING clauses of the outer
SELECT statement (nested query).
Type of subquery:
▪ A scalar subquery returns a single column and a single row (singlevalue).
▪ A row subquery returns multiple columns, but a single row.
▪ A table subquery returns one or more columns and multiple rows.
Example:
List the staff who work in the branch at ‘163 Main St’.
Example:
List the staff whose salary is greater than the average salary, and list by how
much their salary is greater than the average.
Example:
List the properties that are handled by staff who work in the branch at ‘163 Main
St’.
Show the resulting salaries if every employee working on ‘X’ project is given all %10
raise.
▪ If the subquery is preceded by the keyword ALL, the condition will only be
true if it is satisfied by all values produced by the subquery.
Example:
Find staff whose salary is larger than the salary of at least one member of
staff at branch B3.
Example:
Find staff whose salary is larger than the salary of every member of staff at
branch B3.
For each department that has more than 5 employees, retrieve the department
number and the number of its employees who are making more than $40,000.
Example:
List the names of all clients who have viewed a property along with any
comment supplied.
SELECT c.clientNo, fname, lname, propertyNo, comment
FROM client c, viewing v
WHERE c.clientNo = v.clientNo;
PROPERTYFORRENT (pno, street, area, city, pcode, type, rooms, rent, sno)
STAFF (sno, fname, lname, position, sex, DOB, salary, bno)
BRANCH (bno, street, city, postcode)
Example:
For each branch office, list the names of staff who manage properties, and
the properties they manage, ordered by branch number, staff number and
property number.
SELECT s.bno, s.sno, fname, lname, pno
FROM staff s, propertyforrent p
WHERE s.sno = p.sno
ORDER BY s.bno, s.sno, p.pno;
List all employees and identify the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, first
name.
Example:
For each branch, list the staff who manage properties, including the city in which
the branch is located and the properties they manage.
SELECT b.bno, b.city, s.sno, fname, lname, pno
FROM branch b, staff s, propertyForRent p
WHERE b.bno = s.bno AND s.sno = p.sno;
Alternatives:
FROM (Branch b JOIN staff s USING bno) As bs
JOIN PropertyForRent p USING sno;
PROPERTYFORRENT (pno, street, area, city, pcode, type, rooms, rent, sno)
STAFF (sno, fname, lname, position, sex, DOB, salary, bno)
BRANCH (bno, street, city, postcode)
Exmaple:
Find the number of properties handled by each staff member and branch.
SELECT s.bno, s.sno, COUNT(*) AS count
FROM staff s, propertyForRent p
WHERE s.sno = p.sno
GROUP BY s.bno, s.sno;
The Cartesian product of two tables is another table consisting of all possible pairs of
rows from the two table.
The columns of the product table are all the columns of the first table followed by all
the columns of the second table.
• Form the Cartesian product of the tables named in the FROM clause.
• If there is a WHERE clause, apply the search condition to each row of the
product table, retaining those rows that satisfy the condition. In terms of the
relational algebra, this operation yields a restriction of the Cartesian product.
• For each remaining row, determine the value of each item in the SELECT list to
produce a single row in the result table.
• If SELECT DISTINCT has been specified, eliminate any duplicate rows from the
result table.
Example:
List the branch offices and properties that are in the same city along with any
unmatched branches.
Example:
List the branch offices and properties in the same city and any unmatched
property.
Example:
List the branch offices and properties that are in the same city and any
unmatched branches or properties.
Example:
PROPERTYFORRENT (pno, street, area, city, pcode, type, rooms, rent, sno)
STAFF (sno, fname, lname, position, sex, DOB, salary, bno)
BRANCH (bno, street, city, postcode)
Example:
Construct a list of all cities where there is either a branch office or a rental
property.
Example:
Insert a new row into the staff table supplying data for all columns.
Example:
Insert a new row into the staff table supplying data for all mandatory columns, knowing
that the sex and birth date are optional fields.
Alternative:
INSERT INTO staff
VALUES (‘SG16’, ‘Alan’, ‘Brown’, ‘Assistant’, NULL, NULL, 8300,
‘B003’);
Example:
Insert rows into the StaffPropCount table using the staff and property_for_rent
tables.
INSERT INTO staffPropCount
(SELECT s.sno, fname, lname, COUNT(*)
FROM staff s, PropertyForRent p
WHERE s.sno = p.sno
GROUP BY s.sno, fname, lname)
UNION
(SELECT sno, fname, lname, 0
FROM Staff
WHERE sno NOT IN (SELECT DISTINCT sno
FROM PropertyForRent));
5/16/2017 AAU-School of Commerce 103
Modifying Data in the DB
(UPDATE)
Syntax
UPDATE table_name
SET column_name1 = data_value1 [, column_namei =
data_valuei ...]
[WHERE search_condition]
Example:
Give all staff a 3% pay increase.
UPDATE staff
SET salary = salary * 1.03;
Example:
Give all managers a 3% pay increase.
UPDATE staff
SET salary = salary * 1.03
WHERE position = ‘Manager’;
Example:
Promote David Ford (sno = ‘SG14’) to Manager and change his salary to
$18,000.
UPDATE staff
SET position=‘Manager’, salary = 18000
WHERE sno=‘SG14’;
Example:
Delete all staff in branch B003.
DELETE FROM staff
WHERE bno = ‘B003’;
Example:
Delete all staff.
DELETE FROM staff;
SELECT *
FROM Manager3Staff;
Example:
Create a view for staff who manage properties for rent, which include the branch
number they work at, their staff number, and the number of properties they manage.
B003 SG14 1
B003 SG37 2
B005 SL41 1
B007 SA9 1
Syntax
DROP VIEW ViewName [RESTRICT | CASCADE];
• RESTRICT, drop operation is rejected if there are any other objects that depend for
their existence upon the existence of the view to be dropped.
• CASCADE, drop operation drops all views defined on the dropped view.
SELECT COUNT(cnt)
FROM StaffPropCount;
SELECT *
FROM StaffPropCount
WHERE cnt > 2;
All updates to a base relation are immediately reflected in all views that
reference that base relation.
• Every column in the SELECT statement is a column name (rather than constant,
expression, or aggregation function).
• Any row inserted through the view must not violate the integrity constraints of the
base table.
UPDATE Manager3Staff
SET bno = ‘B005’
WHERE sno = ‘SG37’;
UPDATE Manager3Staff
SET Salary = 9500
WHERE Sno = ‘SG37’;
5/16/2017 AAU-School of Commerce 123
SQL-DCL