1
CHAPTER 4
STRUCTURED QUERY LANGUAGE
(SQL)
2
Structured Query Language
SQL,short for Structured Query Language is a
simple programming language used for accessing and
managing data in relational databases.
SQL can be divided into two parts:
The Data Manipulation Language (DML)
The Data Definition Language (DDL).
3
Types of SQL
DML
Retrieving and updating data.
Example : SELECT, UPDATE, DELETE, INSERT.
DDL
Defining the database structure and controlling access the
data.
Example: CREATE , ALTER , DROP.
4
Used of SQL
Allow user to create database and relation structure
Perform basic data management tasks, such as the
insertion, modification, and deletion of data from the
relations
5
DDL
The Data Definition Language (DDL) is used to create
and destroy databases and database objects.
These commands will primarily be used by database
administrators during the setup and removal phases of a
database project.
6
Creating Database and Table
Create database
Syntax: CREATE DATABASE database_name;
Example : CREATE DATABASE Company;
Create table
Syntax:
CREATE TABLE table_name
(
column_name1 data type1 [NULL|NOT NULL],
column_name1 data type2 …….
);
7
Create Table : Example
CREATE TABLE worker
(
workerno VARCHAR (5) NOT NULL,
workername VARCHAR (15),
position VARCHAR (15),
address VARCHAR (20),
entrydate DATE,
tel_no VARCHAR (7),
salary DECIMAL (7,0),
PRIMARY KEY (workerno)
);
8
WORKER TABLE
9
Another Table : Building
CREATE TABLE building
(
buildno VARCHAR( 5 ) NOT NULL,
address VARCHAR( 20 ) ,
city VARCHAR( 10 ) ,
buildtype VARCHAR( 10 ) ,
roomno INT,
rent DECIMAL( 4, 0 ) ,
workerno VARCHAR( 5 ) ,
PRIMARY KEY ( buildno ) ,
FOREIGN KEY ( workerno ) REFERENCES worker
);
10
BUILDING TABLE
11
DROP DATABASE/TABLE
DROP DATABASE
Syntax: DROP database database_name;
Example: DROP DATABASE company;
DROP TABLE
Syntax: DROP TABLE table_name;
Example: DROP TABLE worker;
**Will delete the entire table.
12
ALTER TABLE
ALTER TABLE statement is used to add or drop columns in
an existing table.
Syntax:
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
13
Example: Add column
Consider this table:
Person
LastName FirstName Address
Pettersen Kari Storgt 20
Add column “City” in the Person table:
ALTER TABLE Person
ADD City VARCHAR (10);
Result:
LastName FirstName Address City
Pettersen Kari Storgt 20
14
Example: Delete column
To delete “Address” column in the Person table:
ALTER TABLE Person DROP COLUMN Address ;
Result:
LastName FirstName City
Pettersen Kari
15
DML
Data Manipulation Language (DML) is a family of computer
languages used by computer programs and/or database users to
insert, delete and update data in a database.
Data Manipulation Language comprises the 'SQL-data change'
statements, which modify stored data but not the schema or database
objects.
16
Insert statement
INSERT INTO - used to insert new rows into a table.
Syntax:
INSERT INTO table_name (column1, column2,…)
VALUES (value1, value2,…);
Enter data to each column:
INSERT INTO worker
VALUES ('A07', 'ALI', 'ASSISTANT MANAGER', 'KLANG', '2000-05-
13', '7891', '4000');
17
Update statement
The UPDATE statement is used to modify the data in a table.
Syntax:
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
18
Example : Update
Person
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67
Update one Column in a Row
Add a first name to the person with a last name of "Rasmussen":
UPDATE Person
SET FirstName = 'Nina‘
WHERE LastName = 'Rasmussen‘;
19
Example : Update
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67
20
Example : Update
Update several columns in a row:
If we want to change the address and name of the city:
UPDATE Person
SET Address = 'Stien 12', City =‘Stavanger’
WHERE LastName = 'Rasmussen'
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
21
Example : Update
Update more than one row at a time :
If we want to change name of the city from Stavanger to Milan:
UPDATE Person
SET City = ‘Milan’;
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Milan
Rasmussen Nina Stien 12 Milan
22
Delete statement
DELETE – to delete rows in a table.
Syntax:
DELETE FROM table_name
WHERE column_name = some_value;
Consider this table:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
23
Example
To delete a row – deleting Nina Rassmussen record.
DELETE FROM Person
WHERE LastName = 'Rasmussen‘;
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
24
Example
To delete all rows:
Itis possible to delete all rows in a table without deleting
the table. This means that the table structure, attributes, and
indexes will be intact:
DELETE FROM table_name
Or
DELETE * FROM table_name
25
SQL QUERIES
26
SQL QUERIES
With SQL, we can query a database and have a result set
returned.
All queries are based on the SELECT command.
Syntax:
SELECT column_name(s)
FROM table_name;
* SELECT, FROM can be written in lower case.
27
Example
Consider this table:
28
Example: SELECT
Select all columns:
SELECT *
FROM worker;
Result: will display the entire table.
29
Example: SELECT
Select certain columns:
SELECT workerno, workername
FROM worker;
Result:
30
SELECT DISTINCT statement
The DISTINCT keyword is used to return only distinct (different) values.
Consider this table: worker
31
SELECT DISTINCT statement
If we use: SELECT address FROM worker;
address
CHERAS
result
BANGI
BANGI
AMPANG
BANGI
KAJANG
32
SELECT DISTINCT statement
If we use:
SELECT DISTINCT address FROM worker;
Result:
address
CHERAS
BANGI
AMPANG
KAJANG
33
Calculated field
Example:
SELECT workerno, workername, salary /2
FROM worker;
Result:
34
Rename column
To rename a column, use AS statement.
Example:
SELECT workerno AS Number, workername AS Name
FROM worker;
Result:
35
SQL WHERE clause
WHERE clause is to specify a selection criterion.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE conditions;
36
SQL WHERE clause
With WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you
want to return for at least one of
the columns
*in some versions of SQL, <>
operator may be written as !=
37
Simple Queries…
List all the workers you earn more than 4000.
SELECT workername, salary
FROM worker
WHERE salary >4000;
Result:
38
Simple Queries…
List all worker who live in Bangi or Kajang.
SELECT workername, address
FROM worker
WHERE address = 'Bangi'
OR address = 'Kajang‘;
Result: *OR is used to join two or
more conditions.
39
Simple Queries…
List worker who live in Bangi and her name is Ani
SELECT workername, address
FROM worker
WHERE workername = ‘Ani'
AND address = ‘Bangi‘;
Result: *OR is used to join two or
more conditions.
40
Simple Queries…
List all the worker who earn between 3000 to 9000.
SELECT workername, salary
FROM worker
WHERE salary BETWEEN 3000 AND 9000;
Result:
*BETWEEN…AND operator selects a
range of data between two values.
*can be numbers, texts or dates.
41
Simple Queries…
List the Director and Vice Director.
SELECT workername, position
FROM worker
WHERE position *IN can be used if you know
IN ('DIRECTOR', 'VICE DIRECTOR'); the exact value that you
Result: seek for at least one of the
columns.
42
Simple Queries…
List the worker who is not living in Bangi.
SELECT workername, address
FROM worker
WHERE address NOT
IN ('BANGI');
Or
SELECT workername, address
FROM worker
WHERE address <> 'BANGI‘;
43
Result:
44
LIKE condition
LIKE - used to specify a search for a pattern in a column.
A "%" sign can be used to define wildcards (missing letters in the pattern) both before
and after the pattern.
Using LIKE:
a) The following SQL statement will return persons with first names that start with an 'O':
SELECT *
FROM Persons
WHERE FirstName
LIKE 'O%' ;
45
LIKE condition
b)The following SQL statement will return persons with first names that end with an 'a':
SELECT * FROM Staff
WHERE FirstName
LIKE '%a' ;
c)The following SQL statement will return persons with first names that contain the pattern 'la':
SELECT *
FROM Staff
WHERE FirstName
LIKE '%la%' ;
46
Simple Queries…
Find worker who doesn’t have phone number.
Consider this table : worker
47
Simple Queries…
SELECT workername, tel_no
FROM worker
WHERE tel_no IS NULL;
Result:
SORTING DATA
The ORDER BY clause is used to sort the
rows.
Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC];
4
SORTING DATA
ORDERS table:
Company OrderNumber
Sega 3412 SELECT Company, OrderNumber
ABC Shop 5678 FROM Orders
W3Schools 6798 ORDER BY Company;
W3Schools 2312
Example: to display the company names in
alphabetical order:
4
SORTING DATA
Result:
Company OrderNumber
ABC Shop 5678 SELECT Company, OrderNumber
Sega 3412 FROM Orders
W3Schools 6798 ORDER BY Company, OrderNumber;
W3Schools 2312
Example: to display the company names in
alphabetical order AND the OrderNumber in
numerical order:
5
SORTING DATA
Result:
Company OrderNumber
ABC Shop 5678 SELECT Company, OrderNumber
Sega 3412 FROM Orders
W3Schools 2312 ORDER BY Company DESC;
W3Schools 6798
Example: To display the company names in
reverse alphabetical order:
5
SORTING DATA
Result:
Company OrderNumber
W3Schools 6798
SELECT Company, OrderNumber
W3Schools 2312 FROM Orders
Sega 3412 ORDER BY OrderNumber ASC;
ABC Shop 5678
Example: To display the order number in
ascending order:
5
SORTING DATA
Result:
Company OrderNumber
W3Schools 2312
Sega 3412
ABC Shop 5678
W3Schools 6798
5
AGGREGATE FUNCTIONS
Some basic SQL aggregate functions:
FUNCTION OUTPUT
COUNT Return the number of rows containing not null values
SUM The sum of all values for a selected attribute in a given
column
AVG Return average of values in a specified column
MAX Return largest of value in a specified column
MIN Return smallest of valuesin a specified column
5
AGGREGATE FUNCTIONS
AVG and SUM - Can be used for
numeric data only
COUNT, MAX and MIN - Can be used for numeric and non-numeric
data.
5
AGGREGATE FUNCTIONS
COUNT EXAMPLE:
Calculate the number of employees who lives in
Bangi.
SELECT COUNT( ADDRESS ) AS Live_in_Bangi
FROM worker
WHERE ADDRESS = 'BANGI';
5
Explain the difference…
Company OrderNumber
Sega 3412
ABC Shop 5678 SELECT COUNT(DISTINCT
company) AS Company
W3Schools 6798
W3Schools 2312 FROM customer_order;
SELECT COUNT(company)
AS Company
FROM customer_order;
5
AGGREGATE FUNCTIONS
SUM EXAMPLE:
SELECT worker no, SUM( rent ) AS RENT
FROM building
WHERE workerno = 'A02‘;
5
AGGREGATE FUNCTIONS
MAX, MIN AND AVERAGE EXAMPLE:
SELECT
min( salary ) AS MIN,
max( salary ) AS MAX,
avg( salary ) AS SALARY
FROM worker;
5
GROUP BY…
GROUP BY... was added to SQL because aggregate
functions (like SUM) return the aggregate of all column
values every time they are called, and without the GROUP
BY function it was impossible to find the sum for each
individual group of column values.
Syntax:
SELECT column, SUM(column)
FROM table
GROUP BY column ;
* SUM can be changed with another aggregate functions
6
Example
Sales table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
Finding the sales amount for each company:
SELECT Company, SUM(Amount) FROM Sales;
Is this correct? Why?
6
Example
SELECT Company, SUM(Amount)
FROM Sales
GROUP BY Company;
6
HAVING…
HAVING... was added to SQL because the WHERE
keyword could not be used against aggregate
functions (like SUM), and without HAVING... it
would be impossible to test for result conditions.
HAVING clause is used to filter data based on the
group functions. This is similar to WHERE
condition but is used with group functions.
Syntax:
SELECT column, SUM(column)
FROM table
GROUP BY column
HAVING SUM (column) condition value;
6
Example…
Sales:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
SELECT company, SUM( amount )
FROM sales
GROUP BY company
HAVING SUM( amount ) >10000;
6
Accessing multiple tables
to access multiple tables, we can use:
Join
6
Join tables