Lecture-3: Structured Query Language-SQL
Course CSB2204: Database Systems
Assoc. Prof. Mohammed Gadelrab
School of Artificial Intelligence & Data Management
Badr University in Assiut (BUA)
Outline
What is SQL?
SQL as a Standard
SQL as a Language
SQL Data Definition
SQL Query & Data Manipulation
Spring 2025 BUA-AI & DM School 2
What is SQL?
BUA-AI & DM School 3
(1) SQL as a Standard
SQL has gone through many standards: starting with SQL-86 or SQL
1.A. SQL-92 is referred to as SQL-2.
Later standards (from SQL-1999) are divided into core specification
and specialized extensions. The extensions are implemented for
different applications – such as data mining, data warehousing,
multimedia etc.
SQL-2006 added XML features; In 2008 they added Object-oriented
features.
SQL-3 is the current standard which started with SQL-1999. It is not
fully implemented in any RDBMS.
Spring 2025 BUA-AI & DM School 4
(2) SQL as a Language
Structured Query language.
Considered one of the major reasons for the commercial success of relational databases.
SQL is an informal or practical rendering of the relational data model with syntax.
Features of SQL Language: DDL + DML and more:
Data definition
Data Manipulation
Transaction control
Security specification (Grant and Revoke)
Active databases
Multi-media
Distributed databases
Spring 2025 BUA-AI & DM School 5
SQL Data Definition
BUA-AI & DM School 6
Schema & Catalog
We cover the basic standard SQL syntax – there are variations in existing RDB
MS systems.
SQL schema:
Identified by a schema name.
Includes an authorization identifier and descriptors for each element.
Schema elements include:
Tables, constraints, views, domains, and other constructs.
Each statement in SQL ends with a semicolon.
Example of CREATE SCHEMA statement (COMPANY is the schema name):
CREATE SCHEMA COMPANY AUTHORIZATION ‘Hossam’;
Catalog: Named collection of schemas in an SQL environment
Spring 2025 BUA-AI & DM School 7
Basic Data Types in SQL
Character-string data types:
char(n) Fixed length character string, with user-specified length n.
varchar(n) Variable length character strings, with user-specified maximum length n.
Numeric data types:
Int: Integer (a finite subset of the integers that is machine-dependent).
smallint: Small integer (a machine-dependent subset of the integer domain type).
numeric(p,d): Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be
stores exactly, but not 444.5 or 0.32)
real, double precision: Floating point and double-precision floating point numbers, with machine-dependent precision.
float(n): Floating point number, with user-specified precision of at least n digits.
Bit-string data types:
Fixed length: BIT(n)
Varying length: BIT VARYING(n)
Boolean data type: Values of TRUE or FALSE or NULL
DATE data type:
Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
DATE, TIME, Timestamp, INTERVAL data types can be cast or converted to string formats for comparison.
Spring 2025 BUA-AI & DM School 8
CREATE TABLE
An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
r is the name of the relation
each Ai is an attribute name in the schema of relation r
Di is the data type of values in the domain of attribute Ai
Can optionally specify schema:
CREATE TABLE COMPANY.EMPLOYEE …
OR: CREATE TABLE EMPLOYEE ...
Example:
create table instructor (
ID char(5),
name var rchar(20),
dept_name varchar(20),
salary numeric(8,2))
ERROR!!!!
Spring 2025 BUA-AI & DM School 9
Basic Constraints
Basic constraints: Relational Model has 3 basic constraint types that are supported in S QL:
Key constraint: A primary key value cannot be duplicated
Entity Integrity Constraint: A primary key value cannot be null
Referential integrity constraints: The “foreign key “ must have a value that is already present as a
primary key, or may be null.
Implications of Allowing NULL Foreign Keys: Allowing NULL values in foreign keys can impact your
database in several ways:
NULL values don’t violate rules but can affect how data is interpreted. Clearly define what NULL
represents in your database to avoid confusion.
NULL values indicate optional or missing links. Ensure your application handles these cases correctly
to avoid errors.
Queries involving NULL can be more complex. Ensure your SQL queries handle NULL values properly
for accurate results.
Spring 2025 BUA-AI & DM School 10
Integrity Constraints in CREATE TABLE
Types of integrity constraints
primary key (A1, ..., An )
foreign key (Am, ..., An ) references r
not null
SQL prevents any update to the database that violates an integrity constraint.
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);
Spring 2025 BUA-AI & DM School 11
Examples on Relation Definitions
1) create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);
2) create table course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references department);
3) create table takes (
ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year)
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);
Spring 2025 BUA-AI & DM School 12
Specifying Attribute Constraints
Default value of an attribute
DEFAULT <value>
NULL is not permitted for a particular attribute (NOT NULL)
CHECK clause
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
PRIMARY KEY clause
Specifies one or more attributes that make up the primary key of a relation
Dnumber INT PRIMARY KEY;
UNIQUE clause
Specifies alternate (secondary) keys (called CANDIDATE keys in the relational model).
Dname VARCHAR(15) UNIQUE;
FOREIGN KEY clause: Default operation: reject update on violation
Attach referential triggered action clause:
Options include SET NULL, CASCADE, and SET DEFAULT
Action taken by the DBMS for SET NULL or SET DEFAULT is the same for both ON DELETE and ON UPDATE
CASCADE option suitable for “relationship” relations
Spring 2025 BUA-AI & DM School 13
Example of Create Table with Constraints
Spring 2025 BUA-AI & DM School 14
SQL Queries & Data Manipulation
Spring 2025 BUA-AI & DM School 15
Basic Retrieval Queries in SQL
SELECT statement
One basic statement for retrieving information from a database.
SELECT lists the attributes desired in the result. It corresponds to “Projection” in relational algebra.
SELECT <Attribute List>
FROM <Table List>
[WHERE <Conditions>]
[ORDER BY <Attribute List>]
<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.
Use ORDER BY clause:
Keyword D E S C to see result in a descending order of values
Keyword A S C to specify ascending order explicitly
Typically placed at the end of the query
Spring 2025 BUA-AI & DM School 16
SELECT (cont.)
Example: find the names of all instructors:
select name
from instructor
NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.)
e.g., Name ≡ NAME ≡ name
Some people use UPPER CASE while others use bold font for SQL Keywords.
SQL allows duplicates in relations as well as in query results.
An asterisk in the select clause denotes “all attributes”
select * from instructor
To force the elimination of duplicates, insert the keyword distinct after select.
Find the department names of all instructors, and remove duplicates
select distinct dept_name
from instructor
The keyword all specifies that duplicates should not be removed.
select all dept_name
from instructor
Spring 2025 BUA-AI & DM School 17
Aggregate Functions
●
These functions operate on the multiset of values of a column of a relation, and return a scaler value.
●
The returned value is a scaler not a set not a relation.
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
●
Examples:
(1) Find the average salary of instructors in the Computer Science department
select avg (salary)
from instructor
where dept_name= 'Comp. Sci.';
(2) Find the total number of instructors who teach a course in the Spring 2018 semester
select count (distinct ID)
from teaches
where semester = 'Spring' and year = 2018;
(3) Find the number of tuples in the course relation
select count (*)
from course;
Spring 2025 BUA-AI & DM School 18
Aggregate Functions- Group by
●
Find the average salary of instructors in each department
select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name
●
Attributes in select clause outside of aggregate functions must appear in group by list
/* Bad query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
Spring 2025 BUA-AI & DM School 19
Aggregate Functions- Having Clause
●
Find the names and average salaries of all departments whose average salary is greater than
42000
select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name
having avg (salary) > 42000;
●
Note: predicates in the having clause are applied after the formation of groups whereas
predicates in the where clause are applied before forming groups
Spring 2025 BUA-AI & DM School 20
Nested Subqueries
Subquery: a query inside another query.
Keywords IN & NOT IN:
SELECT *
FROM students
WHERE student_ID IN (SELECT students_ID
FROM students
WHERE GPA > 3.4 AND Level = 2);
Spring 2025 BUA-AI & DM School 21
WHERE Clause
SQL allows the use of the logical connectives and, or, and not
The operands of the logical connectives can be expressions involving the comparison operators <, <=, >, >=, =, and <>.
Comparisons can be applied to results of arithmetic expressions
To find all instructors in Comp. Sci. dept with salary > 70000
select name
from instructor
where dept_name = 'Comp. Sci.' and salary > 70000
LIKE comparison operator: Used for string pattern matching
% replaces an arbitrary number of zero or more characters
underscore (_) replaces a single character
Examples:
WHERE Address LIKE ‘%Houston,TX%’;
WHERE Ssn LIKE ‘_ _ 1_ _ 8901’;
BETWEEN comparison operator:
WHERE(Salary BETWEEN 30000 AND 40000) AND Dno = 5;
Spring 2025 BUA-AI & DM School 22
Qualifiers & Alias
Same name can be used for two (or more) attributes in different relations:
As long as the attributes are in different relations
Must qualify the attribute name with the relation name to prevent ambiguity
Example:
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name=’Research’ AND DEPARTMENT.Dnumber=EMPLOYEE.Dnumber;
Using Aliases or renaming Table or Tuple Variables:
Example: 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;
Spring 2025 BUA-AI & DM School 23
Database Modification
Insert new tuples into a given relation
Delete tuples from a given relation.
Update values in some tuples in a given relation
Spring 2025 BUA-AI & DM School 24
Updates to Tables
Insert
insert into instructor values ('10211', 'Smith', 'Biology', 66000);
Delete
Remove all tuples from the student relation
delete from student
Drop Table
drop table r
Alter
alter table r add A D
where A is the name of the attribute to be added to relation r and D is the domain of A.
All exiting tuples in the relation are assigned null as the value for the new attribute.
alter table r drop A
where A is the name of an attribute of relation r
Dropping of attributes not supported by many databases.
Spring 2025 BUA-AI & DM School 25
Delete
Delete all instructors
delete from instructor
Delete all instructors from the Finance department
delete from instructor
where dept_name= 'Finance’;
Delete all tuples in the instructor relation for those instructors associated with a department located in the Watson building.
delete from instructor
where dept name in (select dept name
from department
where building = 'Watson');
Delete all instructors whose salary is less than the average salary of instructors
delete from instructor
where salary < (select avg (salary) from instructor);
Problem: as we delete tuples from instructor, the average salary changes
Solution used in SQL:
First, compute avg (salary) and find all tuples to delete
Next, delete all tuples found above (without recomputing avg or retesting the tuples)
Spring 2025 BUA-AI & DM School 26
Insert
Add a new tuple to course
insert into course
values ('CSB-2204', 'Database Systems', 'Comp. Sci.', 3);
or equivalently
insert into course (course_id, title, dept_name, credits)
values ('CSB-2204', 'Database Systems', 'Comp. Sci.', 3);
Add a new tuple to student with tot_creds set to null
insert into student
values ('3003', 'Green', 'Finance', null);
Make each student in the Music department who has earned more than 144 credit hours an instructor in the Music department with a
salary of $18,000.
insert into instructor
(select ID, name, dept_name, 18000
from student
where dept_name = 'Music' and total_cred > 144);
The inner select from where statement is evaluated fully before any of its results are inserted into the relation.
Otherwise queries like the following would cause problem:
insert into table1 select * from table1
Spring 2025 BUA-AI & DM School 27
Update…..Set
Give a 5% salary raise to all instructors:
update instructor
set salary = salary * 1.05
Give a 5% salary raise to those instructors who earn less than 70000
update instructor
set salary = salary * 1.05
where salary < 70000;
Give a 5% salary raise to instructors whose salary is less than average
update instructor
set salary = salary * 1.05
where salary < (select avg (salary)
from instructor);
Increase salaries of instructors whose salary is over $100,000 by 3%, and all others by a 5%. Write two update statements:
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
The order is important
Can be done better using the case statement (next slide)
Spring 2025 BUA-AI & DM School 28
Update…..Set
Give a 5% salary raise to all instructors:
update instructor
set salary = salary * 1.05
Give a 5% salary raise to those instructors who earn less than 70000
update instructor
set salary = salary * 1.05
where salary < 70000;
Give a 5% salary raise to instructors whose salary is less than average
update instructor
set salary = salary * 1.05
where salary < (select avg (salary)
from instructor);
Spring 2025 BUA-AI & DM School 29
Update…..Set
Increase salaries of instructors whose salary is over $100,000 by 3%, and all others by a 5%. By
writing two update statements:
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
There is a problem because order is important. Some instructors can have boththe 3% and the 5%
increase.
Can be done better using the case statement:
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
Spring 2025 BUA-AI & DM School 30
Example of CREATE, INSERT, SELECT
1) Create Tables:
CREATE TABLE Suppliers (
SupplierID INT AUTO_INCREMENT PRIMARY KEY,
SupplierName VARCHAR(100)
);
CREATE TABLE Products (
ProductID INT AUTO_INCREMENT PRIMARY KEY,
ProductName VARCHAR(100),
SupplierID INT,
FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID)
);
2) Insert Data into Tables:
INSERT INTO Suppliers (SupplierName) VALUES ('Acme Corp'), ('Global Supplies');
INSERT INTO Products (ProductName, SupplierID) VALUES ('Laptop', 1), ('Mouse', NULL);
(3) Select Data from Tables:
SELECT * FROM Suppliers;
SELECT * FROM Products;
BUA-AI & DM School 31
???
BUA-AI & DM School 32