SlideShare a Scribd company logo
1 of 107
Download to read offline
CHAPTER 4
STRUCTURED
QUERY
LANGUAGE
(SQL)
DFC2033 DATABASE SYSTEM
Course Learning Outcome
›  CLO1 : Explain the fundamentals
concepts of database management and
relational data model to create a
database based on an organization’s
requirements.
›  CLO3 : Solve an organization’s
requirements by selecting the correct
database query formulation using an
appropriate commercial Database
Management System (DBMS).
At the end of this class you
should know.
›  Use SQL commands to database.
›  State the use of Structured Query Language (SQL).
›  Define the two main sublanguages in SQL
commands:
a. Data Definition Language (DDL)
b. Data manipulation Language (DML)
›  Describe the functions of the four basic DDL
commands:
a. CREATE
b. USE
c. ALTER
d. DROP
Introduction to SQL
§  Structured Query Language.
§  Standard Relational database language.
§  Originally SQL was called SEQUEL (Structured
English QUEry Language)
§  Was design an implemented at IBM research.
§  Now become standard for commercial
relational DBMS
§  Divided into two types of language:
§  Data Definition Language (DDL)
§  Data Manipulation Language (DML)
4
Use 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
¡  Perform both simple and
complex queries
5
What SQL can do?
§  SQL can execute queries against a database
§  SQL can retrieve data from a database
§  SQL can insert records in a database
§  SQL can update records in a database
§  SQL can delete records from a database
§  SQL can create new databases
§  SQL can create new tables in a database
§  SQL can create stored procedures in a database
§  SQL can create views in a database
§  SQL can set permissions on tables, procedures,
and views
6
DDL
›  Create database and tables
›  Modify the structure of the existing tables and
other objects in the database.
›  Some DDL commands
›  CREATE DATABASE - creates a new database
›  USE DATABASE – select database to work with
›  ALTER DATABASE - modifies a database
›  CREATE TABLE - creates a new table
›  ALTER TABLE - modifies a table
›  DROP TABLE - deletes a table
7
DML
›  A language for manipulation of data
inside the database.
›  The statement used to work with data
inside the tables.
›  Some DML commands:
›  SELECT - extracts data from a database
›  UPDATE - updates data in a database
›  DELETE - deletes data from a database
›  INSERT INTO - inserts new data into a
database
8
SQL DATA TYPE (TEXT)
9
Data type Description
CHAR(size) Holds a fixed length string (can contain letters,
numbers, and special characters). The fixed size is
specified in parenthesis. Can store up to 255 characters
VARCHAR(size) Holds a variable length string (can contain letters,
numbers, and special characters). The maximum size is
specified in parenthesis. Can store up to 255 characters.
Note: If you put a greater value than 255 it will be
converted to a TEXT type
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535
characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535
bytes of data
SQL DATA TYPE (TEXT)MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes
of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295
characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295
bytes of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535
values in an ENUM list. If a value is inserted that is not in the
list, a blank value will be inserted.
Note:	
  The	
  values	
  are	
  sorted	
  in	
  the	
  order	
  you	
  enter	
  them.	
  
You	
  enter	
  the	
  possible	
  values	
  in	
  this	
  format:	
  ENUM('X','Y','Z')	
  
SET Similar to ENUM except that SET may contain up to 64 list items
and can store more than one choice
10
SQL DATA TYPE (NUMBER)
11
Data type Description
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*.
The maximum number of digits may be specified in
parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295
UNSIGNED*. The maximum number of digits may be
specified in parenthesis
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal.
0 to 18446744073709551615 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
SQL DATA TYPE (NUMBER)
FLOAT(size,d) A small number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is
specified in the d parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is
specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point.
The maximum number of digits may be specified in the size
parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
12
SQL DATA TYPE (DATE)
13
Data type Description
DATE() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD
HH:MM:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number
of seconds since the Unix epoch ('1970-01-01 00:00:00'
UTC). Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to
'2038-01-09 03:14:07' UTC
TIME() A time. Format: HH:MM:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR() A year in two-digit or four-digit format.
Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in
two-digit format: 70 to 69, representing years from 1970 to 2069
CREATE
1.  Create database
CREATE DATABASE databasename;
CREATE DATABASE pbu;
2.  Select Database to work with
USE pbu;
14
CREATE
3.  Create table
CREATE TABLE tablename
( attribute1 datatype (n),
attribute2 datatype (n),
attributen datatype (n)
);
** A constraint can be applied on the attribute.
15
CREATE
CREATE TABLE student
( f_name VARCHAR(25) NOT NULL,
l_name VARCHAR(25),
AGE DATE
);
16
CREATE TABLE WITH PRIMARY
KEY
CREATE TABLE product
( prod_id CHAR(10) PRIMARY KEY NOT NULL,
prod_name VARCHAR(10) NOT NULL,
prod_quantity INT(10)
);
17
CREATE TABLE WITH
PRIMARY KEY AND
FOREIGN KEY
CREATE TABLE customer
( cust_id CHAR(10) PRIMARY KEY NOT NULL,
f_name VARCHAR(10) NOT NULL,
l_name INT(10),
product_id CHAR(10),
FOREIGN KEY (product_id) REFERENCES
product (prod_id);
);
18
ALTER
Add column to the table:
ALTER TABLE tablename
ADD attributename datatype(n);
ALTER TABLE student
ADD addresss VARCHAR(20) NOT NULL,
ADD phone_num VARCHAR(20),
ADD PRIMARY KEY (stud_id) ;
19
ALTER
ALTER TABLE product
DROP prod_name,
DROP primary key;
20
DROP
1.  Remove database
DROP DATABASE databasename;
DROP database pbu;
** all database including tables are deleted.
2.  Remove table
DROP TABLE tablename;
** all data and table structure will be deleted.
21
To be continued…
At the end of this class you
should know.
› Describe the functions of the
following DML commands:
a. INSERT
b. SELECT
c. UPDATE
d. DELETE
INSERT
›  Add one or more tuples to a relation
›  Attribute values should be listed in the
same order as in the CREATE TABLE
command.
INSERT tablename
VALUE (value1, value2, valuen);
25
INSERT
EXAMPLE:
INSERT INTO EMPLOYEE
VALUES ('Richard','K','Marini', '653298653',
'30-DEC 52‘ '98 Oak Forest,Katy,TX', 'M',
37000,'987654321', 4 )
26
INSERT
›  An alternate form of INSERT specifies
explicitly the attribute names that
correspond to the values in the new tuple.
›  Attributes with NULL values can be left out
›  Example: Insert a tuple for a new
EMPLOYEE for whom we only know the
FNAME, LNAME, and SSN attributes.
INSERT INTO EMPLOYEE (FNAME,LNAME, SSN)
VALUES ('Richard', 'Marini', '653298653');
27
UPDATE
›  Used to modify attribute values of one or more
selected tuples
›  A WHERE-clause selects the tuples to be modified
›  An additional SET-clause specifies the attributes to
be modified and their new values
›  Each command modifies tuples in the same
relation
UPDATE tablename
SET attributename=newvalue
WHERE codition;
28
UPDATE
›  Change the location and controlling
department number of project number 10 to
'Bellaire' and 5, respectively.
UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5
WHEREPNUMBER=10
** You have to specify the where condition. If
not all tuples will be change to Bellaire and 5 in
attribute PLOCATION and DNUM
29
EXAMPLE
UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE PNUMBER = 10;
30
DELETE
›  Removes tuples from a relation
›  Includes a WHERE-clause to select the tuples
to be deleted
›  Tuples are deleted from only one table at a
time
›  A missing WHERE-clause specifies that all
tuples in the relation are to be deleted; the
table then becomes an empty table
›  The number of tuples deleted depends on the
number of tuples in the relation that satisfy the
WHERE-clause
31
DELETE
DELETE FROM EMPLOYEE
WHERE LNAME='Brown’;
32
TRUNCATE
›  The SQL TRUNCATE command is used to
delete all the rows from the table and free
the space containing the table.
TRUNCATE TABLE table_name;
TRUNCATE TABLE employee;
33
DELETE VS TRUNCATE
›  TRUNCATE is a DDL whereas DELETE is a DML
›  You can use WHERE clause(conditions) with
DELETE but you can't use WHERE clause with
TRUNCATE .
›  You can't rollback data in TRUNCATE but in
DELETE you can rollback data. TRUNCATE
removes(delete) the record permanently.
›  TRUNCATE is faster than DELETE.
34
SELECT
›  Used to retrieve data in the table
›  Basic queries : SELECT-FROM-WHERE
structure.
SELECT attribute1, attribute2,...
attribute-n
FROM table_name;
SELECT stud_id, f_name
FROM student;
36
HOW TO SELECT ALL
ATTRIBUTES IN THE TABLE?
› Using asterisk ( * ) to select all
attributes in the table.
SELECT * FROM student ;
37
SELECT
›  Can be used with logical operator to
select data with certain condition.
38
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<>
!=
Not equal to
SELECT
39
• People
• First_Name • Last_Name • Gender • Age • Phone
• John • Smith • M • 27 • 2-4315
• Sally • Jones • F • 27 • 3-1542
• John • White • M • 32 • 2-4315
• Mary • Smith • F • 42 • 5-4321
• First_Name • Last_Name
John White
Mary Smith
Result:
Let’s retrieve first name and last name for people who age is
greater than 30.
SELECT
Retrieve the birthdate and address of the
employee whose name is 'John B. Smith'.
41
SELECT BDATE, ADDRESS FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B’ AND
LNAME='Smith’;
Retrieve the name and address of all employees who
work for the 'Research' department.
42
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO;
SELECT
› Similar to a SELECT-PROJECT-JOIN
sequence of relational algebra
operations
› (DNAME='Research') is a selection
condition (corresponds to a SELECT
operation in relational algebra)
›  (DNUMBER=DNO) is a join condition
(corresponds to a JOIN operation in
relational algebra)
43
44
SELECT
For every project located in 'Stafford', list the project
number, the controlling department number, and the
department manager's last name, address, and
birthdate.
45
Attribute to
select ?
PNUMBER
DNUM
LNAME
BDATE
ADDRESS
Table?
PROJECT
DEPARTMENT
EMPLOYEE
Join condition?
PLOCATION= ‘Stafford’
DNUM = DNUMBER (JOIN PROJECT AND
DEPARTMENT)
MGRSSN = SSN (JOIN DEPARTMENT AND
EMPLOYEE)
SELECT
SELECT PNUMBER, DNUM, LNAME, BDATE,
ADDRESS
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND
MGRSSN=SSN AND
PLOCATION='Stafford‘;
46
SELECT
› There are two join conditions
› The join condition
DNUM=DNUMBER relates a
project to its controlling
department
› The join condition MGRSSN=SSN
relates the controlling
department to the employee
who manages that
47
Group discussion
Create SQL command for each of the
followings:
›  Q1 : Select project name located at
Houston
›  Q2 : Select employee first name, last
name for those who works more than 20
hours.
›  Q3 : Select manager’s first name, last
name, address, department’s name and
dependent’s name for manager who has
male dependent.
48
Answer q1
49
Answer q2
50
Answer q1
51
To be continued…
At the end of this class you
should know.
Create new table with CREATE command.
›  Remove tables with DROP command.
›  Delete data with the DELETE and
TRUNCATE commands.
›  Add data with the INSERT command.
›  Use data manipulation statements of SQL
on a given database:
a. Retrieve data with the SELECT command
b. Retrieve data from multiple tables with SQL
JOINs (outer join, and inner joins)
c. Use SQL CASE statements
IN • People
• First_Name • Last_Name • Gender • Age • Phone
• John • Smith • M • 27 • 2-4315
• John • White • M • 32 • 2-4315
• Mary • Smith • F • 42 • 5-4321
• Mama Mia • Steventh • F • 38 • 5-4321
SELECT
First_Name,LastName,Age
FROM People
WHERE Age IN (27,32,42);
Result:
• John • Smith • M • 27 • 2-4315
• John • White • M • 32 • 2-4315
• Mary • Smith • F • 42 • 5-4321
SUBSTRING COMPARISON
›  The LIKE comparison operator is used to
compare partial strings
›  Two reserved characters are used: '%' (or
'*' in some implementations).
55
LIKE Employee
First_Name Last_Name Gender Age Phone
John Smith M 27 2-4315
John White M 32 2-4315
Mary Smith F 42 5-4321
Mama Mia Steventh F 38 5-4321
John Smith M 27 2-4315
Mary Smith F 42 5-4321
Sury Steventh F 38 5-4321
SELECT *
FROM Employee
WHERE Last_Name LIKE ‘%th';
This SQL statement will match
any first names that end with
‘th’
Result:
LIKE Employee
First_Name Last_Name Gender Age Phone
John Smith M 27 2-4315
John White M 32 2-4315
Mary Smith F 42 5-4321
Mama Mia Steventh F 38 5-4321
SELECT *
FROM Employee
WHERE First_Name LIKE ‘Ma%';
This SQL statement will match
any first names that START with
‘Ma’
Mary Smith F 42 5-4321
Mama Mia Steventh F 38 5-4321
Result:
ORDER BY
›  The ORDER BY clause is used to sort the
tuples in a query result based on the
values of some attribute(s).
›  The default order is in ascending order of
values
›  We can specify the keyword DESC if we
want a descending order; the keyword
ASC can be used to explicitly specify
ascending order, even though it is the
default
58
ORDER BYEmployee
First_Name Last_Name Gender Age Phone
John Smith M 27 2-4315
John White M 32 2-4315
Mary Smith F 42 5-4321
Mama Mia Steventh F 38 5-4321
SELECT
First_Name,Last_Name,Age
FROM Employee
WHERE Gender=“M”
ORDER BY Age;
By default : Sort in ascending
order
Result: John Smith 27
John White 32
ORDER BYEmployee
First_Name Last_Name Gender Age Phone
John Smith M 27 2-4315
John White M 32 2-4315
Mary Smith F 42 5-4321
Mama Mia Steventh F 38 5-4321
SELECT
First_Name,LastName,Age
FROM Employee
WHERE Gender=“M”
ORDER BY Age DESC;
Sort in descending order: add
DESC
Result: John White 32
John Smith 27
DISTINCT
›  SQL does not treat a relation as a set, so
redundant data or tuples can appear.
›  To eliminate redundant tuples in a query
result, the keyword DISTINCT is used
SELECT DISTINCT SALARY
FROM EMPLOYEE;
61
UNSPECIFIED WHERE
CLAUSE
›  A missing WHERE-clause indicates no
condition; hence, all tuples of the relation
in the FROM-clause are selected
›  This is equivalent to the condition WHERE
TRUE is in one relation.
›  If more than one relation is specified in the
FROM-clause and there is no join
condition, then the CARTESIAN PRODUCT
of tuples is selected
62
UNSPECIFIED WHERE
CLAUSE
SELECT SSN, DNAME
FROM EMPLOYEE, DEPARTMENT
63
OUTPUT
64
8 ROWS FROM
EMPLOYEE
X
3 ROWS FROM
DEPARTMENT
= 24 ROWS
UNSPECIFIED WHERE
CLAUSE
› The SQL before produced a large
relation which concatenate with
every tuples from both relations
› It is extremely important not to
overlook specifying any selection
and join conditions in the WHERE-
clause; otherwise, incorrect and
very large relations may result
65
Aliases
›  In SQL, we can use the same name for
two (or more) attributes as long as the
attributes are in different relations.
›  A query that refers to two or more
attributes with the same name must
qualify the attribute name with the
relation name by prefixing the relation
name to the attribute name
Example:
›  EMPLOYEE.LNAME, DEPARTMENT.DNAME
66
Aliases
›  Some queries need to refer to the same
relation twice.
›  In this case, aliases are given to the
relation name
›  Example:
For each employee, retrieve the
employee's
name, and the name of his or her
immediate supervisor.
67
SELECT E.FNAME, S.FNAME
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN;
68
Aliases
69
Aliases
›  The alternate relation names E and S are
called aliases or tuple variables for the
EMPLOYEE relation.
›  We can think of E and S as two different
copies of EMPLOYEE;
›  E represents employees in role of
supervisees
›  S represents employees in role of supervisors
70
SQL JOINS
›  Permit users to specify a table resulting
from a join operation in the from clause
of a query.
›  It is easier to do than mixing together all
the select and join conditions in where
clause.
›  The default join is inner join.
›  For example to join a table of the
EMPLOYEE and DEPARTMENT.
71
SQL JOINS›  Without join SQL command will be:
SELECT FNAME, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER;
›  With JOIN the SQL command will be :
SELECT FNAME, DNAME
FROM ( EMPLOYEE JOIN DEPARTMENT ON DNO =
DNUMBER );
72
73
SQL JOINS
The example before :
Retrieve the name and address of all employees
who work for the 'Research' department.
74
SELECT FNAME, SSN, SALARY
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNUMBER=DNO;
How it will be done using SQL join ?
SQL JOINSSELECT FNAME, SSN, SALARY
FROM ( EMPLOYEE JOIN
DEPARTMENT ON DNO =
DNUMBER )
WHERE DNAME = ‘Research’;
75
SQL JOINS
SELECT PNUMBER, PNAME, DNUM, FNAME, SSN,
SALARY
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND
MGRSSN=SSN AND
PLOCATION='Stafford‘;
How it will be done with SQL Join ?
76
SQL JOINS
SELECT PNUMBER, PNAME, DNUM, FNAME,
SSN, SALARY
FROM ( PROJECT JOIN DEPARTMENT ON
DNO = DNUMBER JOIN EMPLOYEE ON
MNGR_SSN=SSN )
WHERE PLOCATION='Stafford‘;
77
OUTPUT
78
SQL JOINS
›  In inner join, tuple is included in the result
only if a matching tuple exists in the other
relations.
›  For outer join, either the all the tables from
the right or left (based on what you
specify) will be included in the relations
together with its matching value.
›  When is to used outer join ?
79
SQL Joins
›  Retrieve only employee name and
supervisor name for those who has
supervisor.
›  Inner Join
SELECT E.FNAME AS Employee_Name,
S.LNAME AS Supervisor_Name
FROM (EMPLOYEE AS E JOIN EMPLOYEE AS S
ON E.SUPERSSN=S.SSN)
80
INNER JOIN
81
SQL LEFT OUTER Joins
›  Retrieve all the employee name and its
supervisor name.
›  That’s mean all employee tuple must be
included.
›  We have to use outer join
SELECT E.FNAME AS Employee_Name,
S.LNAME AS Supervisor_Name
FROM (EMPLOYEE AS E LEFT OUTER JOIN
EMPLOYEE AS S
ON E.SUPERSSN=S.SSN)
82
LEFT OUTER JOIN
83
Aggregate function
›  There are 5 aggregate function in SQL.
›  COUNT (Return the number of tuples in
rlation)
›  SUM (Return Summation of value )
›  MAX (Return Maximum value in a relation)
›  MIN (Return Minimum value in a relation)
›  AVG (Return Average )
84
COUNT
Product
PRO_ID NAME V_CODE
1 FAN 21
2 DESK 22
3 PENCIL 22
4 ERASER 21
Result:
SELECT COUNT(*) AS no_of_product;
no_of_product
4
SUM›  SELECT SUM(PRICE) AS Total
›  FROM product;
Result:
Total
850
Product
PRO_ID NAME PRICE
1 FAN 200
2 DESK 220
3 PENCIL 220
4 ERASER 210
AVG›  SELECT AVG(PRICE) AS total
›  FROM product;
Result:
total
212.5
Product
PRO_ID NAME PRICE
1 FAN 200
2 DESK 220
3 PENCIL 220
4 ERASER 210
MAX›  SELECT MAX(PRICE) AS max_price
›  FROM product;
Result:
max_price
220
Product
PRO_ID NAME PRICE
1 FAN 200
2 DESK 220
3 PENCIL 220
4 ERASER 210
Aggregate function
›  Find the maximum salary, the minimum
salary, and the average salary among all
employees.
›  SELECT MAX(SALARY), MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE;
89
GROUP DISCUSSION
QUESTION1
Find the maximum salary, the minimum salary,
and the average salary among employees who
work for the 'Research' department.
QUESTION2
Retrieve the number of employees in the
‘Administration Department' department
90
ANSWER Q1
91
ANSWER Q2
92
GROUPING
›  In many cases, we want to apply the
aggregate functions to subgroups of
tuples in a relation
›  Each subgroup of tuples consists of the set
of tuples that have the same value for
the grouping attribute(s)
›  The function is applied to each subgroup
independently
›  SQL has a GROUP BY-clause for specifying
the grouping attributes, which must also
appear in the SELECT-clause
93
GROUPING
For each department, retrieve the
department number, the number of
employees in the department, and their
average salary.
SELECT DNO, COUNT (*), AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNO;
94
OUTPUT
95
GROUPING
›  The EMPLOYEE tuples are divided into
groups--each group having the same
value for the grouping attribute DNO
›  The COUNT and AVG functions are
applied to each such group of tuples
separately
›  The SELECT-clause includes only the
grouping attribute and the functions to be
applied on each group of tuples
›  A join condition can be used in conjunction with
grouping
96
GROUPING
›  For each project, retrieve the project
number, project name, and the number
of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER;
›  In this case, the grouping and functions are
applied after the joining of the two relations
97
OUTPUT
98
THE HAVING-CLAUSE
›  Sometimes we want to retrieve the values
of these functions for only those groups
that satisfy certain conditions.
›  The HAVING-clause is used for specifying a
selection condition on groups (rather than
on individual tuples)
99
THE HAVING-CLAUSE
›  For each project on which more than two
employees work , retrieve the project
number, project name, and the number
of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER
HAVING COUNT (*) > 2;
100
OUTPUT
101
Summary of SQL Queries
›  A query in SQL can consist of up to six
clauses, but only the first two, SELECT and
FROM, are mandatory. The clauses are
specified in the following order:
SELECT <attribute list>
FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]
102
Summary of SQL Queries
›  The SELECT-clause lists the attributes or
functions to be retrieved
›  The FROM-clause specifies all relations (or
aliases) needed in the query but not those
needed in nested queries
›  The WHERE-clause specifies the conditions
for selection and join of tuples from the
relations specified in the FROM-clause
103
Summary of SQL Queries
›  GROUP BY specifies grouping attributes
›  HAVING specifies a condition for selection
of groups
›  ORDER BY specifies an order for displaying
the result of a query
›  A query is evaluated by first applying the
WHERE-clause, then GROUP BY and
HAVING, and finally the SELECT-clause
104
SQL CASE
›  SQL CASE is a very unique conditional
statement providing if/then/else logic for
any ordinary SQL command, such as
SELECT or UPDATE.
›  It then provides when-then-else
functionality (WHEN this condition is met
THEN do_this).
›  This functionality provides the developer
the ability to manipulate the presentation
of the data without actually updating or
changing the data as it exists inside the
SQL table.
105
SQL CASE
›  SYNTAX
CASE WHEN
‘VALUE’ THEN ‘STATEMENT’
ELSE ‘STATEMENT’
END AS ‘NEW ATTRIBUTENAME’
FROM TABLENAME;
106
EXAMPLE
107

More Related Content

What's hot

Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Beat Signer
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Dhani Ahmad
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 

What's hot (20)

SQL Commands
SQL Commands SQL Commands
SQL Commands
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql commands
Sql commandsSql commands
Sql commands
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Mysql
MysqlMysql
Mysql
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
SQL
SQLSQL
SQL
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 

Viewers also liked

Oxford Scholarship Online Access
Oxford Scholarship Online AccessOxford Scholarship Online Access
Oxford Scholarship Online AccessAnwarul Islam, PhD
 
Software Engineering - 01. Introduction
Software Engineering - 01. IntroductionSoftware Engineering - 01. Introduction
Software Engineering - 01. IntroductionArry Arman
 
Software Engineering - Introduction and Motivation (Marcello Thiry)
Software Engineering - Introduction and Motivation (Marcello Thiry)Software Engineering - Introduction and Motivation (Marcello Thiry)
Software Engineering - Introduction and Motivation (Marcello Thiry)Marcello Thiry
 
Chapter 2 Relational Data Model-part 3
Chapter 2 Relational Data Model-part 3Chapter 2 Relational Data Model-part 3
Chapter 2 Relational Data Model-part 3Eddyzulham Mahluzydde
 
Congratsyourthedbatoo
CongratsyourthedbatooCongratsyourthedbatoo
CongratsyourthedbatooDave Stokes
 
Chapter 2 Relational Data Model-part1
Chapter 2 Relational Data Model-part1Chapter 2 Relational Data Model-part1
Chapter 2 Relational Data Model-part1Eddyzulham Mahluzydde
 
Introduction To Navicat MySql GUI
Introduction To Navicat MySql GUIIntroduction To Navicat MySql GUI
Introduction To Navicat MySql GUIchadrobertson75
 
Chapter 2 Relational Data Model-part 2
Chapter 2 Relational Data Model-part 2Chapter 2 Relational Data Model-part 2
Chapter 2 Relational Data Model-part 2Eddyzulham Mahluzydde
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinhwebhostingguy
 
The care and feeding of a MySQL database
The care and feeding of a MySQL databaseThe care and feeding of a MySQL database
The care and feeding of a MySQL databaseDave Stokes
 
DATABASE PROJECT
DATABASE PROJECTDATABASE PROJECT
DATABASE PROJECTabdul basit
 
introduction to database
 introduction to database introduction to database
introduction to databaseAkif shexi
 
Introducing the MySQL Workbench CASE tool
Introducing the MySQL Workbench CASE toolIntroducing the MySQL Workbench CASE tool
Introducing the MySQL Workbench CASE toolAndrás Bögöly
 
MN691 Assignment 3 - Final Report 2
MN691 Assignment 3 - Final Report 2MN691 Assignment 3 - Final Report 2
MN691 Assignment 3 - Final Report 2Abi Reddy
 
Recipe Database Project Management
Recipe Database Project ManagementRecipe Database Project Management
Recipe Database Project Managementformalforker
 

Viewers also liked (20)

Jeremy123
Jeremy123Jeremy123
Jeremy123
 
Oxford Scholarship Online Access
Oxford Scholarship Online AccessOxford Scholarship Online Access
Oxford Scholarship Online Access
 
Software Engineering - 01. Introduction
Software Engineering - 01. IntroductionSoftware Engineering - 01. Introduction
Software Engineering - 01. Introduction
 
Software Engineering - Introduction and Motivation (Marcello Thiry)
Software Engineering - Introduction and Motivation (Marcello Thiry)Software Engineering - Introduction and Motivation (Marcello Thiry)
Software Engineering - Introduction and Motivation (Marcello Thiry)
 
Chapter 2 Relational Data Model-part 3
Chapter 2 Relational Data Model-part 3Chapter 2 Relational Data Model-part 3
Chapter 2 Relational Data Model-part 3
 
Congratsyourthedbatoo
CongratsyourthedbatooCongratsyourthedbatoo
Congratsyourthedbatoo
 
EC Database System
EC Database SystemEC Database System
EC Database System
 
Chapter 2 Relational Data Model-part1
Chapter 2 Relational Data Model-part1Chapter 2 Relational Data Model-part1
Chapter 2 Relational Data Model-part1
 
Introduction To Navicat MySql GUI
Introduction To Navicat MySql GUIIntroduction To Navicat MySql GUI
Introduction To Navicat MySql GUI
 
Mysql grand
Mysql grandMysql grand
Mysql grand
 
Chapter 2 Relational Data Model-part 2
Chapter 2 Relational Data Model-part 2Chapter 2 Relational Data Model-part 2
Chapter 2 Relational Data Model-part 2
 
Chapter 3 Entity Relationship Model
Chapter 3 Entity Relationship ModelChapter 3 Entity Relationship Model
Chapter 3 Entity Relationship Model
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
 
The care and feeding of a MySQL database
The care and feeding of a MySQL databaseThe care and feeding of a MySQL database
The care and feeding of a MySQL database
 
DATABASE PROJECT
DATABASE PROJECTDATABASE PROJECT
DATABASE PROJECT
 
introduction to database
 introduction to database introduction to database
introduction to database
 
Introducing the MySQL Workbench CASE tool
Introducing the MySQL Workbench CASE toolIntroducing the MySQL Workbench CASE tool
Introducing the MySQL Workbench CASE tool
 
MN691 Assignment 3 - Final Report 2
MN691 Assignment 3 - Final Report 2MN691 Assignment 3 - Final Report 2
MN691 Assignment 3 - Final Report 2
 
Mysql workbench 5
Mysql workbench 5Mysql workbench 5
Mysql workbench 5
 
Recipe Database Project Management
Recipe Database Project ManagementRecipe Database Project Management
Recipe Database Project Management
 

Similar to Chapter 4 Structured Query Language

Similar to Chapter 4 Structured Query Language (20)

unit 1 ppt.pptx
unit 1 ppt.pptxunit 1 ppt.pptx
unit 1 ppt.pptx
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
DBMS Part-3.pptx
DBMS Part-3.pptxDBMS Part-3.pptx
DBMS Part-3.pptx
 
Lab
LabLab
Lab
 
Les09
Les09Les09
Les09
 
Les09
Les09Les09
Les09
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Module 3
Module 3Module 3
Module 3
 
Sql
SqlSql
Sql
 
SQL
SQLSQL
SQL
 
DBMS.pdf
DBMS.pdfDBMS.pdf
DBMS.pdf
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
 
Less08 Schema
Less08 SchemaLess08 Schema
Less08 Schema
 
MS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsMS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutions
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 

Recently uploaded

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

Chapter 4 Structured Query Language

  • 2. Course Learning Outcome ›  CLO1 : Explain the fundamentals concepts of database management and relational data model to create a database based on an organization’s requirements. ›  CLO3 : Solve an organization’s requirements by selecting the correct database query formulation using an appropriate commercial Database Management System (DBMS).
  • 3. At the end of this class you should know. ›  Use SQL commands to database. ›  State the use of Structured Query Language (SQL). ›  Define the two main sublanguages in SQL commands: a. Data Definition Language (DDL) b. Data manipulation Language (DML) ›  Describe the functions of the four basic DDL commands: a. CREATE b. USE c. ALTER d. DROP
  • 4. Introduction to SQL §  Structured Query Language. §  Standard Relational database language. §  Originally SQL was called SEQUEL (Structured English QUEry Language) §  Was design an implemented at IBM research. §  Now become standard for commercial relational DBMS §  Divided into two types of language: §  Data Definition Language (DDL) §  Data Manipulation Language (DML) 4
  • 5. Use 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 ¡  Perform both simple and complex queries 5
  • 6. What SQL can do? §  SQL can execute queries against a database §  SQL can retrieve data from a database §  SQL can insert records in a database §  SQL can update records in a database §  SQL can delete records from a database §  SQL can create new databases §  SQL can create new tables in a database §  SQL can create stored procedures in a database §  SQL can create views in a database §  SQL can set permissions on tables, procedures, and views 6
  • 7. DDL ›  Create database and tables ›  Modify the structure of the existing tables and other objects in the database. ›  Some DDL commands ›  CREATE DATABASE - creates a new database ›  USE DATABASE – select database to work with ›  ALTER DATABASE - modifies a database ›  CREATE TABLE - creates a new table ›  ALTER TABLE - modifies a table ›  DROP TABLE - deletes a table 7
  • 8. DML ›  A language for manipulation of data inside the database. ›  The statement used to work with data inside the tables. ›  Some DML commands: ›  SELECT - extracts data from a database ›  UPDATE - updates data in a database ›  DELETE - deletes data from a database ›  INSERT INTO - inserts new data into a database 8
  • 9. SQL DATA TYPE (TEXT) 9 Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type TINYTEXT Holds a string with a maximum length of 255 characters TEXT Holds a string with a maximum length of 65,535 characters BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
  • 10. SQL DATA TYPE (TEXT)MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note:  The  values  are  sorted  in  the  order  you  enter  them.   You  enter  the  possible  values  in  this  format:  ENUM('X','Y','Z')   SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice 10
  • 11. SQL DATA TYPE (NUMBER) 11 Data type Description TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis
  • 12. SQL DATA TYPE (NUMBER) FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter 12
  • 13. SQL DATA TYPE (DATE) 13 Data type Description DATE() A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC TIME() A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' YEAR() A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069
  • 14. CREATE 1.  Create database CREATE DATABASE databasename; CREATE DATABASE pbu; 2.  Select Database to work with USE pbu; 14
  • 15. CREATE 3.  Create table CREATE TABLE tablename ( attribute1 datatype (n), attribute2 datatype (n), attributen datatype (n) ); ** A constraint can be applied on the attribute. 15
  • 16. CREATE CREATE TABLE student ( f_name VARCHAR(25) NOT NULL, l_name VARCHAR(25), AGE DATE ); 16
  • 17. CREATE TABLE WITH PRIMARY KEY CREATE TABLE product ( prod_id CHAR(10) PRIMARY KEY NOT NULL, prod_name VARCHAR(10) NOT NULL, prod_quantity INT(10) ); 17
  • 18. CREATE TABLE WITH PRIMARY KEY AND FOREIGN KEY CREATE TABLE customer ( cust_id CHAR(10) PRIMARY KEY NOT NULL, f_name VARCHAR(10) NOT NULL, l_name INT(10), product_id CHAR(10), FOREIGN KEY (product_id) REFERENCES product (prod_id); ); 18
  • 19. ALTER Add column to the table: ALTER TABLE tablename ADD attributename datatype(n); ALTER TABLE student ADD addresss VARCHAR(20) NOT NULL, ADD phone_num VARCHAR(20), ADD PRIMARY KEY (stud_id) ; 19
  • 20. ALTER ALTER TABLE product DROP prod_name, DROP primary key; 20
  • 21. DROP 1.  Remove database DROP DATABASE databasename; DROP database pbu; ** all database including tables are deleted. 2.  Remove table DROP TABLE tablename; ** all data and table structure will be deleted. 21
  • 23.
  • 24. At the end of this class you should know. › Describe the functions of the following DML commands: a. INSERT b. SELECT c. UPDATE d. DELETE
  • 25. INSERT ›  Add one or more tuples to a relation ›  Attribute values should be listed in the same order as in the CREATE TABLE command. INSERT tablename VALUE (value1, value2, valuen); 25
  • 26. INSERT EXAMPLE: INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC 52‘ '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 ) 26
  • 27. INSERT ›  An alternate form of INSERT specifies explicitly the attribute names that correspond to the values in the new tuple. ›  Attributes with NULL values can be left out ›  Example: Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME, and SSN attributes. INSERT INTO EMPLOYEE (FNAME,LNAME, SSN) VALUES ('Richard', 'Marini', '653298653'); 27
  • 28. UPDATE ›  Used to modify attribute values of one or more selected tuples ›  A WHERE-clause selects the tuples to be modified ›  An additional SET-clause specifies the attributes to be modified and their new values ›  Each command modifies tuples in the same relation UPDATE tablename SET attributename=newvalue WHERE codition; 28
  • 29. UPDATE ›  Change the location and controlling department number of project number 10 to 'Bellaire' and 5, respectively. UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHEREPNUMBER=10 ** You have to specify the where condition. If not all tuples will be change to Bellaire and 5 in attribute PLOCATION and DNUM 29
  • 30. EXAMPLE UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE PNUMBER = 10; 30
  • 31. DELETE ›  Removes tuples from a relation ›  Includes a WHERE-clause to select the tuples to be deleted ›  Tuples are deleted from only one table at a time ›  A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the table then becomes an empty table ›  The number of tuples deleted depends on the number of tuples in the relation that satisfy the WHERE-clause 31
  • 32. DELETE DELETE FROM EMPLOYEE WHERE LNAME='Brown’; 32
  • 33. TRUNCATE ›  The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table. TRUNCATE TABLE table_name; TRUNCATE TABLE employee; 33
  • 34. DELETE VS TRUNCATE ›  TRUNCATE is a DDL whereas DELETE is a DML ›  You can use WHERE clause(conditions) with DELETE but you can't use WHERE clause with TRUNCATE . ›  You can't rollback data in TRUNCATE but in DELETE you can rollback data. TRUNCATE removes(delete) the record permanently. ›  TRUNCATE is faster than DELETE. 34
  • 35.
  • 36. SELECT ›  Used to retrieve data in the table ›  Basic queries : SELECT-FROM-WHERE structure. SELECT attribute1, attribute2,... attribute-n FROM table_name; SELECT stud_id, f_name FROM student; 36
  • 37. HOW TO SELECT ALL ATTRIBUTES IN THE TABLE? › Using asterisk ( * ) to select all attributes in the table. SELECT * FROM student ; 37
  • 38. SELECT ›  Can be used with logical operator to select data with certain condition. 38 = Equal > Greater than < Less than >= Greater than or equal <= Less than or equal <> != Not equal to
  • 39. SELECT 39 • People • First_Name • Last_Name • Gender • Age • Phone • John • Smith • M • 27 • 2-4315 • Sally • Jones • F • 27 • 3-1542 • John • White • M • 32 • 2-4315 • Mary • Smith • F • 42 • 5-4321 • First_Name • Last_Name John White Mary Smith Result: Let’s retrieve first name and last name for people who age is greater than 30.
  • 40.
  • 41. SELECT Retrieve the birthdate and address of the employee whose name is 'John B. Smith'. 41 SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’;
  • 42. Retrieve the name and address of all employees who work for the 'Research' department. 42 SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO;
  • 43. SELECT › Similar to a SELECT-PROJECT-JOIN sequence of relational algebra operations › (DNAME='Research') is a selection condition (corresponds to a SELECT operation in relational algebra) ›  (DNUMBER=DNO) is a join condition (corresponds to a JOIN operation in relational algebra) 43
  • 44. 44
  • 45. SELECT For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, address, and birthdate. 45 Attribute to select ? PNUMBER DNUM LNAME BDATE ADDRESS Table? PROJECT DEPARTMENT EMPLOYEE Join condition? PLOCATION= ‘Stafford’ DNUM = DNUMBER (JOIN PROJECT AND DEPARTMENT) MGRSSN = SSN (JOIN DEPARTMENT AND EMPLOYEE)
  • 46. SELECT SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford‘; 46
  • 47. SELECT › There are two join conditions › The join condition DNUM=DNUMBER relates a project to its controlling department › The join condition MGRSSN=SSN relates the controlling department to the employee who manages that 47
  • 48. Group discussion Create SQL command for each of the followings: ›  Q1 : Select project name located at Houston ›  Q2 : Select employee first name, last name for those who works more than 20 hours. ›  Q3 : Select manager’s first name, last name, address, department’s name and dependent’s name for manager who has male dependent. 48
  • 53. At the end of this class you should know. Create new table with CREATE command. ›  Remove tables with DROP command. ›  Delete data with the DELETE and TRUNCATE commands. ›  Add data with the INSERT command. ›  Use data manipulation statements of SQL on a given database: a. Retrieve data with the SELECT command b. Retrieve data from multiple tables with SQL JOINs (outer join, and inner joins) c. Use SQL CASE statements
  • 54. IN • People • First_Name • Last_Name • Gender • Age • Phone • John • Smith • M • 27 • 2-4315 • John • White • M • 32 • 2-4315 • Mary • Smith • F • 42 • 5-4321 • Mama Mia • Steventh • F • 38 • 5-4321 SELECT First_Name,LastName,Age FROM People WHERE Age IN (27,32,42); Result: • John • Smith • M • 27 • 2-4315 • John • White • M • 32 • 2-4315 • Mary • Smith • F • 42 • 5-4321
  • 55. SUBSTRING COMPARISON ›  The LIKE comparison operator is used to compare partial strings ›  Two reserved characters are used: '%' (or '*' in some implementations). 55
  • 56. LIKE Employee First_Name Last_Name Gender Age Phone John Smith M 27 2-4315 John White M 32 2-4315 Mary Smith F 42 5-4321 Mama Mia Steventh F 38 5-4321 John Smith M 27 2-4315 Mary Smith F 42 5-4321 Sury Steventh F 38 5-4321 SELECT * FROM Employee WHERE Last_Name LIKE ‘%th'; This SQL statement will match any first names that end with ‘th’ Result:
  • 57. LIKE Employee First_Name Last_Name Gender Age Phone John Smith M 27 2-4315 John White M 32 2-4315 Mary Smith F 42 5-4321 Mama Mia Steventh F 38 5-4321 SELECT * FROM Employee WHERE First_Name LIKE ‘Ma%'; This SQL statement will match any first names that START with ‘Ma’ Mary Smith F 42 5-4321 Mama Mia Steventh F 38 5-4321 Result:
  • 58. ORDER BY ›  The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s). ›  The default order is in ascending order of values ›  We can specify the keyword DESC if we want a descending order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default 58
  • 59. ORDER BYEmployee First_Name Last_Name Gender Age Phone John Smith M 27 2-4315 John White M 32 2-4315 Mary Smith F 42 5-4321 Mama Mia Steventh F 38 5-4321 SELECT First_Name,Last_Name,Age FROM Employee WHERE Gender=“M” ORDER BY Age; By default : Sort in ascending order Result: John Smith 27 John White 32
  • 60. ORDER BYEmployee First_Name Last_Name Gender Age Phone John Smith M 27 2-4315 John White M 32 2-4315 Mary Smith F 42 5-4321 Mama Mia Steventh F 38 5-4321 SELECT First_Name,LastName,Age FROM Employee WHERE Gender=“M” ORDER BY Age DESC; Sort in descending order: add DESC Result: John White 32 John Smith 27
  • 61. DISTINCT ›  SQL does not treat a relation as a set, so redundant data or tuples can appear. ›  To eliminate redundant tuples in a query result, the keyword DISTINCT is used SELECT DISTINCT SALARY FROM EMPLOYEE; 61
  • 62. UNSPECIFIED WHERE CLAUSE ›  A missing WHERE-clause indicates no condition; hence, all tuples of the relation in the FROM-clause are selected ›  This is equivalent to the condition WHERE TRUE is in one relation. ›  If more than one relation is specified in the FROM-clause and there is no join condition, then the CARTESIAN PRODUCT of tuples is selected 62
  • 63. UNSPECIFIED WHERE CLAUSE SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT 63
  • 64. OUTPUT 64 8 ROWS FROM EMPLOYEE X 3 ROWS FROM DEPARTMENT = 24 ROWS
  • 65. UNSPECIFIED WHERE CLAUSE › The SQL before produced a large relation which concatenate with every tuples from both relations › It is extremely important not to overlook specifying any selection and join conditions in the WHERE- clause; otherwise, incorrect and very large relations may result 65
  • 66. Aliases ›  In SQL, we can use the same name for two (or more) attributes as long as the attributes are in different relations. ›  A query that refers to two or more attributes with the same name must qualify the attribute name with the relation name by prefixing the relation name to the attribute name Example: ›  EMPLOYEE.LNAME, DEPARTMENT.DNAME 66
  • 67. Aliases ›  Some queries need to refer to the same relation twice. ›  In this case, aliases are given to the relation name ›  Example: For each employee, retrieve the employee's name, and the name of his or her immediate supervisor. 67
  • 68. SELECT E.FNAME, S.FNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN; 68
  • 70. Aliases ›  The alternate relation names E and S are called aliases or tuple variables for the EMPLOYEE relation. ›  We can think of E and S as two different copies of EMPLOYEE; ›  E represents employees in role of supervisees ›  S represents employees in role of supervisors 70
  • 71. SQL JOINS ›  Permit users to specify a table resulting from a join operation in the from clause of a query. ›  It is easier to do than mixing together all the select and join conditions in where clause. ›  The default join is inner join. ›  For example to join a table of the EMPLOYEE and DEPARTMENT. 71
  • 72. SQL JOINS›  Without join SQL command will be: SELECT FNAME, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER; ›  With JOIN the SQL command will be : SELECT FNAME, DNAME FROM ( EMPLOYEE JOIN DEPARTMENT ON DNO = DNUMBER ); 72
  • 73. 73
  • 74. SQL JOINS The example before : Retrieve the name and address of all employees who work for the 'Research' department. 74 SELECT FNAME, SSN, SALARY FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO; How it will be done using SQL join ?
  • 75. SQL JOINSSELECT FNAME, SSN, SALARY FROM ( EMPLOYEE JOIN DEPARTMENT ON DNO = DNUMBER ) WHERE DNAME = ‘Research’; 75
  • 76. SQL JOINS SELECT PNUMBER, PNAME, DNUM, FNAME, SSN, SALARY FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford‘; How it will be done with SQL Join ? 76
  • 77. SQL JOINS SELECT PNUMBER, PNAME, DNUM, FNAME, SSN, SALARY FROM ( PROJECT JOIN DEPARTMENT ON DNO = DNUMBER JOIN EMPLOYEE ON MNGR_SSN=SSN ) WHERE PLOCATION='Stafford‘; 77
  • 79. SQL JOINS ›  In inner join, tuple is included in the result only if a matching tuple exists in the other relations. ›  For outer join, either the all the tables from the right or left (based on what you specify) will be included in the relations together with its matching value. ›  When is to used outer join ? 79
  • 80. SQL Joins ›  Retrieve only employee name and supervisor name for those who has supervisor. ›  Inner Join SELECT E.FNAME AS Employee_Name, S.LNAME AS Supervisor_Name FROM (EMPLOYEE AS E JOIN EMPLOYEE AS S ON E.SUPERSSN=S.SSN) 80
  • 82. SQL LEFT OUTER Joins ›  Retrieve all the employee name and its supervisor name. ›  That’s mean all employee tuple must be included. ›  We have to use outer join SELECT E.FNAME AS Employee_Name, S.LNAME AS Supervisor_Name FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.SUPERSSN=S.SSN) 82
  • 84. Aggregate function ›  There are 5 aggregate function in SQL. ›  COUNT (Return the number of tuples in rlation) ›  SUM (Return Summation of value ) ›  MAX (Return Maximum value in a relation) ›  MIN (Return Minimum value in a relation) ›  AVG (Return Average ) 84
  • 85. COUNT Product PRO_ID NAME V_CODE 1 FAN 21 2 DESK 22 3 PENCIL 22 4 ERASER 21 Result: SELECT COUNT(*) AS no_of_product; no_of_product 4
  • 86. SUM›  SELECT SUM(PRICE) AS Total ›  FROM product; Result: Total 850 Product PRO_ID NAME PRICE 1 FAN 200 2 DESK 220 3 PENCIL 220 4 ERASER 210
  • 87. AVG›  SELECT AVG(PRICE) AS total ›  FROM product; Result: total 212.5 Product PRO_ID NAME PRICE 1 FAN 200 2 DESK 220 3 PENCIL 220 4 ERASER 210
  • 88. MAX›  SELECT MAX(PRICE) AS max_price ›  FROM product; Result: max_price 220 Product PRO_ID NAME PRICE 1 FAN 200 2 DESK 220 3 PENCIL 220 4 ERASER 210
  • 89. Aggregate function ›  Find the maximum salary, the minimum salary, and the average salary among all employees. ›  SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE; 89
  • 90. GROUP DISCUSSION QUESTION1 Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. QUESTION2 Retrieve the number of employees in the ‘Administration Department' department 90
  • 93. GROUPING ›  In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation ›  Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s) ›  The function is applied to each subgroup independently ›  SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause 93
  • 94. GROUPING For each department, retrieve the department number, the number of employees in the department, and their average salary. SELECT DNO, COUNT (*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO; 94
  • 96. GROUPING ›  The EMPLOYEE tuples are divided into groups--each group having the same value for the grouping attribute DNO ›  The COUNT and AVG functions are applied to each such group of tuples separately ›  The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples ›  A join condition can be used in conjunction with grouping 96
  • 97. GROUPING ›  For each project, retrieve the project number, project name, and the number of employees who work on that project. SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER; ›  In this case, the grouping and functions are applied after the joining of the two relations 97
  • 99. THE HAVING-CLAUSE ›  Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions. ›  The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples) 99
  • 100. THE HAVING-CLAUSE ›  For each project on which more than two employees work , retrieve the project number, project name, and the number of employees who work on that project. SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER HAVING COUNT (*) > 2; 100
  • 102. Summary of SQL Queries ›  A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>] 102
  • 103. Summary of SQL Queries ›  The SELECT-clause lists the attributes or functions to be retrieved ›  The FROM-clause specifies all relations (or aliases) needed in the query but not those needed in nested queries ›  The WHERE-clause specifies the conditions for selection and join of tuples from the relations specified in the FROM-clause 103
  • 104. Summary of SQL Queries ›  GROUP BY specifies grouping attributes ›  HAVING specifies a condition for selection of groups ›  ORDER BY specifies an order for displaying the result of a query ›  A query is evaluated by first applying the WHERE-clause, then GROUP BY and HAVING, and finally the SELECT-clause 104
  • 105. SQL CASE ›  SQL CASE is a very unique conditional statement providing if/then/else logic for any ordinary SQL command, such as SELECT or UPDATE. ›  It then provides when-then-else functionality (WHEN this condition is met THEN do_this). ›  This functionality provides the developer the ability to manipulate the presentation of the data without actually updating or changing the data as it exists inside the SQL table. 105
  • 106. SQL CASE ›  SYNTAX CASE WHEN ‘VALUE’ THEN ‘STATEMENT’ ELSE ‘STATEMENT’ END AS ‘NEW ATTRIBUTENAME’ FROM TABLENAME; 106