0% found this document useful (0 votes)
4 views

Lecture04 -SQL Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture04 -SQL Part 1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction

to SQL – Part 1
Parvez Jugon
Structured Query Language (SQL) –
An Introduction
What is SQL?
SQL is a Programming Language, designed to manage data in a relational database.
Uses simple declarative statements (non-procedural)

Data Manipulation Language(DML) Data Definition Language(DDL)


SELECT CREATE
INSERT ALTER
UPDATE DROP
DELETE RENAME
MERGE TRUNCATE

Transaction Control (TCL) Data Control Language(DCL)


COMMIT GRANT
ROLLBACK REVOKE
SAVEPOINT
Before you start:

You should know the following before you start.

Structured
Query Entities

Language
(SQL) Attributes (Column names)

Data types

Relationships (relationship between


entities)

Constraints (Primary key, Foreign key,


Unique, Not null, Check, Default)
Structured Query Language (SQL) –
An Introduction
What is SQL?
It is a defacto Industry Standard.
There is an ANSI standard - although there are many different versions and dialects.
T-SQL commands may vary slightly from ANSI-SQL or SQL used in other systems (e.g.
MySQL)

SQL consists of 3 main components:


DDL - Data Definition Language
(used in the creation/destruction of relational tables, indexes, views etc.)
e.g. CREATE TABLE EMP
(empnum smallint not null,
ename char(15), Indentation and layout are not required
salary smallmoney, for execution
deptnum smallint); They are required for clarity.
When inserting data of type String or Date into a table, the
SQL – An Introduction values should be between inverted commas.
When querying data of
DML - Data Manipulation Language String or Date data type, it
should be queried between
(used for retrieval, appending, deleting, updating tables, etc) e.g.inverted commas.
INSERT INTO EMP DELETE FROM EMP
VALUES (1, 'Smith', 10000, 12); WHERE ename = 'Jones';
SELECT *
UPDATE EMP SELECT ename FROM EMP ;
SET salary = 20000 FROM EMP
WHERE ename = 'Smith' ; WHERE salary > 20000 ;

DCL - Data Control Language


(used for creating table permissions, valid users, etc)
e.g. GRANT ALL [PRIVILEGES ] ON EMP TO John
[WITH GRANT OPTION]; (assuming John is a registered user)
Some SQL Reserved Words
A complete list of operators is available on MYSQL website
SELECT HAVING UPDATE IN There are also a set of comparison operators:
FROM GROUP BY DELETE ASC =
WHERE DISTINCT INSERT SET
Equal to
AND DESC INTO AS
OR ORDER BY VALUES NOT <>
SQL – An Introduction
Some Common Data Types
Character Strings:
char(n) - data entries are consistent in size e.g. char (12)
varchar(n) - data entries vary considerably in size e.g. varchar (30)

Exact Numerics:
tinyint (0 to 255) smallint (-32,768 to 32,767),
int (-2,147,483,648 to 2,147,483,648) bigint (-2^63 to 2^63-1)
decimal [ (p[ ,s] )] – precision and scale e.g. decimal (7,2)

Dates and Times e.g. date = ‘1912-10-25’;


Date
DateTime
Visit MYSQL website to find a whole list of Data
Types
When querying data of String or
Date data type, it should be
When inserting data of type String or queried between inverted
Date into a table, commas.
the values should be between inverted
commas.
SQL – An Introduction CREATE DATABASE DATABASENAME;

Building a Database – Creating the Tables


Consider the following relational schema: EMPLOYEE (enum , ename, sdate, salary, floor)
With sample data as shown PROJECT (pnum , pname, leader)
WORKS_ON (enum* , pnum* , role)
EMPLOYEE
enum ename sdate salary floor
852341 Smith 2019/01/12 15000 1 WORKS_ON
852358 Jones 2019/07/11 19000 3 Notice the PKs
enum pnum role
852407 Brown 2020/03/03 16000 3 and FKs, and how 852341 121 Manager
852455 White 2020/04/09 25100 2 the tables will be 852341 135 Designer
852491 Adams 2018/07/12 30500 1 linked 852358 147 Consultant
852514 Doyle 2018/11/12 11650 2 852358 135 Consultant
852530 Evans 2020/08/06 26980 4 852407 216 Assistant
PROJECT Decide on the 852455 121 Assistant
pnum pname leader Data Types 852455 227 Manager
121 IT Gates 852491 135 Designer
135 Design Sinclair 852491 216 Manager
147 Analysis Einstein Can an attribute 852514 121 Assistant
216 Publicity Saatchi be NULL? 852514 216 Consultant
227 Theatre Dench 852514 251 Manager
251 Sport Shearer 852530 147 Manager
SQL – An Introduction SQL Style Guide:
1. Create the EMPLOYEE Table Table names and SQL Reserved words – ALL
EMPLOYEE (enum , ename, salary, floor) CAPS, words separated by underscore (_)
EMPLOYEE Attribute names – meaningful, all lowercase,
enum ename salary floor
words separated by underscore (_)
sdate
852341 Smith 2019/01/12 15000 1 Layout – generally, one SQL clause per line
852358 Jones 2019/07/11 19000 3
852407 Brown 2020/03/03 16000 3 Don’t waste storage space –
852455 White 2020/04/09 25100 2 choose data types that are just
852491 Adams 2018/07/12 30500 1 large enough.
852514 Doyle 2018/11/12 11650 2
852530 Evans 2020/08/06 26980 4 CREATE TABLE EMPLOYEE (
enum int not null,
ename char (15),
sdate date,
salary decimal (7,2),
Entity Integrity - no attributes floor tinyint,
participating in the primary key of a
CONSTRAINT pk_emp PRIMARY KEY (enum)
relation can accept null values.
);

In this example, pk_emp is the name


Primary Key Constraint – can be added given to the Primary Key Constraint
when the table is created, or added
later using an ALTER TABLE statement.
SQL – An Introduction CONSTRAINT in SQL can be
created at:
1. Table level
CREATE TABLE EMPLOYEE ( 2. Column level
enum int not null, Table level constraint And finally use the
ename char (15), Alter statement
sdate date,
salary decimal (7,2),
floor tinyint,
CONSTRAINT pk_emp PRIMARY KEY (enum)
); column level constraint

CREATE TABLE EMPLOYEE (


enum int PRIMARK KEY,
ename char (15),
sdate date,
salary decimal (7,2),
floor tinyint,
);
ALTER TABLE EMPLOYEE
ADD CONSTRAINT fk_wo1 PRIMARY KEY (enum);
ALTER TABLE WORKS_ON
ADD CONSTRAINT fk_wo2 FOREIGN KEY (enum) REFERENCES EMPLOYEE (enum);
SQL – An Introduction WORKS_ON
enum pnum role
2. Create the WORK_ON Table 852341 121 Manager
WORKS_ON (enum* , pnum* , role) 852341 135 Designer
852358 147 Consultant
CREATE TABLE WORKS_ON ( 852358 135 Consultant
enum int not null, 852407 216 Assistant
pnum smallint not null, 852455 121 Assistant
role char(15), 852455 227 Manager
CONSTRAINT pk_wo PRIMARY KEY (enum, 852491 135 Designer
pnum) 852491 216 Manager
We will use an ALTER TABLE statement to
852514 121 Assistant
); make enum and pnum FKs
Data Types must be the same as PKs in 852514 216 Consultant
corresponding tables 852514 251 Manager
3. Create the PROJECT Table 852530 147 Manager
PROJECT (pnum , pname, leader)
PROJECT
pnum pname leader
121 IT Gates
CREATE TABLE PROJECT (
135 Design Sinclair pnum smallint not null,
147 Analysis Einstein pname char(15),
216 Publicity Saatchi leader char(15),
227 Theatre Dench CONSTRAINT pk_proj PRIMARY KEY (pnum)
251 Sport Shearer );
SQL – An Introduction
Integrity Constraints can be used to apply business rules to the tables. They can be added in
the CREATE TABLE statement or later using ALTER TABLE

We have already seen NOT NULL and PRIMARY KEY

Constraints can be named – as earlier with PRIMARY KEY in the CREATE TABLE statements –
or applied directly to a column/attribute – as with not null.

Other useful constraints are :


DEFAULT − Provides a default value for a column when none is specified.
e.g., in the WORKS_ON table role char(15) DEFAULT ‘To be set’,
UNIQUE − Ensures that all values in a column are different.
e.g., in the PROJECT table leader char(15) UNIQUE,
CHECK − Ensures that all the values in a column satisfies certain conditions.
e.g., in the EMPLOYEE table floor tinyint CHECK (floor <= 7),

We’ll look at the FOREIGN KEY constraint now and INDEX (used to create and retrieve data
from the database very quickly) later in the module.
SQL – An Introduction
Building a Database – Create the Links (FKs) and establish Referential Integrity
Relational Schema: EMPLOYEE (enum , ename, salary, floor)
PROJECT (pnum , pname, leader)
WORKS_ON (enum*, pnum*, role)
Remember: If a relational table includes a foreign key (FK) matching the primary key (PK) of
another relational table, then every value of the FK must:
• either be equal to a value of the PK in some tuple (row)
• or be wholly NULL
Foreign Keys can be created, and Referential Integrity established, using an ALTER TABLE
statement OR at time when table is created.
Requires referencing from the Foreign Key towards a corresponding Primary Key in another
table
Attributes don’t have to
To put referential integrity between enum from WORKS_ON (FK) and have the same name,
enum from EMPLOYEE (PK) but MUST have the same
ALTER TABLE WORKS_ON Data Type
ADD CONSTRAINT fk_wo1 FOREIGN KEY (enum) REFERENCES EMPLOYEE (enum);
To put referential integrity between pnum from WORKS_ON (FK) & pnum from PROJECT (PK)
ALTER TABLE WORKS_ON
ADD CONSTRAINT fk_wo2 FOREIGN KEY (pnum) REFERENCES PROJECT (pnum);
SQL – An Introduction In general, may not be possible.
Depends on data types and if data
Other useful ALTER TABLE Commands has been entered already.
Changing a datatype/size (to whole numbers only)
ALTER TABLE EMPLOYEE
MODIFY COLUMN salary int; Delete budget attribute from PROJECT
Adding a new attribute (budget to PROJECT) ALTER TABLE PROJECT
DROP COLUMN budget;
ALTER TABLE PROJECT
ADD budget decimal (9,2);

Adding a PK (if not done in create table)


ALTER TABLE EMPLOYEE
ADD CONSTRAINT pk_emp PRIMARY KEY (enum);

Drop the PK from PROJECT (A two stage process:


1. Drop referential Integrity on PROJECT PK – refer by name
2. Drop the PK from PROJECT – refer by name)
ALTER TABLE WORKS_ON (drop referential integrity)
DROP INDEX fk_wo2;
Please note DROP CONSTAINT is
ALTER TABLE PROJECT (drop PK) used in Oracle, SQL Server and
DROP INDEX pk_proj; Access. DROP INDEX is used in
MYSQL
SQL – An Introduction When inserting data of type String or Date into a table,
the values should be between inverted commas.
Building a Database – Adding Records
General Syntax
INSERT INTO TABLENAME (attribute list)
VALUES (record values)
e.g. Add new employee record 852559 , 'Brown’, ‘2021/02/15’, 18000, 4
INSERT INTO EMPLOYEE (enum, ename, sdate, salary, floor)
VALUES (852559, 'Brown', ‘2021/02/15’, 18000, 4) ;
Which can be shortened where a whole record is added to:
EMPLOYEE
INSERT INTO EMPLOYEE
VALUES (852559, 'Brown', ‘2021/02/15’, 18000, 4);

Other ways to inserting records in a table (Selecting records from other table)
INSERT INTO CUSTOMERS(EMPLOYEE_ID, LASTNAME, FIRSTNAME, STARTDATE,
SALARY) SELECT EMPLOYEE_ID, LASTNAME, FIRSTNAME, STARTDATE, SALARY
FROM CUSTOMERS;

INSERT INTO CUSTOMERS


SELECT * FROM employee WHERE SALARY > 500;
enum ename sdate salary floor
SQL – An Introduction 852341
852358
Smith 2019/01/12
Jones 2019/07/11
15000 1
19000 3
Building a Database – Deleting Records 852407 Brown 2020/03/03 16000 3
852455 White 2020/04/09 25100 2
General Syntax
852491 Adams 2018/07/12 30500 1
DELETE FROM TABLENAME 852514 Doyle 2018/11/12 11650 2
WHERE selection clause; 852530 Evans 2020/08/06 26980 4
e.g. Delete employees earning above 18000 on the 2nd floor EMPLOYEE
DELETE FROM EMPLOYEE
WHERE salary > 18000
AND floor = 2 ;

Remove all records from table

TRUNCATE TABLE EMPLOYEE

*Referential Integrity applies


SQL – An Introduction
Building a Database – Editing Records
General Syntax
UPDATE TABLENAME
SET attribute = new value
WHERE selection clause;
e.g. Change the project leader of the Theatre project to Branagh
UPDATE PROJECT
SET leader = 'Branagh'
WHERE pname = ‘theatre';

NOTE – Referential Integrity must be considered when adding, deleting or updating records
Using the relational schema and sample data on slide 7, consider each of the examples
above. Will the queries execute correctly? INSERT INTO EMPLOYEE
VALUES (852559, 'Brown’,
1. Add new employee record ‘2021/02/15’, 18000, 4);
852559 , 'Brown', ‘2021/02/15’, 18000, 4
DELETE FROM EMPLOYEE
2. Delete employees earning WHERE salary > 18000
above 18000 on the 2nd floor AND floor = 2 ;

3. Change the project leader UPDATE PROJECT


of the Theatre project to Branagh SET leader = 'Branagh‘
WHERE pname = ‘theatre';
SQL – An Introduction
Consider the following relational schema: EMPLOYEE (enum , ename, salary, floor)
PROJECT (pnum , pname, leader)
With sample data as shown WORKS_ON (enum* , pnum* , role)
Will the following queries execute correctly?

EMPLOYEE PROJECT WORKS_ON


INSERT INTO EMPLOYEE 
VALUES (852559, 'Brown', 18000,
pnum pname leader enum
852341
pnum
121
role
Manager
121 IT Gates
‘2021/05/19’, 4);
135 Design Sinclair 852341 135 Designer
147 Analysis Einstein 852358 147 Consultant
216 Publicity Saatchi 852358 135 Consultant
DELETE FROM EMPLOYEE
WHERE salary > 18000
 227
251
Theatre
Sport
Dench
Shearer
852407
852455
216
121
Assistant
Assistant
AND floor = 2 ; 852455 227 Manager
enum ename sdate salary floor 852491 135 Designer
852341 Smith 2019/01/12 15000 1 852491 216 Manager
UPDATE PROJECT
SET leader = 'Branagh‘ 852358 Jones 2019/07/11 19000 3 852514 121 Assistant
WHERE pname = ‘theatre'; 852407 Brown 2020/03/03 16000 3 852514 216 Consultant
852455 White 2020/04/09 25100 2
 852491 Adams 2018/07/12 30500 1
852514
852530
251
147
Manager
Manager
852514 Doyle 2018/11/12 11650 2
852530 Evans 2020/08/06 26980 4
SQL – Queries on a Single Table
So far, we’ve seen a number of CRUD operations (C – INSERT, U – UPDATE & D – DELETE)
Now look at R operations – the SELECT statement – used to retrieve data/information from
the database
The general form of the SELECT statement is as follows:
SELECT <attribute list>
FROM <table list>
WHERE <selection clause>
[AND/OR/NOT <selection clause>….]
GROUP BY <attribute list> [grouping]
HAVING <aggregate function selection> [between groups]
ORDER BY <attribute list> [sorting]
For example, the natural language query: Get the names and salaries of all employees
who are on the first floor
can be answered using SQL query: SELECT always returns a table
- even if a single value is returned..
SELECT ename, salary
FROM EMPLOYEE
May want information returned
WHERE floor = 1 ;
from more than one table
List all tables used in the query.
SQL – Queries on a Single Table
In the examples that follow the EMPLOYEE, PROJECT, WORKS_ON database is used -
with relational schema EMPLOYEE (enum, ename, sdate, salary, floor)
PROJECT (pnum, pname, leader)
and sample data as shown
WORKS_ON (enum*, pnum*, role)
EMPLOYEE
WORKS_ON
enum ename sdate salary floor enum pnum role
852341 Smith 2019/01/12 15000 1 852341 121 Manager
852358 Jones 2019/07/11 19000 3 852341 135 Designer
852358 147 Consultant
852407 Brown 2020/03/03 16000 3 852358 135 Consultant
852455 White 2020/04/09 25100 2 852407 216 Assistant
852491 Adams 2018/07/12 30500 1 852455 121 Assistant
852514 Doyle 2018/11/12 11650 2 852455 227 Manager
852530 Evans 2020/08/06 26980 4 852491 135 Designer
852491 216 Manager
852514 121 Assistant
PROJECT 852514 216 Consultant
pnum pname leader 852514 251 Manager
121 IT Gates 852530 147 Manager
135 Design Sinclair
147 Analysis Einstein
216 Publicity Saatchi
227 Theatre Dench
251 Sport Shearer
SQL – Queries on a Single Table
How to Construct an SQL SELECT Query
Need to interpret the meaning of the natural language query (sentence) to find:
1. What columns do we want to see in the query result table?
(Which attributes (columns) go into the SELECT clause?)
2. What other attributes are involved in the query
(for selecting in a WHERE/AND/OR/NOT clause)
or grouping (GROUP BY clause)
or choosing between groups (HAVING clause)
or sorting (ORDER BY clause)
3. What table(s) are required to get all the attributes involved in the SELECT clause or
from the WHERE, GROUP BY, HAVING or ORDER BY clauses
(all the tables used will be included in the FROM clause)
For example: Get the names and salaries of all employees who are on the first floor
4. Attributes in SELECT clause:
We want the names of the employees (ename)
and the salaries of the employees (salary)
5. The WHERE clause attributes:
We need to find employees on the first floor (floor = 1)
6. Table(s) with required attributes in FROM clause:
ename, salary and floor all come from the EMPLOYEE table
SQL – Queries on a Single Table
So, the natural language query: Get the names and salaries of all employees who are on
the first floor
can be answered using an SQL query:
Names and salaries.
SELECT ename, salary
FROM EMPLOYEE All attributes are in the EMPLOYEE table.
WHERE floor = 1 ;
On the first floor.
EMPLOYEE Result Table
enum ename sdate salary floor ename salary
852341 Smith 2019/01/12 15000 1 Smith 15000
852358 Jones 2019/07/11 19000 3 Adams 30500
852407 Brown 2020/03/03 16000 3
852455 White 2020/04/09 25100 2 Get the employee details of all employees on the
852491 Adams 2018/07/12 30500 1 first floor
852514 Doyle 2018/11/12 11650 2 SELECT * * - all attributes Limit can be
used to restrict
852530 Evans 2020/08/06 26980 4 FROM EMPLOYEE number of
WHERE floor = 1 ; rows. E.g.
LIMIT 1
SELECT * Result Table
enum ename sdate salary floor
is equivalent to
852341 Smith 2019/01/12 15000 1
SELECT enum, ename, sdate, salary, 852491 Adams 2018/07/12 30500 1
floor
SQL – Queries on a Single Table
Get the names and salaries of all employees who earns more than 20000
SELECT ename, salary
FROM EMPLOYEE
WHERE salary > 20000 ;

Get a list of staff and the salaries they earn ordering by those who earn the highest salary?

Get the staff who earns the highest salary?


SQL – LIMIT
So, the natural language query: Get the names and salaries of the employees with the
highest salary on the first floor. (HINT: use LIMIT)
can be answered using an SQL query:
SELECT ename, salary Names and salaries.
FROM EMPLOYEE
WHERE floor = 1 All attributes are in the EMPLOYEE table.
ORDER BY salary DESC On the first floor.
LIMIT 1 ; Display only 1
record Result Table
EMPLOYEE ename salary
enum ename salary floor Adams 30500
sdate
852341 Smith 2019/01/12 15000 1
852358 Jones 2019/07/11 19000 3
852407 Brown 2020/03/03 16000 3
852455 White 2020/04/09 25100 2
852491 Adams 2018/07/12 30500 1
852514 Doyle 2018/11/12 11650 2
852530 Evans 2020/08/06 26980 4
SQL – Queries on a Single Table
WHERE Clauses with an AND
Get the employee numbers for employees in project 121 who have an Assistant role
SELECT enum Result Table
FROM WORKS_ON enum
WHERE pnum = 121 852455
AND role = 'Assistant' ; 852514
WORKS_ON
enum pnum role Alternative WHERE Clauses with an OR
852341 121 Manager
852341 135 Designer
Get the name of employees working on the 1st
852358 147 Consultant or 2nd floor EMPLOYEE
852358 135 Consultant SELECT ename
852407 216 Assistant
852455 121 Assistant FROM EMPLOYEE enum ename sdate salary floor
852455 227 Manager WHERE floor = 1 852341 Smith 2019/01/12 15000 1
852491 135 Designer OR floor = 2 ; 852358 Jones 2019/07/11 19000 3
852491 216 Manager Result Table 852407 Brown 2020/03/03 16000 3
852514 121 Assistant ename 852455 White 2020/04/09 25100 2
852514 216 Consultant Smith 852491 Adams 2018/07/12 30500 1
852514 251 Manager 852514 Doyle 2018/11/12 11650 2
White 852530 Evans 2020/08/06 26980 4
852530 147 Manager Adams
Doyle
SQL – Queries on a Single Table
Calculation

SELECT ename, salary, salary+100


FROM EMPLOYEE;

**Use parentheses
SELECT ename, salary, 12*(salary+100)
FROM EMPLOYEE;
SELECT ename
SQL – Comparison Conditions FROM EMPLOYEE
WHERE ename LIKE 'S%';

SELECT * EMPLOYEE
WHERE floor IS NULL;

SELECT * EMPLOYEE
WHERE floor IS NOT NULL;

INSERT INTO EMPLOYEE(enum, INSERT INTO WORKS_ON(enum,


ename, sdate, salary, floor) VALUES pnum, role) VALUES
(856666, ’Jonas’, (856666, 121, NULL);
'2020/11/11',22750, NULL);
SQL – Comparison Conditions
SQL also provides several Logical Operators used to test for the truth of some condition.
We have already seen AND, OR, BETWEEN, NOT and IN – (there are a number of others)
The LIKE Operator
LIKE allows the use of wildcards to perform pattern matching on an attribute in a query.
It can be used in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.
% wildcard representing any string of characters
_ wildcard representing a single character
[ ] looks for any match within a range of characters e.g. [a-m]
[^ ] looks for any match not in the specified range e.g. [^a-m]

Some Examples:
Get the names of employees starting with 'S‘ Get the names of employees containing the
string 'row' anywhere

SELECT ename SELECT ename FROM


EMPLOYEE
FROM EMPLOYEE
WHERE ename LIKE '%row%';
WHERE ename LIKE 'S%';
Get the names of employees with any
SELECT ename FROM characters from n to r
EMPLOYEE
SELECT ename
WHERE ename LIKE 'D_le';
FROM EMPLOYEE
WHERE ename LIKE '%[n-r]%';
SQL – NULL VALUES - NVL

To convert a null value to an actual value, use the NVL


function.
Syntax: NVL (expr1, expr2)
• expr1 is the source value or expression that may
contain a null
• expr2 is the target value for converting the null

Data Type Conversion Example


Number NVL(number_column,9)
Date NVL(date_column, ’2020-01-03')
CHAR or VARCHAR2 NVL(character_column, 'Unavailable')

SELECT enum, pnum,


SELECT enum, ename, NVL(floor, 0) NVL(role, 'NOT ASSIGNED')
FROM EMPLOYEE; FROM EMPLOYEE;
SQL – NULL VALUES
NVL2
SELECT enum, NVL2(floor, 'Assigned a floor', 'Not assigned a floor')
FROM EMPLOYEE

The NVL2 function examines the first expression. If the first expression is not null,
then the NVL2 function returns the second expression. If the first expression is null,
then the third expression is returned.

SELECT enum, pnum, NVL2(Role, 'Assigned', 'Not assigned')


FROM EMPLOYEE

NULLIF

SELECT enum, LENGTH(enum) "expr1", ename, LENGTH(ename) "expr2",


NULLIF(LENGTH(enum), LENGTH(enum)) result
FROM EMPLOYEE

The NULLIF function compares two expressions.


If they are equal, the function returns null.
If they are not equal, the function returns the first expression.
You cannot specify the literal NULL for first expression.
SQL – NULL VALUES
COALESCE

SELECT last_name,
COALESCE(commission_pct, salary, 10) comm
FROM employee ORDER BY commission_pct;

If the COMMISSION_PCT value is not null, it is shown.


If the COMMISSION_PCT value is null, then the SALARY is shown.
If the COMMISSION_PCT and SALARY values are null, then the value 10 is shown.

*example is not in the sample table provided


SQL – Queries on a Single Table
Other Useful Operators with the WHERE Clause
Using the IN Operator to Specify Multiple Values in a WHERE Clause.
SELECT ename
FROM EMPLOYEE
WHERE floor IN (1, 2);
Using the BETWEEN Operator to Select Values within a Range
SELECT ename values can be numbers,
FROM EMPLOYEE text, or dates.
WHERE ename BETWEEN ‘Adams’ AND ‘Evans’;
The NOT Operator
Get the names of employees on all floor, except floors 1 and 3
SELECT ename
FROM EMPLOYEE
WHERE floor NOT IN (1, 3);
Combining Operators in the WHERE Clause.
Operators can be combined to form more complex queries, using parenthesis as
necessary to establish precedence.
SELECT *
Get details of all projects between FROM PROJECT
project number 121 and 227, WHERE pnum BETWEEN 121 AND 227
except those led by Sinclair or Saatchi AND leader NOT IN (‘Sinclair’, ‘Saatchi’);
SQL – Aliases & Concatenation
Column aliases

SELECT ename, salary + 100 AS ‘Total Salary’


FROM employee;
Table aliases
SELECT ename, salary + 100 AS “Salary” Very useful when Joining several
FROM employee; Tables.

SELECT e.ename, e.salary+100 AS “Salary”


FROM employee e;

Concatenation
SELECT CONCAT(enum, ” ", ename, ” ", salary)
FROM Employee;
SQL – Date
DEFAULT DATE IN MariaDB is YYYY-MM-DD
Today’s date  Now()

SELECT enum, sdate, salary


FROM EMPLOYEE;

SELECT enum, YEAR(sdate), salary


FROM EMPLOYEE;

SELECT enum, MONTH(sdate), salary


FROM EMPLOYEE; SELECT sdate, ADDDATE(sdate, INTERVAL 6 MONTH)
FROM EMPLOYEE;

SELECT sdate, ADDDATE(sdate, INTERVAL 6 YEAR)


FROM EMPLOYEE;

SELECT sdate, ADDDATE(sdate, INTERVAL 6 DAY)


FROM EMPLOYEE;
SQL – Aggregate Functions
Aggregate Functions
SQL provides a number of built-in aggregate functions that return a single value, calculated
from values in a column.
SUM( ) - Returns the Total Value
AVG( ) - Returns the Average Value
MAX( ) - Returns the Highest Value
MIN( ) - Returns the Lowest Value
COUNT( ) - Returns the number of tuples (rows) in result table
Aggregate functions can ONLY appear in SELECT and HAVING clauses
What is the total salary of all employees? Aggregate functions normally appear
SELECT SUM(salary) alone in a SELECT clause (except for
Result
the special case where a GROUP BY
FROM EMPLOYEE; 144230 clause is present)
What is the average salary for employees on the 3rd floor?
SELECT AVG(salary)
Result
FROM EMPLOYEE * - can be used ONLY with COUNT
20604
WHERE floor = 3 ; COUNT using PK or * - other attributes
may be NULL.
How many employees are on the 1st floor?
SELECT COUNT (*) or SELECT COUNT (enum)
FROM EMPLOYEE FROM EMPLOYEE Result
WHERE floor = 1; WHERE floor = 1; 2
SQL – Aggregate Functions

SELECT COUNT(*)
FROM EMPLOYEE; COUNT all rows even
duplicates
SELECT COUNT(floor)
FROM EMPLOYEE;

SELECT COUNT(DISTINCT floor) IGNORING duplicates when


FROM employee; Counting.
**DISTINCT RETURNS NON-DUPLICATE COLUMNS.
**MORE EXAMPLE ON NEXT SLIDE

What will this query do?

SELECT DISTINCT floor


FROM employee;
SQL – Queries on a Single Table
The ORDER BY Clause
Uses options ASC - ascending or DESC - descending
e.g. List the employee names in alphabetic order ename
Adams
SELECT ename Brown
FROM EMPLOYEE Doyle
ORDER BY ename ASC; Evans
ASC is the default value and thus not Jones
strictly necessary in this example Smith
White
The DISTINCT Predicate
Eliminates duplicate tuples (rows)
e.g. Get a list of roles worked on (without repeat values) role
Manager
SELECT DISTINCT role
Designer
FROM WORKS_ON; Consultant
Assistant
DISTINCT clauses are most useful when used with an attribute which does Administrator
NOT have unique values and the duplicated result rows are not required

Without DISTINCT, the query would return multiple entries for each role –
as per the original WORKS_ON table
SQL – Queries on a Single Table
The GROUP BY Clause
Groups result table by attribute(s).
GROUP BY clauses group the data by value using a field that MUST therefore have
duplicate values so that at least some groups have multiple records.
An aggregate function can then be applied to each group.
All simple attributes appearing in the SELECT clause MUST appear in the GROUP BY clause
e.g. Get the average salary by floor of all employees
Result Table
SELECT floor, AVG(salary)
floor AVG (salary)
FROM EMPLOYEE
1 22750
GROUP BY floor ; 2 18375
3 17500
EMPLOYEE 4 26980
enum ename salary floor
852341 Smith 15000 1
852358 Jones 19000 3 Get the total salary spent by the company per year
852407 Brown 16000 3
852455 White 25100 2 SELECT YEAR(sdate), SUM(salary)
852491 Adams 30500 1 FROM EMPLOYEE
852514 Doyle 11650 2
GROUP BY YEAR(sdate) ;
852530 Evans 26980 4
SQL – Queries on a Single Table
When GROUP BY clauses are being used:
Can't use a normal attribute in the GROUP BY clause that does not already appear in the
SELECT clause
Don’t use more than one attribute in the GROUP BY clause (unless you intend to use
grouping and subgrouping – not covered in these notes)
The attribute you group by should normally be repeated in the SELECT clause
The HAVING Clause
Can ONLY be used when a GROUP BY clause is present - used to choose between groups.
Can ONLY contain expressions using aggregate functions
e.g. Get the floors having two or more employees Result Table
SELECT floor floor
FROM EMPLOYEE 1
GROUP BY floor 2
HAVING COUNT(*) >= 2 ; 3
HAVING clauses are used to choose between groups and cannot appear without a preceding
GROUP BY clause.
HAVING clauses MUST be constructed as:
Aggregate function compared with a value
count( ), avg( ), etc =, <, >, etc number

You might also like