Chapter 7 - Introduction To Structured Query Language (SQL)
Chapter 7 - Introduction To Structured Query Language (SQL)
1
Learning Objectives
• After completing this chapter, you will be able to:
• Retrieve specified columns of data from a database
• Join multiple tables in a single SQL query
• Restrict data retrievals to rows that match complex criteria
• Aggregate data across groups of rows
• Create subqueries to preprocess data for inclusion in other queries
• Identify and use a variety of SQL functions for string, numeric, and date
manipulation
• Explain the key principles in crafting a SELECT query
2
SQL Statement Elements
Predicates
Predicates and
and Operators
Operators Batch
Batch Separators
Separators
Functions
Functions Control
Control of
of Flow
Flow
Variables
Variables Comments
Comments
Expressions
Expressions
3
Predicates
Predicates and
and Operators
Operators
Predicates and
Elements: Operators:
IN, BETWEEN, LIKE,
Predicates ISNULL,EXISTS,DISTINCT <COLUMN1> BETWEEN 1 AND 5
<COLUMN1> LIKE “DAL%”
=, >, <, >=, <=, <>, !=, !>, !
Comparison Operators <
Arithmetic Operators +, -, *, /, %
SELECT
SELECT unitprice,
unitprice, OrderQty,
OrderQty, (unitprice
(unitprice ** OrderQty)
OrderQty) FROM
FROM sales.salesorderdetail;
sales.salesorderdetail;
SELECT
SELECT ** FROM
FROM Customers
Customers WHERE
WHERE City
City == "London"
"London" OR
OR Country
Country == "UK";
"UK";
SELECT
SELECT ** FROM
FROM Products
Products WHERE
WHERE Price
Price >=
>= 30;
30;
SELECT
SELECT ** FROM
FROM Customers
Customers WHERE
WHERE City
City IN
IN ('Paris','London');
('Paris','London');
SELECT
SELECT ** FROM
FROM Products
Products WHERE
WHERE Price
Price BETWEEN
BETWEEN 50
50 AND
AND 60;
60; 4
Comments
Comments
/*
This is a block
of
of commented
commented code
*/
• T-SQL
-- This
This line
-- Editors of
of text
linesuchtextaswill
SSMS
will be
be ignored
will typically color-code comments,
ignored
as shown above
5
Variables
Variables
6
Functions
Functions
7
Expressions
Expressions
SELECT
SELECT YEAR(OrderDate) ++ 1 ...
SELECT
SELECT OrderQty
OrderQty * UnitPrice ...
8
Batch
Batch Separators
Separators
9
Control
Control of
of Flow
Flow
• Allow you to control the flow of execution within code, handle errors,
and maintain transactions
• Used in programmatic code objects
• Stored procedures, triggers, statement blocks
• IF...ELSE •• TRY...CATCH
TRY...CATCH • BEGIN TRANSACTION
• WHILE
• COMMIT TRANSACTION
• BREAK
• ROLLBACK TRANSACTION
• CONTINUE
• BEGIN...END
10
Introduction to SQL
SQL Statements
R
o
w
s
14
Examples (3 of 6)
How can I find all person names and last names only from HR ?
SELECT FirstName,LastName FROM Person.Person ;
15
Applying the logical order of operations
to writing SELECT statements (4 of 6)
USE
USE AdventureWorks2012;
5 SELECT
SELECT SalesPersonID, YEAR(OrderDate) AS
AS OrderYear
OrderYear
1 FROM
FROM Sales.SalesOrderHeader
2 WHERE
WHERE CustomerID = 29974
3 GROUP
GROUP BY
BY SalesPersonID, YEAR(OrderDate)
YEAR(OrderDate)
4 HAVING
HAVING COUNT(*) > 11
ORDER
ORDER BY
BY SalesPersonID, OrderYear;
OrderYear;
6
1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
16
SQL Data Types
• Data type: specification about the kinds of data that can be stored
in an attribute
• Fundamental types of data
• Character data (alphabetic characters , digits ,some special charters,
strings)
• Numeric data ( numbers as digit)
• Date data ( day ,year )
17
SQL Wildcard Types
• Wildcards are symbol that can be used as a general
substitute for other characters or commands
Fundamental types
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] Matches only a character NOT specified within
or the brackets
[!charlist]
18
SELECT Statement with DISTINCT Options (5 of 6)
19
SELECT Statement with Column Aliases (6 of 6)
20
Aggregate Functions ( 1 of 2) Aggregate
Functions
•• SUM
SUM
• Takes a collection of rows and reduces it to a •• MIN
MIN
single row in whole table •• MAX
MAX
•• AVG
AVG
• Aggregate functions are most commonly •• COUNT
COUNT
used in SELECT column list to return an
aggregate values that has been calculated Table1
across a collection of row
• COUNT
SELECT function
COUNT is used
(Name) FROM to tally
Table1 ; the number
of non-null values of and attribute.
SELECT COUNT (fk) FROM Table1 ;
21
Aggregate Functions ( 2 of 2) Aggregate
Functions
• MIN and MAX finds highest and lowest numbers •• SUM
SUM
SELECT max (fk) FROM Table1 ; •• MIN
MIN
•• MAX
MAX
SELECT min (fk) FROM Table1 ; •• AVG
AVG
•• COUNT
COUNT
SELECT min (fk) ,MAX (FK) FROM Table1 ;
Table1
23
FROM Clause Options (1 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
Only some of the DBMS use this syntax ,MS-SQL prefer inner joins for Natural Joins
and don’t support Cross joins at all.
• Inner joins return only rows from the tables that match on a common value
• Outer joins return the same matched rows as the inner join, plus unmatched rows
from one table or the other
24
Example
Table1 Table2
25
FROM Clause Options (2 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
26
FROM Clause Options (3 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
The INNER JOIN only returns those rows that are
an exact match, and the LEFT OUTER JOIN
returns the rows that are an exact match, plus all
remaining unmatched rows from one LEFT table.
27
SELECT * FROM table_a INNER JOIN table_b ON table_a.id=table_b.id;
28
FROM Clause Options (6 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
Full outer join returns not only the rows
matching but it also returns all of the rows
which unmatched values from both tables
29
FROM Clause Options (10 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
JOIN ON syntax
Express a join when the tables have no common attribute names
Query returns only the rows that meet the indicated join condition
An outer join is needed to
Recursive joins: include any employee who
Recursive query: joins a table to itself is not managed by anyone
Employees M
Employees E
30
Relational Set Operators-Intersect (1 of 3)
• Can be used to combine rows from two queries, returning only the rows that appear
in both sets ( which costumers are in both table)
Fk={Null,1,2,3,5,8}
??
Attributes must have union compatible Number VarChar (30) Number Char(20)
31
Relational Set Operators -Union(2 of 3)
• Combines rows from two or more queries without including duplicate rows ( I want
to see all costumer list without duplication)
• UNION ALL
• Used to produce a relation that retains
the duplicate rows
• Used to unite more than just two queries
Fk={Null,1,2,3,5,8}
Union clause output
id={1,2,3,4,5,6,7,8}
32
Relational Set Operators –Except(Minus) (3 of 3)
• Combines rows from two queries and returns only the rows that appear in the first
set but not in the second ( which costumers are in the first table are not found in the
second table)
Fk={Null,1,2,3,5,8}
id={1,2,3,4,5,6,7,8}
Except cause output
33
Where Clause Options (1 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
[WHERE: filters the rows of data based on provided criteria]
• WHERE clause is used to add conditional restriction(s) to the SELECT statement that
limit the rows returned by the query
• Syntax:
SELECT columnlist If all rows are required for output
FROM tablelist then WHERE clause is not needed !!
[WHERE conditionlist ]
Comparison Operators =, >, <, >=, <=, <>, !=, !>, !<
Arithmetic Operators +, -, *, /, %
34
Where Clause Options (2 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]
35
Where Clause Options (3 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]
Table2
SELECT id,name FROM Table1 where fk IS NOT NULL ;
36
Where Clause Options (3 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]
Table2
37
Where Clause Options (4 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]
SELECT * FROM Table1 WHERE Name BETWEEN 'ANNE' AND
'FRED' ;
38
Where clause vs JOINs !!!
SELECT name FROM Table1 as t1 inner join Table2 as t2 on t1.fk=t2.id ;
Table1
SELECT name FROM Table1 ,Table2 where table1.fk=table2.id ;
Output
Table2
39
Other Special Operators “IN” and ‘LIKE”
41
GROUP BY Clause Options (2 of 2)
42
HAVING BY Clause Options
• A SELECT clause
SELECT column1 = (SELECT column-name FROM table-name WHERE condition),
column-names
FROM table-name WHERE condition
• A FROM clause
SELECT column-names
FROM (SELECT column-names FROM table-name1 WHERE condition)
WHERE condition
45
Subqueries (2 of 7)
Key characteristics
1. A subquery is a query (SELECT statement) inside another query
2. A subquery is normally expressed inside parentheses
3. The first query in the SQL statement is known as the outer query
4. The query inside the SQL statement is known as the inner query
5. The inner query is executed first
6. The output of an inner query is used as the input for the outer query
7. The entire SQL statement is sometimes referred to as a nested query
SELECT ProductName
1
FROM Product
WHERE Id IN (SELECT ProductId
FROM OrderItem
WHERE Quantity > 100)
46
Subqueries (3 of 7)
Subquery can return one or more values
• One single value (one column and/or one row) include NULL !
• Conditional expression in use ( >,<,=,=>,<= )
• A list of values (one column and multiple rows)
• A virtual table (multicolumn, multi-row set of values)
SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId,OrderId
FROM OrderItem
WHERE Quantity > 100)
47
Subqueries (4 of 7)
• IN subqueries –equality operator
• IN operator: used to compare a single attribute to a list of values
• IN subquery: values are not known beforehand, but can be derived
using a query Table1
• Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
SELECT * FROM Table1 WHERE fk in ( SELECT id =1
FROM Table2) ; Table2
SELECT column_name(s)
FROM table_name Table2
WHERE column_name operator ALL
(SELECT column_name FROM table_name
WHERE condition);
Any return ?
Please Read Tables 7.8 thru 7.13 SQL functions are explained with
examples we will use some of them in lab exercise 51
DML –Data Manipulation Language DML-Data
Manipulation
INSERT Language
SELECT
The insert statement is used, obviously, to add new rows to a table. INSERT
UPDATE
DELETE
INSERT INTO <table name>
VALUES (<value 1>, ... <value n>);
• Yes, you will need a separate INSERT statement for every row.
• The subquery can be nested inside a INSERT
INSERT INTO NewNrder
SELECT * FROM Orders
WHERE OldOrders in(2000,5000);
52
DML –Data Manipulation Language DML-Data
Manipulation
UPDATE Language
SELECT
INSERT
The update statement is used to change values that are already in a UPDATE
table. DELETE
UPDATE <table name> SET <attribute> = <expression>
WHERE <condition>;
54
Questions ?
55
Summary (1 of 2)
• SQL commands can be divided into two overall categories: data definition
language (DDL) commands and data manipulation language (DML) commands
• The ANSI standard data types are supported by all RDBMS vendors in different
ways
• The basic data types are NUMBER, NUMERIC, INTEGER, CHAR, VARCHAR, and DATE
• The SELECT statement is the main data retrieval command in SQL
• The column list represents one or more column names separated by commas
• Operations that join tables can be classified as inner joins and outer joins
• A natural join returns all rows with matching values in the matching columns
and eliminates duplicate columns
• Joins may use keywords such as USING and ON
• The ORDER BY clause is used to sort the output of a SELECT statement
56
Summary (2 of 2)
• The WHERE clause can be used with the SELECT, UPDATE, and DELETE
statements to restrict the rows affected by the DDL command
• Aggregate functions (COUNT, MIN, MAX, and AVG) are special
functions that perform arithmetic computations over a set of rows
• Subqueries and correlated queries are used when it is necessary to
process data based on other processed data
• Most subqueries are executed in a serial fashion
• SQL functions are used to extract or transform data
• SQL provides relational set operators to combine the output of two
queries to generate a new relation
• Crafting effective and efficient SQL queries requires a great deal of skill
57