DBAS20146
Module 6
Introduction to SQL
Sheridan College
SQL Overview
◼ SQL - Structured Query Language
◼ The standard for relational database management
systems (RDBMS)
◼ RDBMS: A database management system that
manages data as a collection of tables in which all
relationships are represented by common values
in related tables
Purpose of SQL Standard
◼ -Specify syntax/semantics for data definition and
manipulation
◼ -Define data structures and basic operations
◼ -Enable portability of database definition and
application modules
◼ -Allow for later growth/enhancement to standard
Benefits of a Standardized
Relational Language
-Reduced training costs
-Productivity
-Application portability
-Reduced dependence on a single vendor
-Cross-system communication
SQL Environment
◼ Data Definition Language (DDL)
◼ Commands that define a database, including creating, altering,
and dropping tables and establishing constraints
◼ Data Manipulation Language (DML)
◼ Commands that maintain and query a database
◼ Data Control Language (DCL)
◼ Commands that control a database, including administering
privileges and committing data
DDL, DML, DCL, and the database development process
Basic Select statement
▪ A Keyword refers to an individual SQL element
• For example, SELECT and FROM are keywords
▪ A clause is a part of SQL statement
• For example: SELECT cname, …. Is a clause
▪ A statement is a combination of two or more
clauses
• For example: SELECT * FROM hr.locations; is a SQL
statement
Writing SQL statements
• SQL statements are not case sensitive
– To enhance readability we use UPPERCASE for keywords and lowercase for tables and
columns
• SQL statements can be on one or more lines
• Keywords cannot be abbreviated or split
across lines
• Clauses are usually placed on separate lines
• Indents are used to enhance readability
Clauses of SELECT Statement
• The four clauses of the SELECT statement
– SELECT
– FROM
– WHERE
– ORDER BY
• All select clauses must have a FROM clause
SELECT *
FROM hr.locations;
You’ll get the result set and the number of rows
selected:
23 rows selected
More on SELECT Clause
• Five ways to code column specifications
– All columns in base table
– Column name in base table
– Concatenation
– Calculation
– Scalar function
s9.tbl_customer s9.tbl_ orders s9.tbl_ orderline
custnum custname city creditlimit ordernum orderdate filled custnum ordernum productnum quantity salesprice
1 Foxbar Toronto 1000 1 15-Aug-17 Y 1 1 7 2 34.99
2 Ironwood Oakville 100 2 4-Oct-17 Y 2 2 6 1 980
3 Kent Burlington 2000 3 23-Nov-17 Y 3 3 4 16 25
4 Moore Toronto 1000 4 12-Jan-18 Y 4 4 1 1 44.95
5 Felipe Mississauga 4500 5 1-Feb-18 N 2 5 2 1 99.99
6 Kwan Toronto 0 6 1-Feb-18 Y 1 5 8 1 25.99
7 Khoury Mississauga 1000 7 6-Feb-18 Y 5 6 7 1 34.99
8 Brant Oakville 1500 8 16-Feb-18 N 10 7 3 1 299.99
9 Wells Burlington 0 9 16-Feb-18 Y 8 8 2 1 99.99
10 Wright Toronto 1000 10 21-Feb-18 N 2 9 5 2 29.99
11 21-Feb-18 N 5 10 5 11 27.5
12 21-Feb-18 N 6 11 3 1 295
13 26-Feb-18 N 5 11 4 3 42
14 28-Feb-18 N 1 11 5 4 27.5
s9.tbl_ product 15 2-Mar-18 N 2 12 5 1 25.99
13 6 1 975
14 7 2 34.99
productnum descr producttype msrp onhand
15 2 1 105
1 Swiss army knife Sports 44.95 22
15 7 1 34.99
2 Electric heater Hardware 99.99 10
3 Snowboard Sports 299.99 37
4 Hockey stick Sports 27.5 172
5 Snow shovel Hardware 29.99 53
6 Stove Appliance 989.99 7
7 Toaster Appliance 34.99 12
8 Jumper cables Hardware 25.99 38
Data Manipulation Language (DML)
The SELECT statement
SELECT *
FROM schema.tablename
Examples:
SELECT * FROM s9.tbl_customer;
SELECT * FROM s9.tbl_orders;
SELECT * FROM s9.tbl_ orderline;
SELECT * FROM s9.tbl_ product;
*schema - if table is outside of user’s schema
Selecting only some fields…
SELECT custnum, custname
FROM s9.tbl_ customer;
custnum custname
3 Kent
4 Moore
5 Felipe
7 Khoury
8 Brant
9 Wells
13 Ironwood
14 Joe
15 Test22
16 Joe G.
Defining a Column Alias
• By default the column name becomes the
name of the column in a result set.
• The column name can be changed using a
column alias, which:
– Renames a column heading
– Can be useful with calculations
– Immediately follows the column name
• An optional ‘AS’ keyword can be written between the
column name and alias
– Requires double quotation marks if it contains
spaces or special characters or is case sensitive or
contains reserved words such “date”
Changing column names
Compare these two SQL statements:
SELECT custnum SELECT custnum AS cust_no
FROM s9.tbl_ customer; FROM s9.tbl_ customer;
custnum cust_no
3 3
4 4
5 5
7 7
8 8
9 9
13 13
14 14
15 15
16 16
SELECT ordernum, productnum, quantity, salesprice
FROM s9.tbl_ orderline;
ordernum productnum quantity salesprice
1 7 2 34.99
2 6 1 980
3 4 16 25
4 1 1 44.95
5 2 1 99.99
5 8 1 25.99
6 7 1 34.99
7 3 1 299.99
8 2 1 99.99
9 5 2 29.99
10 5 11 27.5
11 3 1 295
11 4 3 42
11 5 4 27.5
12 8 1 25.99
13 6 1 975
14 7 2 34.99
15 2 1 105
15 7 1 34.99
Using Expressions
• An expression is a combination of column names
and operators that evaluate a single value.
• Arithmetic expressions contain numbers and
date data type combined with arithmetic
operators
– Parentheses are used to force prioritized evaluation and to clarify statements
• String expressions consists of a combination of
one or more character columns and literal values
– Uses concatenation operator (||)
• A null is a value that is unavailable, unassigned,
unknown or inapplicable
– A null is not the same as zero or blank space.
Using Arithmetic Expressions
• Arithmetic expressions use numeric or date values
and arithmetic operators
– Arithmetic operators are: +, -, * and /
– The arithmetic operators in order of precedence:
• * Multiplication
• / Division
• + Addition
• - Subtraction
– Use brackets to change the order of calculations
• Example:
SELECT first_name, last_name,
salary * 12 AS "Annual
Salary"
FROM hr.employees;
SELECT ordernum, productnum, quantity, salesprice, quantity * salesprice
FROM s9.tbl_ orderline;
ordernum productnum quantity salesprice quantity * salesprice
1 7 2 34.99 69.98
2 6 1 980 980
3 4 16 25 400
4 1 1 44.95 44.95
5 2 1 99.99 99.99
5 8 1 25.99 25.99
6 7 1 34.99 34.99
7 3 1 299.99 299.99
8 2 1 99.99 99.99
9 5 2 29.99 59.98
10 5 11 27.5 302.5
11 3 1 295 295
11 4 3 42 126
11 5 4 27.5 110
12 8 1 25.99 25.99
13 6 1 975 975
14 7 2 34.99 69.98
15 2 1 105 105
15 7 1 34.99 34.99
SELECT ordernum, productnum, quantity, salesprice, quantity * salesprice AS totalprice
FROM s9.tbl_ orderline;
ordernum productnum quantity salesprice totalprice
1 7 2 34.99 69.98
2 6 1 980 980
3 4 16 25 400
4 1 1 44.95 44.95
5 2 1 99.99 99.99
5 8 1 25.99 25.99
6 7 1 34.99 34.99
7 3 1 299.99 299.99
8 2 1 99.99 99.99
9 5 2 29.99 59.98
10 5 11 27.5 302.5
11 3 1 295 295
11 4 3 42 126
11 5 4 27.5 110
12 8 1 25.99 25.99
13 6 1 975 975
14 7 2 34.99 69.98
15 2 1 105 105
15 7 1 34.99 34.99
SELECT ordernum, productnum, quantity, salesprice, quantity * salesprice AS
totalprice,(quantity * salesprice) * 0.13 AS tax, (quantity * salesprice)+((quantity *
salesprice) * 0.13) AS totalwithtax
FROM s9.tbl_ orderline;
ordernum productnum quantity salesprice totalprice tax totalwithtax
1 7 2 34.99 69.98 9.0974 79.0774
2 6 1 980 980 127.4 1107.4
3 4 16 25 400 52 452
4 1 1 44.95 44.95 5.8435 50.7935
5 2 1 99.99 99.99 12.999 112.9887
5 8 1 25.99 25.99 3.3787 29.3687
6 7 1 34.99 34.99 4.5487 39.5387
7 3 1 299.99 299.99 38.999 338.9887
8 2 1 99.99 99.99 12.999 112.9887
9 5 2 29.99 59.98 7.7974 67.7774
10 5 11 27.5 302.5 39.325 341.825
11 3 1 295 295 38.35 333.35
11 4 3 42 126 16.38 142.38
11 5 4 27.5 110 14.3 124.3
12 8 1 25.99 25.99 3.3787 29.3687
13 6 1 975 975 126.75 1101.75
14 7 2 34.99 69.98 9.0974 79.0774
15 2 1 105 105 13.65 118.65
15 7 1 34.99 34.99 4.5487 39.5387
Retrieving calculated Values
• You can retrieve values that are calculated from
multiple columns. For example:
– How much is the difference between the highest and
the lowest salary for each job title?
SELECT max_salary - min_salary, job_title
FROM hr.jobs;
– The column name for the calculated value is the entire
expression
– You can use alias to display more meaningful column
name:
SELECT max_salary - min_salary AS difference,
job_title AS “Job Title”
FROM hr.jobs;
SELECT CONCAT ('Customer Name:', custname , ' , Customer Number: ' , custnum)
FROM s9.tbl_customer;
CONCAT ('Customer Name:', custname , ' , Customer Number: ' , custnum)
Customer Name:Kent , Customer Number: 3
Customer Name:Moore , Customer Number: 4
Customer Name:Felipe , Customer Number: 5
Customer Name:Khoury , Customer Number: 7
Customer Name:Brant , Customer Number: 8
Customer Name:Wells , Customer Number: 9
Customer Name:Ironwood , Customer Number: 13
Customer Name:Joe , Customer Number: 14
Customer Name:Test22 , Customer Number: 15
Customer Name:Joe G. , Customer Number: 16
SELECT CONCAT ('Customer Name:', custname , ' , Customer Number: ' , custnum) AS
customer_info
FROM s9.tbl_customer;
customer_info
Customer Name:Kent , Customer Number: 3
Customer Name:Moore , Customer Number: 4
Customer Name:Felipe , Customer Number: 5
Customer Name:Khoury , Customer Number: 7
Customer Name:Brant , Customer Number: 8
Customer Name:Wells , Customer Number: 9
Customer Name:Ironwood , Customer Number: 13
Customer Name:Joe , Customer Number: 14
Customer Name:Test22 , Customer Number: 15
Customer Name:Joe G. , Customer Number: 16
Formatting String Values
• You can combine data from the tables by
concatenating them.
• Besides strings and printable characters you can
combine special non-printable character for
formatting purposes:
– CHR(10) – new line
– CHR(13) - carriage return (not used in linux).
– CHR(9) is a tab
SELECT first_name || ' ' || last_name || CHR(10) ||
'Email: ' || CHR(9) || email || CHR(10) ||
'Phone: ' || CHR(9) || phone_number
FROM hr.employees;
Scalar Functions in Oracle
• TO_DATE function
In Oracle, TO_DATE function converts a string value to DATE data type value using the
specified format. ; SELECT TO_DATE('2012-06-05', 'YYYY-MM-DD') FROM dual;
• TO_CHAR function
– Converts a DATETIME, number, expression to a TEXT expression in a
specified format
• SYSDATE function
– Returns today’s date and time
• ROUND function
SELECT ROUND(123.456, 2) FROM dual;
DATE PART QUERIES
SELECT EXTRACT (year FROM orderdate) AS y
FROM s9.tbl_orders;
DATE PART QUERIES
SELECT EXTRACT (day FROM orderdate) AS d,
EXTRACT (month FROM orderdate) AS m,
EXTRACT (year FROM orderdate) AS y
FROM s9.tbl_orders;
• The above query pulls out the various parts of the orderdate column in the
orders table
• Notice each value is separated and listed as its own column in the resultset
DAYNAME/DATENAME (MySQL/SQL Server)
• If we want to know the day name for a specific date, we
can use the DAYNAME() function in MySQL or
DATENAME() in MS SQL Server or use
TO_CHAR(TO_DATE) in Oracle
MySQL:
SELECT DAYNAME('2013-01-23') FROM dual;
MS SQL Server:
SELECT DATENAME(w,'2013-01-23’)
Oracle:
SELECT TO_CHAR(TO_DATE('2013-01-23','yyyy-mm-
dd'),'day') AS dayname FROM dual;
DAYNAME('2013-01-23')
Wednesday
DATENAME (Transact-SQL) – MS SQL Server
• Returns a character string that represents the
specified datepart of the specified date
datepart Abbreviations
Syntax
year yy, yyyy
SELECT DATENAME ( datepart , date )
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
TZoffset tz
ISO_WEEK ISOWK, ISOWW
DAY NAME (MySQL/SQL Server), Oracle
• We might also include DAYNAME (or
DATENAME) as part of a larger query ordernum orderdate DAYNAME(orderdate)
MySQL:
1 05/09/1997 Friday
SELECT ordernum, orderdate, DAYNAME(orderdate)
2 05/09/1997 Friday
FROM orders ;
3 05/09/1997 Friday
4 01/10/1997 Wednesday
MS SQL Server: 5 08/10/1997 Wednesday
SELECT ordernum, orderdate, 6 19/10/1997 Sunday
DATENAME(w,orderdate) 7 15/10/1997 Wednesday
FROM orders ; 8 17/10/1997 Friday
9 04/11/1997 Tuesday
ORACLE: 10 06/11/1997 Thursday
SELECT ordernum, 11 01/12/1997 Monday
orderdate,TO_CHAR(TO_DATE(orderdate,'yyyy-mm- 12 04/12/1997 Thursday
dd'),'day') AS dayname 13 08/12/1997 Monday
FROM s9.tbl_orders ; 14 15/12/1997 Monday
15 17/12/1997 Wednesday
Display current system date
Using MySQL: Using MS SQL Server:
• CURDATE() • GETDATE()
Will display current system date Will display current system date
Example: Example:
SELECT CURDATE() FROM dual; SELECT GETDATE();
CURDATE()
03/09/2014 2014-09-03 17:46:39.400
Using Oracle:
SELECT SYSDATE FROM dual;
ORACLE:
SELECT ordernum, orderdate, ROUND(SYSDATE - orderdate) AS numofdays
FROM s9.tbl_orders ;
Example
• Table employee contains the hiring date. Use
that information to find out how many years
each employee has been working for?
SELECT first_name, last_name,
ROUND((SYSDATE - hire_date)/365) AS
"Years"
FROM hr.employees;
WHERE Clause
• WHERE clause is used to filter the rows in the
base table:
– If WHERE is omitted all base table rows will be included.
• WHERE clause can also be a search condition which consists of one or more Boolean expressions
– All Boolean expressions are evaluated and the result is applied to WHERE clause
SELECT *
FROM hr.employees
WHERE department_id = 100 AND salary >= 7000;
OR try
SELECT *
FROM s9.tbl_customer
WHERE UPPER(city) = 'TORONTO’;
**Oracle data is case-sensitive – convert to UPPER
cases both sides to get better results
Comparison Operators
• Examples:
SELECT * FROM hr.employees WHERE salary > 20000;
Or try:
SELECT * FROM s9.tbl_customer WHERE creditlimit >0;
Other Comparison Operators
• Example:
SELECT *
FROM hr.employees
WHERE salary BETWEEN 15000 AND 20000;
Logical Conditions
• Example:
SELECT *
FROM hr.employees
WHERE salary >10000 AND department_id = 100;
Or try:
SELECT * FROM s9.tbl_customer
WHERE creditlimit >0 AND city LIKE 'Tor%';
Rules of Precedence
Eliminating Duplicate Rows
• Eliminate duplicate rows by using the
DISTINCT keyword in the SELECT clause
SELECT DISTINCT salary FROM hr.employees;
SELECT DISTINCT city FROM s9.tbl_customer;
• To eliminate duplicate rows in the result, use
the DISTINCT keyword in the SELECT
statement immediately after the SELECT
keyword
ORDER BY Clause
• ORDER BY clause sorts the result set based on specified field
and sequence
SELECT * FROM hr.employees
WHERE department_id = 100 AND salary >= 7000
ORDER BY first_name;
Or try:
SELECT *
FROM s9.tbl_customer
WHERE creditlimit >0
AND city LIKE 'Tor%'
ORDER BY custname DESC;
Aggregate Functions
• Aggregate operate on series of values and
return a single summary value
– AVG([ALL|DISTINCT] expression)
– SUM([ALL|DISTINCT] expression)
– MIN([ALL|DISTINCT] expression)
– MAX([ALL|DISTINCT] expression)
– COUNT([ALL|DISTINCT] expression)
– COUNT(*)
• Null values are always excluded from these functions
• Example:
– Find the most highest salary in the hr database
SELECT MAX(salary)
FROM hr.employees;
Aggregate Functions
• Aggregate operate on series of values and
return a single summary value
– AVG([ALL|DISTINCT] expression)
– SUM([ALL|DISTINCT] expression)
– MIN([ALL|DISTINCT] expression)
– MAX([ALL|DISTINCT] expression)
– COUNT([ALL|DISTINCT] expression)
– COUNT(*)
• Null values are always excluded from these functions
• Example:
– Number of customers in s9.tbl_customer:
SELECT COUNT(*) AS numofcust
FROM s9.tbl_customer;
Aggregate Functions
– Number of customers from city starting with Tor and credit limit greater than zero in
s9.tbl_customer:
SELECT COUNT(*) AS numofcust
FROM s9.tbl_customer
WHERE creditlimit >0
AND city LIKE 'Tor%’;
Try this:
SELECT COUNT(*),MIN(msrp),MAX(msrp),
ROUND(AVG(msrp),2),SUM(msrp),SUM(onhand)
FROM s9.tbl_product;
Exercise
• What is the average salary of the employees
from the finance department (department_id
= 100)? Round the result to two decimal
places.
SELECT ROUND(AVG(salary), 2)
FROM hr.employees
WHERE department_id = 100;
Subqueries
• A subquery is a SELECT statement that is
coded inside another SQL statement
• A subquery can return:
– A single value
– A single columns
– A result set
• Example:
– Who are the employee(s) that left the company on 2007-12-31?
SELECT *
FROM hr.employees
WHERE employee_id IN
(SELECT employee_id
FROM hr.job_history
WHERE end_date = '2007-12-31');
Exercise
• Which departments are not located in US and
Canada
– Hint: use sub query to find the location_id-s that are not located in US and CA and use those
values to compare with location_id-s of departments table .
• Solution
SELECT department_id, department_name
FROM hr.departments
WHERE location_id NOT IN
(SELECT location_id
FROM hr.locations
WHERE country_id IN ('US', 'CA'));
Exercise
• Which products have never been ordered?
– Hint: use sub query to find the productnum-s that have been ordered – so they are in
tbl_orderline table, and use those values to compare with productnum-s of tbl_product table
.
• Solution
SELECT *
FROM s9.tbl_product
WHERE productnum NOT IN
(SELECT DISTINCT productnum
FROM s9.tbl_orderline);
Exercise
• Which product is the most expensive?
– Hint: use sub query to find the MAX(msrp) in the tbl_product, and use that value to compare
with msrp of tbl_product table .
• Solution
SELECT *
FROM s9.tbl_product
WHERE msrp =
(SELECT MAX(msrp)
FROM s9.tbl_product);
Questions?
50