You are on page 1of 99

DFC20203

DATABASE DESIGN
CHAPTER 4
Structured Query Language (SQL)
CHAPTER 4
WHAT YOU WILL LEARN:
SQL commands to a database.
Functions of the basic DDL
commands.
DML statements and
commands.
Functions for SQL advanced
commands.
SQL aggregate functions.
Introduction

SQL – Structured Query Language

Originally developed in the SEQUEL and System-R


projects at IBM’s research laboratory between 1974-
1977.

The standard for RDBMS (DB2, Oracle, MS Access,


Sybase, MS SQL Sever etc).
Introduction

• Main characteristics:
SQL is an ANSI and ISO standard computer language
for creating and manipulating databases.
SQL allows the user to create, update, delete, and
retrieve data from a database.
SQL is very simple and easy to learn.
Non-procedural language.
Consists of standard English words.
Advantages And Disadvantages

• Portable: SQL is run in programs • Requires detailed


ADVANTAGES

DISADVANTAGES
in mainframes, PCs, laptops, knowledge of the
servers and even mobile phones.
Easy to learn and understand:
structure of the database.
SQL mainly consists of English • Can provide misleading
statements and it is very easy to results.
learn and understand a SQL • Difficult Interface: SQL
query. has a complex interface that
• Used with any DBMS system
with any vendor.
makes it difficult for some
• No coding needed: It is very users to access it.
easy to manage the database
systems without any need to
write the substantial amount of
code by using the standard SQL.
• Multiple data views: By use of
SQL, different views of structure
and content of a database can
be provided for different users.
SQL STATEMENTS TYPES

DDL DML DCL TCL


• Data definition • Data manipulation • Data control • Transaction control
language language language language
• It is used to create • It is used to retrieve, • It is used to create • TCL commands are
and modify the store, modify, delete, roles, permissions, used to manage
structure of database insert and update and referential transactions in
objects in database data in database integrity as well it is database.
used to control • These are used to
access to database manage the changes
by securing it. made by DML
statements.
• It also allows
statements to be
grouped together into
logical transactions.
Example of SQL statements

SQL

DDL DML DCL TCL

UPDATE,
CREATE,
INSERT…INTO, GRANT, COMMIT,
ALTER, USE,
DELETE, REVOKE ROLLBACK
DROP
SELECT
CREATE THE DATABASE

◎All tables are stored in a database.


◎To create a database:

CREATE DATABASE database-name

Example : CREATE DATABASE mydatabase;


USE DATABASE

◎ Used when you have more than one


database and need to switch between
them.

◎ Syntax: USE database name;

◎ Example: USE mydatabase;


CREATE TABLE

◎To create new table in a database:


CREATE TABLE table_name
(
column_name data type [UNIQUE|NOT NULL],
[PRIMARY KEY (column_name),]
[FOREIGN KEY (foreign_key_column)
REFERENCES parent_table_name,
);

*Notes: SQL statements are not case-sensitive.


SQL Data Types
Type Size Description
CHAR[Length] Length bytes A fixed-length field from 0 to 255
characters long.
VARCHAR(Length) String length + 1 bytes A fixed-length field from 0 to 255
characters long.
TINYTEXT String length + 1 bytes A string with a maximum length of 255
characters
TEXT String length + 2 bytes A string with a maximum length of
65,535 characters.
MEDIUMTEXT String length + 3 bytes A string with a maximum length of
16,777,215 characters.
LONGTEXT String length + 4 bytes A string with a maximum length of
4,294,967,295 characters.
TINYINT[Length] 1 byte Range of -128 to 127 or 0 to 255
unsigned.
SMALLINT[Length] 2 bytes Range of -32,768 to 32,767 or 0 to
65,535 unsigned.
MEDIUMINT[Length] 3 bytes Range of -8,388,608 to 8,388,607 or 0
to 16,777,215 unsigned
SQL Data Types (cont.)
INT[Length] 4 bytes Range of -2,147,483,648 to 2,147,483,647
or 0 to 4,294,967,295 unsigned
BIGINT[Length] 8 bytes Range of -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 or 0 to
18,446,744,073,709,551,615 unsigned
FLOAT 4 bytes A small number with a floating decimal
point.
DOUBLE[Length, Decimals] 8 bytes A large number with a floating decimal
point.
DECIMAL[Length, Decimals] Length +1 bytes or A DOUBLE stored as a string, allowing
Length + 2 bytes for a fixed decimal point.
DATE 3 bytes In the format YYYY-MM-DD
DATETIME 8 bytes In the format YYYY-MM-DD
HH:MM:SS.
TIMESTAMP 4 bytes In the format YYYYMMDDHHMMSS;
acceptable range ends in the year 2037.
TIME 3 bytes In the format of HH:MM:SS.
ENUM 1 or 2 bytes Short for enumeration, that is, each column
can have one of several possible values.

SET 1, 2, 3, 4, or 8 bytes Like ENUM except that each column can


have more than one of several possible
values.
CONSTRAINT

◎Enforce rules at the table level.


◎Prevent invalid data entry.
◎ Prevent the deletion of a table if there are
dependencies.
◎ Can be specified when a table is created
(with the CREATE TABLE statement) or after
the table is created (with the ALTER TABLE
statement).
PRIMARY
KEY Constraints are the rules enforced
on the data columns of a table.
Prevent invalid data entry.
FOREIGN
KEY This ensures the accuracy and
reliability of the data in the
database.
NOT NULL Constraints could be either on a
column level or a table level. The
CONSTRAINT column level constraints are
applied only to one column,
UNIQUE whereas the table level constraints
are applied to the whole table.
Can be specified when a table is
CHECK created (with the CREATE TABLE
statement) or after the table is
created (with the ALTER TABLE
DEFAULT statement).
CONSTRAINT

• Uniquely identifies each row of the table.


PRI
MA • Automatically apply NOT NULL & UNIQUE constraint.
RY
KEY
• A key used to link two tables together which sometimes also
FOR called as referencing key.
EIG • The relationship between 2 tables matches the Primary Key in
N one of the tables with a Foreign Key in the second table.
KEY

• Ensures that a column cannot have NULL value.


NOT • A NULL is not the same as no data, rather, it represents
NUL unknown data.
L

https://www.tutorialspoint.com/sql/sql-constraints.htm
CONSTRAINT
• Ensures that all values in a column are different.
UNI • The UNIQUE Constraint prevents two records from having identical values in
a column.
QU
E
• The CHECK constraint ensures that all the values in a column satisfies
certain conditions.
CH • The CHECK Constraint enables a condition to check the value being entered
into a record. If the condition evaluates to false, the record violates the
EC constraint and isn't entered the table.
K

• Provides a default value for a column when none is specified.


DE • The DEFAULT constraint provides a default value to a column when the
INSERT INTO statement does not provide a specific value.
FA
ULT
CONSTRAINT: PRIMARY KEY
SINGLE COLUMN PK COMPOSITE PK
COLUMN LEVEL : TABLE LEVEL:
CREATE TABLE department CREATE TABLE CUSTOMERS
( (
dept_id int(3) PRIMARY KEY, ID INT,
dept_name varchar(20) NAME VARCHAR (20),
); AGE INT,
ADDRESS CHAR (25) ,
TABLE LEVEL: SALARY DECIMAL (18, 2),
CREATE TABLE department PRIMARY KEY (ID, NAME)
( );
dept_id int(3),
dept_name varchar(20),
PRIMARY KEY (dept_id)
);
CONSTRAINT: PRIMARY KEY
CREATE PRIMARY KEY USING DELETE PRIMARY KEY:
ALTER TABLE:

ALTER TABLE DEPARTMENT ALTER TABLE DEPARTMENT


ADD PRIMARY KEY (dept_id); DROP PRIMARY KEY ;

ALTER TABLE CUSTOMER S


ADD PRIMARY KEY (ID, NAME);
CONSTRAINT: FOREIGN KEY

CREATE TABLE employee


(
emp_id VARCHAR (5) PRIMARY KEY,
emp_name VARCHAR (15),
entrydate TIMESTAMP DEFAULT
CURRENT_TIMESTAMP,
salary DECIMAL (7,0),
dept_id int(3),
FOREIGN KEY (dept_id) REFERENCES department (dept_id)
);
CONSTRAINT: FOREIGN KEY
CREATE FOREIGN KEY USING DELETE FOREIGN KEY:
ALTER TABLE:

ALTER TABLE EMPLOYEE ALTER TABLE EMPLOYEE


ADD FOREIGN KEY (dept_id) DROP FOREIGN KEY;
REFERENCES DEPARTMENT
(dept_id);
CONSTRAINT: NOT NULL
CREATE NOT NULL REMOVE NOT NULL
CONSTRAINT: CONSTRAINT :

CREATE TABLE department ALTER TABLE department


( MODIFY dept_name varchar(20)
dept_id int(3) PRIMARY KEY, NULL;
dept_name varchar(20) NOT
NULL
);

ALTER TABLE department


MODIFY dept_name varchar(20)
NOT NULL;
CONSTRAINT: UNIQUE
CREATE UNIQUE CONSTRAINT: ALTER TABLE CUSTOMERS
ADD CONSTRAINT
CREATE TABLE department myUniqueConstraint
( UNIQUE(AGE, SALARY);
(Supports naming the constraint in
dept_id int(3) PRIMARY KEY, multiple columns)
dept_name varchar(20) UNIQUE
); DELETE UNIQUE CONSTRAINT:

ALTER TABLE department ALTER TABLE CUSTOMERS


MODIFY dept_name varchar(20) DROP INDEX
UNIQUE; myUniqueConstraint;
CONSTRAINT: CHECK
CREATE CHECK CONSTRAINT:
ALTER TABLE CUSTOMERS ADD
CREATE TABLE CUSTOMERS CONSTRAINT myCheckConstraint
( CHECK(AGE >= 18);
ID INT, (Supports naming the constraint in
NAME VARCHAR (20), multiple columns)
AGE INT CHECK (AGE >= 18),
DELETE CHECK CONSTRAINT:
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), ALTER TABLE CUSTOMERS ADD
PRIMARY KEY (ID, NAME) CONSTRAINT myCheckConstraint
); CHECK(AGE >= 18);

ALTER TABLE CUSTOMERS MODIFY (does not work with MySQL as MySQL does
AGE INT NOT NULL not support CHECK constraint)
CHECK (AGE >= 18 );
CONSTRAINT: DEFAULT

CREATE DEFAULT CONSTRAINT:

CREATE TABLE employee


(
emp_id VARCHAR (5) PRIMARY KEY,
emp_name VARCHAR (15),
entrydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
salary DECIMAL (7,0),
dept_id int(3),
FOREIGN KEY (dept_id) REFERENCES department (dept_id)
);
CONSTRAINT: DEFAULT
CREATE DEFAULT CONSTRAINT:

CREATE TABLE CUSTOMERS


( DELETE DEFAULT CONSTRAINT:
ID INT,
NAME VARCHAR (20), ALTER TABLE CUSTOMERS
AGE INT, ALTER COLUMN SALARY DROP DEFAULT;
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 3000.00,

PRIMARY KEY (ID, NAME)


);

ALTER TABLE CUSTOMERS


MODIFY SALARY DECIMAL (18, 2) DEFAULT
5000.00;
RIDDLES
Which ring is square?
You can see me in water,
but I never get wet. What
am I?
A man was driving a black
car. His lights were off.
The moon shown no
light. A cat was in the
middle of the road. How
did he know to stop?
ACTIVITY: CREATE THESE
TABLES

CREATE TABLE department


(
dept_id int(3) PRIMARY KEY,
dept_name varchar(20) UNIQUE
);
ACTIVITY: CREATE THESE
TABLES

CREATE TABLE employee


(
emp_id VARCHAR (5) PRIMARY KEY,
emp_name VARCHAR (15) NOT NULL,
entrydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
salary DECIMAL (7,0) DEFAULT 3500.00,
dept_id int(3),
FOREIGN KEY (dept_id) REFERENCES department (dept_id)
);
CREATE TABLE
Note the following features in creating table:
 PK designations contain both a NOT NULL and a UNIQUE
specification (to enforce entity integrity).
 The list of attributes is enclosed in parentheses.
 A comma is used after each attribute and its
characteristics have been defined.
 The command sequence end with a semicolon.
Creating a table Using a Subquery

• Create a table by combining the CREATE


TABLE statement and the AS subquery
option.
• Syntax:
CREATE TABLE table_name
[(column, column…)]
AS subquery;
Example
CREATE TABLE employee2
AS
SELECT * FROM employee;

OR

CREATE TABLE employee2


AS
SELECT emp_id, emp_name
FROM employee;
DISPLAYING TABLE STRUCTURE

◎Use DESCRIBE or DESC command to display


the structure of a table.

Example: DESCRIBE employee;


DESC employee;
DELETE TABLE
◎DROP TABLE
○ Syntax: DROP TABLE table_name;

○ Example: DROP TABLE employee2;

Will delete the entire table.


MODIFYING TABLES
◎ The ALTER TABLE statement allows you to
rename an existing table. It can also be used to
add, modify, or drop a column from an existing
table.
◎ Syntax:
ALTER TABLE table_name (action
field_definition, action field_definition,..);
Renaming a table

• The basic syntax for renaming a table is:


ALTER TABLE table_name
RENAME TO new_table_name;
• For example:
ALTER TABLE employee2
RENAME TO staff;
• This will rename the employee2 table to
staff.
Add column

• To add a column to an existing table, the


ALTER TABLE syntax is:
ALTER TABLE table_name
ADD column_name column-definition;
• For example:
ALTER TABLE staff
ADD email varchar(50);
• This will add a column called email to the
staff table.
Add multiple columns
• To add multiple columns to an existing table, the
ALTER TABLE syntax is:
ALTER TABLE table_name
ADD ( column_1 column-definition,
column_2 column-definition, ...
column_n column_definition );
• For example:
ALTER TABLE staff
ADD ( email varchar(50),
city varchar(45) );
• This will add two columns (email and city) to the
staff table.
Modify a column
• To modify a column in an existing table, the
ALTER TABLE syntax is:
ALTER TABLE table_name
MODIFY column_name column_type;
• For example:
ALTER TABLE staff
MODIFY email varchar(100) not null;
• This will modify the column called email to be a
data type of varchar(100) and force the column
to not allow null values.
Delete column
◎ To drop a column in an existing table, the ALTER
TABLE syntax is:
ALTER TABLE table_name
DROP COLUMN column_name;
◎ For example:
ALTER TABLE staff
DROP COLUMN city;
◎ This will drop the column called city from the
table called staff.
Rename column

• To rename a column, the ALTER TABLE


syntax is:
ALTER TABLE table_name
CHANGE old_name new_name data_type;
• Example:
ALTER TABLE staff
CHANGE email email_address varchar(50);
ADDING RECORDS
 INSERT INTO - used to insert new rows into a table.
 Syntax:

INSERT INTO table_name (column1, column2,…)

VALUES (value1, value2,…);

• Enter all data into each column:

INSERT INTO employee

VALUES ('A07', ‘ANA', '2000-05-13‘, 4500,1);

• Enter data into selected columns (at least primary key column):

INSERT INTO employee (empno, empname)

VALUES ('A07', ‘ANA');


MODIFY RECORDS
◎ 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
Example
◎ Table: Person
LastName FirstName Address City

Nilsen Fred Matang 22 Kuching


Rahmat Gita 67

◎ Update one Column in a Row


○ Add a first name to the person with a last name of "Rahmat":
UPDATE Person
SET FirstName = 'Nina‘
WHERE LastName = ‘Rahmat‘;
Example
◎ Result:
LastName FirstName Address City
Nilsen Fred Matang 22 Kuching
Rahmat Nina Gita 67

◎ Update several columns in a row:


○ If we want to change the address and name of the city:
UPDATE Person
SET Address = ‘Gita 12', City =‘Kuching’
WHERE LastName = 'Rahmat'

○ Result:
LastName FirstName Address City
Nilsen Fred Matang 22 Kuching
Rahmat Nina Gita 12 Kuching
REMOVE RECORDS - DELETE
◎ DELETE – to delete records in a table.
◎ Syntax:
DELETE FROM table_name
WHERE column_name = some_value;
◎ Consider this table: Person
LastName FirstName Address City
Nilsen Fred Matang 22 Kuching
Rahmat Nina Gita 12 Kuching
Example

◎ To delete a row – deleting Nina Rahmat record.


DELETE FROM Person
WHERE LastName = 'Rahmat‘;
◎ Result:
LastName FirstName Address City
Nilsen Fred Matang 22 Kuching

◎ To delete all rows:


○ It is 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
Example:
DELETE FROM Person;
REMOVE RECORDS - TRUNCATE

• TRUNCATE command will removes all rows


from a table, leaving the table empty and the
table structure intact.
• DDL statement rather than DML (which is
DELETE).
• Syntax: TRUNCATE TABLE table_name;
• Example: TRUNCATE TABLE Person;
• Difference with DELETE command:
– With DELETE, you can use WHERE (specify conditions)
but you can’t use WHERE with TRUNCATE.
RIDDLES
What comes once in a minute,
twice in a moment, but never
in a thousand years?
What room do ghosts avoid?
I am a five letter word and I
am a fruit. Take the first letter
out and I am a crime, take out
the first and second letter and
I am a animal, take out the
first and last letter and I am a
type of music. What am I?

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.


SQL QUERIES

◎The following examples are based on


database SAKILA.
◎Type these SQL command to use database
SAKILA:
USE SAKILA;
Example: SELECT

◎ Select several columns: ◎ Select all columns:


SELECT first_name, last_name SELECT *
FROM customer;
FROM customer;
◎ Result:??
◎ Result: will display the entire
table.
DUPLICATE ROWS
◎The default display of queries is all rows,
including duplicate rows.
SELECT address FROM employee ; SELECT DISTINCT address FROM employee;

address
address
CHERAS
BANGI CHERAS
BANGI BANGI
AMPANG
AMPANG
BANGI
KAJANG KAJANG

1 2
DUPLICATE ROWS (cont.)

• Try these SQL codes and observe the


output:
(using MySQL Workbench, database sakila)

▫ SELECT RATING FROM FILM;

▫ SELECT DISTINCT RATING FROM FILM;


ARITHMETIC EXPRESSIONS

◎Create expressions with number and date


data by using arithmetic operators.

OPERATOR DESCRIPTION
+ ADD

- SUBTRACT

* MULTIPLY

/ DIVIDE
EXAMPLE(using MySQL Workbench, database
sakila)

1. SELECT film_id, rental_rate, rental_rate+10


FROM film;
2. SELECT film_id, rental_rate,
rental_rate+10*12
FROM film;
3. SELECT film_id, rental_rate,
(rental_rate+10)*12
FROM film;
USING COLUMN ALIAS
(using MySQL Workbench, database sakila)

1. SELECT film_id, rental_rate,


rental_rate+10 AS new_rate
FROM film;
2. SELECT film_id, rental_rate,
rental_rate+10 ‘new rate’
FROM film;
3. SELECT film_id, rental_rate,
rental_rate+10 AS ‘new rate’
FROM film;
LIMITING ROWS THAT ARE
SELECTED

• Restrict the rows that are returned by using the


WHERE clause:
SELECT column_name(s)
FROM table_name
WHERE condition(s);
• Condition is composed of column names,
expressions, constants and a comparison operator
• A condition specifies a combination of one or more
expressions and logical (Boolean) operators and
returns a value of TRUE, FALSE or UNKNOWN.
COMPARISON & LOGICAL OPERATOR
Operator Description
= Equal Syntax:
<> Not equal … WHERE expr operator value

> Greater than Example:


< Less than …WHERE salary <= 3000
…WHERE empname = ‘JOHN’
>= Greater than or equal
<= Less than or equal
BETWEEN
Between an inclusive range
…AND …
LIKE Search for a pattern
IN (SET) If you know the exact value you want
to return for at least one of the
columns
IS NULL Is a null value
EXISTS Check whether an attribute has a
value. Opposite of IS NULL
EXAMPLE(using MySQL Workbench, database
sakila)

• SELECT first_name,last_name
FROM customer
WHERE customer_id = 1;

• SELECT first_name,last_name
FROM customer
WHERE customer_id <= 10;
BETWEEN…AND… operator

To display rows based on a range values:


SELECT film_id, title, replacement_cost
FROM film
WHERE replacement_cost BETWEEN 9.00
AND 12.00;

*values can be numbers, texts or dates.


Using the IN operator
 Use the IN operator to test for values in a list.
 Can reduce the need to use multiple OR
conditions.
 IN function can be used with string and numeric
values.
 Example:
SELECT address_id
FROM address
WHERE district IN ('California',
'Nagasaki');
• It is equivalent to the following statement:
SELECT address_id
FROM address
WHERE district = ‘California’
OR district = ‘Nagasaki’;
NOT IN operator
• IN function can be combined with NOT operator.
SELECT title
FROM film
WHERE rating NOT IN (‘PG');
Pattern matching using the LIKE
operator
◎Use the LIKE operator to perform wildcard
searches of valid search string values.
◎Search conditions can contain either literal
characters or numbers:
% denotes zero or many character
_ denotes one character
Example
• SELECT title
FROM film
WHERE tile like ‘J%’;

• SELECT title
FROM film
WHERE title like ‘%B%’;

• SELECT title
FROM film
WHERE title like ‘%A’;
Combining Wildcard Characters

• Combine two wildcard characters (%,_) with


literal characters for pattern matching:
SELECT title
FROM film
WHERE title LIKE ‘_C%’;
USING LOGICAL OPERATOR

◎Logical operator:
AND : returns true if both component conditions are
true.
OR : returns true if either component condition is true
Example

SELECT title, rental_rate


FROM film
WHERE title LIKE ‘R%’
AND rental_rate = 2.99;

SELECT title, rental_rate


FROM film
WHERE title LIKE ‘R%’
OR rental_rate = 2.99;
SORTING DATA
◎ The ORDER BY clause is used to sort the rows.
◎ Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name;

*default order is ascending.


*to sort records in descending order, add DESC after
column’s name.
◎ ORDERS table:
Company OrderNumber
Sega 3412
ABC Shop 5678
W3Schools 6798
W3Schools 2312

◎ Example: to display the company names in


alphabetical order:

SELECT Company, OrderNumber


FROM Orders
ORDER BY Company;
◎ Result: Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 2312
W3Schools 6798

◎ Example: To display the company names in reverse


alphabetical order:

SELECT Company, OrderNumber


FROM Orders
ORDER BY Company DESC;
◎ Result: Company OrderNumber
W3Schools 6798
W3Schools 2312
Sega 3412
ABC Shop 5678

◎ Example: To display the order number by using


attribute position:
SELECT Company, OrderNumber
FROM Orders
ORDER BY 2;
◎ Result:
Company OrderNumber
W3Schools 2312
Sega 3412
ABC Shop 5678
W3Schools 6798
Exercise (using MySQL
Workbench, database sakila)

• Based on table film, create SQL code to:


Find films with PG, G or PG-13 rating.
Find films with rental rate less than 3.00.
Find films where its replacement cost is in the range
of 10.00 to 20.00.
Find films which has GOLD in its title and running
time (length) less than 100 minutes. Display only
column title and length for the output.
Display all the records in table film based on order
of its running time.
AGGREGATE FUNCTIONS
◎ 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 Average for the specified column
MAX Maximum value encountered in a given column
MIN Minimum value encountered in a given column
AGGREGATE FUNCTIONS

◎COUNT EXAMPLE:
SELECT COUNT( film_id )
FROM film
WHERE special_features LIKE
‘%Deleted Scenes%';
Explain the difference…

Company OrderNumber
Sega 3412
ABC Shop 5678
W3Schools 6798
W3Schools 2312

SELECT COUNT(company) SELECT COUNT(DISTINCT company) AS


Company
AS Company
FROM customer_order;
FROM customer_order;
AGGREGATE FUNCTIONS

◎SUM EXAMPLE:
SELECT SUM(amount)
FROM payment;
AGGREGATE FUNCTIONS

◎MAX, MIN AND AVERAGE EXAMPLE:


SELECT
min( amount ) AS MIN,
max( amount ) AS MAX,
avg( amount) AS AVERAGE
FROM payment;
ROUND FUNCTION
◎ ROUND function rounds the column,
expression or value to n decimal places.
◎ Example:
SELECT ROUND (45.933,2),
ROUND (45.899,0),
ROUND (45.899,-1)
FROM DUAL;
◎ DUAL is a public table that you can use to
view results from functions and calculations.
GROUP BY…
◎ You can divide rows in a table into smaller groups by
using the GROUP BY clause.
◎ Syntax:
SELECT column, aggregate_function(column)
FROM table
GROUP BY column ;
Example

SELECT RATING, COUNT(FILM_ID)


FROM FILM
GROUP BY RATING;
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.
◎ Syntax:

SELECT column, SUM(column)


FROM table
GROUP BY column
HAVING SUM (column) condition value;
Example…
◎ Sales:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100

SELECT company, SUM( amount )


FROM sales
GROUP BY company
HAVING SUM( amount ) >10000;
INTERSECT

◎ INTERSECT operator is used to combine two


SELECT statements, but returns rows only
from the first SELECT statement that are
identical to a row in the second SELECT
statement.
◎ This means INTERSECT returns only
common rows returned by the two SELECT
statements.
INTERSECT

◎Syntax:
SELECT column1 [, column2 ]
FROM table1, table2
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1, table2
[WHERE condition]
EXAMPLE

◎Consider these two tables:


EXAMPLE
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

INTERSECT

SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
RESULT

khilan

chaitali
Exercise (using MySQL
Workbench, database sakila)
• Based on table film_category, write SQL
codes to find the number of films for each
category.
• Based on table film_category, write SQL
codes to find the sum of payment for each
customer.
• Based on table film_category, write SQL
codes to find which category has more than
60 films.
RIDDLES
Two fathers and two sons went
fishing one day. They were there the
whole day and only caught 3 fish.
One father said, that is enough for
all of us, we will have one each. How
can this be possible?

They have not flesh, nor feathers,


nor scales, nor bone. Yet they have
fingers and thumbs of their own.
What are they?
Review Questions
◎Describe the following SQL statements:
○ SELECT
○ FROM
○ WHERE
○ GROUP BY
○ ORDER BY
○ HAVING
○ LIKE
○ BETWEEN… AND
◎Describe the following SQL functions:
○ Average
○ Count
○ Max
○ Min
○ Sum
◎Explain the difference between:
○ Where & Having
○ Select & Select Distinct
○ Count & Count Distinct
○ Delete & Truncate
◎Explain three SQL characteristics.
◎Explain:
○ DDL
○ DML
Give two SQL statements for each category.
◎Explain three strengths and weaknesses of SQL.
◎Explain the following constraints:
○ Not null
○ Unique
○ Primary key
○ Foreign key
◎Other type of question:
○ Form SQL query based on some tables \ table
structure.
○ Determine output from SQL queries.

You might also like