Ch05-Part 1

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

Chapter 5

Relational Data
Retrieval: SQL
Fundamentals of Database Management Systems,
2nd ed by Mark L. Gillenson, Ph.D.
University of Memphis
John Wiley & Sons, Inc.
Chapter Objectives
 Describe SQL as a relational data manipulation language.

 Explain that you can create and update relational tables using SQL.

 Write SQL SELECT commands to retrieve relational data using a variety of


operators, including GROUP BY, ORDER BY, and the built-in functions of
AVG, SUM, MAX, MIN, and COUNT.
 Write SQL SELECT commands that join relational tables.

 Write SQL SELECT subqueries.

 Describe a strategy for writing SQL SELECT statements.

 Describe the principles of how a relational query optimizer works.

4-2
4-2
SQL
 Structured Query Language.
 Very heavily used in practice today.

Building the Data Structure


 Base tables - actual physical tables in which the data will be
stored on the disk.
 Created using the CREATE TABLE command.
 Deleted using the DROP TABLE command.
 Logical View - also just called a view.
 May consist of a subset of the columns of a table, a subset of the rows of
a table, or both.
 May also be the join of two or more base tables.
 A mapping onto the base table(s).
 Created using the CREATE VIEW command.
 Views are used for security purposes because they provide
encapsulation of the name of the table. Data is in the virtual table, not
stored permanently. Views display only selected data.
4-3
4-3
DDL – Data Definition Language
DQL – Data Query Language
DML – Data Manipulation Language
DCL – Data Control Language
TCL – Transaction Control Language 9-4
9-4
Data Management
 Data Definition
 Invoked with a data definition language (DDL).
 Instructs the DBMS software on what tables will be in the
database, what attributes will be in the tables, which
attributes will be indexed, etc.
 Data Manipulation
 Refers to the four basic operations that can and must be
performed on data stored in any DBMS.
1. Data retrieval
2. Data update
3. Insertion of new records
4. Deletion of existing records
 Requires data manipulation language (DML)
4-5
4-5
Data Manipulation Operations
 SELECT – used for retrieving existing data: it is DQL
 UPDATE - used for updating existing data.
 INSERT - used for inserting new rows in tables.
 DELETE - used for deleting existing rows in tables.
 LOCK – used for table control concurrency.
 MERGE - Does insert, update, and delete all in one.

 This short video to answer why we develop the concept of DB


 Database Administrator creates the database first

4-6
4-6
Introduction: SQL SELECT
 Used for data retrieval.
 You specify what data you are looking for rather than
provide a logical sequence of steps that guide the
system in how to find the data.
 Can be run in either a query or an embedded mode.
 Command will work with Oracle, MS Access, SQL
Server, DB2, Informix, MySQL, etc.

The Basic SQL SELECT

SELECT <columns>
FROM <table>
WHERE <predicates identifying rows to be included>;
4-7
4-7
SQL Query Example
“Find all customers.”
SELECT * FROM Customers;
SELECT CustomerID, CustomerName  FROM Customers;

SQL Query Example, with WHERE


“Find the customers from Mexico.”

SELECT * FROM Customers
WHERE Country='Mexico';

 The desired attributes are listed in the SELECT clause.


 The required table is listed in the FROM clause.
 The restriction (predicate) indicating which row(s) is involved is shown
in the WHERE clause in the form of an equation.
4-8
4-8
SQL Operators
SQL Arithmetic Operators
Operator Description Example
+ Add Try it
- Subtract Try it
* Multiply Try it
/ Divide Try it
% Modulo Try it
SQL Comparison Operators
Operator Description Example
= Equal to Try it
> Greater than Try it
< Less than Try it
>= Greater than or equal to Try it
<= Less than or equal to Try it
<> Not equal to Try it 4-9
4-9
SQL AND, OR and NOT Operators
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';

 With the AND operator, both conditions have to be satisfied to


be included in the result.

SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

 The OR operator really means one or the other or both.

SELECT * FROM Customers
WHERE NOT Country='Germany';

NOT Operator is used to negate a condition in the WHERE clause.


4-10
SQL Combining AND, OR and NOT
 AND is said to be “higher in precedence” than OR.
 So all ANDs are considered before any ORs are considered.
SELECT * FROM Customers If you really wanted the OR
WHERE Country='Germany' AND  to be considered first, you
could force it by adding the
(City='Berlin' OR City='München'); parenthesis.

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

4-11
SQL BETWEEN Operator
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

SELECT * FROM Products WHERE ProductName BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni';

SELECT * FROM Products WHERE ProductName NOT BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni’;
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31’;

SELECT HIREDATE FROM EMPLOYEES WHERE HIREDATE BETWEEN '11-


JUL-1981' AND '13-JUL-1987' 4-12
SQL Query Example: IN

SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef
Anton's Cajun Seasoning"
ORDER BY ProductName;

Single quotes are used to indicate the beginning and end of a string in SQL.
Double quotes generally aren't used in SQL. It depends on RDBMS.

4-13
4-13
SQL Query Example: LIKE

SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

 “%” character used as a “wildcard”‫لبدل‬AA‫ ا‬to represent any string of characters.

SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
 The single “_” character in the operator LIKE “_a%” specifies that there will be
one character followed by “a.”

SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

4-14
SQL Query Example: DISTINCT

SELECT Country FROM Customers;
SELECT DISTINCT Country FROM Customers;
SELECT COUNT(DISTINCT Country) FROM Customers;
SELECT COUNT(Country) FROM Customers;

 Eliminate duplicate rows in a query result.

4-15
SQL Query Example: ORDER BY
SELECT * FROM Customers ORDER BY Country;
SELECT * FROM Customers ORDER BY Country DESC;
By Several Columns
SELECT * FROM Customers ORDER BY Country, CustomerName;

 The default order for ORDER BY is ascending.


 The clause can include the term ASC at the end to make ascending explicit.
 The clause can include DESC for descending order.

4-16
SQL COUNT(), AVG() and SUM() Functions
SELECT COUNT(ProductID) FROM Products;

SELECT AVG(Price) FROM Products;

SELECT SUM(Quantity) FROM OrderDetails;

 They are built-in functions of SQL. 4-17


SQL MIN() and MAX() Functions
SELECT MIN(Price) FROM Products;
SELECT MAX(Price) AS LargestPrice FROM Products;

4-18
SQL Query Example: GROUP BY
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one
or more columns.

SELECT COUNT(CustomerID), Country FROM Customers


GROUP BY Country;

SELECT COUNT(CustomerID), Country FROM Customers


GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOf
Orders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
4-19
SQL Query Example: HAVING
The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.

SELECT column_name(s) SELECT COUNT(CustomerID),
FROM table_name Country
WHERE condition FROM Customers
GROUP BY column_name(s) GROUP BY Country
HAVING condition HAVING COUNT(CustomerID) > 5;
ORDER BY column_name(s);

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
4-20
SQL CREATE TABLE
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);
CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName
varchar(255),
    Address varchar(255),
    City varchar(255)
);
4-21
SQL INSERT INTO Statement
INSERT INTO table_name (column1, column2, column3,
…)VALUES (value1, value2, value3, ...);

INSERT INTO Customers (CustomerName, ContactName,


Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');

4-22
The Join

 A JOIN clause is SQL SELECT allows you to join two or more


tables, based on a related column between them.

 Two specifications must be made in the SELECT statement.


 The tables to be joined must be listed in the FROM clause.
 The join attributes must be declared and matched to each other in the WHERE
clause.

 A table name qualifier is required when different tables have an


attribute with the same name.

4-23
4-23
SQL Query Example: Join

Here are the different types of the JOINs in SQL:


•(INNER) JOIN: Returns records that have matching values in both tables
•LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
•RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
•FULL (OUTER) JOIN: combines the results and returns all (matched or
unmatched) rows from the tables on both sides of the join clause.

Let’s Practice 4-25


4-25

You might also like