0% found this document useful (0 votes)
13 views63 pages

IE 171 Lecture 8 - SQL (Part 2)

The document provides an overview of Structured Query Language (SQL), covering its components such as Data Manipulation Language (DML) and Data Definition Language (DDL). It includes instructions on writing SQL commands, querying databases, and using various SQL functions like SELECT, JOIN, and aggregate functions. Additionally, it offers practical examples and exercises related to a sample DVD rental database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views63 pages

IE 171 Lecture 8 - SQL (Part 2)

The document provides an overview of Structured Query Language (SQL), covering its components such as Data Manipulation Language (DML) and Data Definition Language (DDL). It includes instructions on writing SQL commands, querying databases, and using various SQL functions like SELECT, JOIN, and aggregate functions. Additionally, it offers practical examples and exercises related to a sample DVD rental database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Structured

Query
Language (SQL)
IE 171: INFORMATION SYSTEMS 1

P RE P ARE D B Y C A S O N DAY

04/18/2023 1
Outline
► Introduction to SQL
◦ DML
◦ DDL

► Why SQL?
► Writing SQL Commands
DML and DDL
DML (data manipulation language) – Adds rows, chooses columns to
show
◦ INSERT, UPDATE, SELECT

DDL (data definition language) – Manipulates tables and attributes


◦ CREATE tables, schemas, views
◦ ALTER tables, schemas, views
◦ Link Tables Through Foreign Keys
◦ DROP or Truncate Tables
Sample
DB
DVD Rental

15 Tables
Install Sample Database
actor – stores actors data inventory – stores inventory data.
including first name and last
name. rental – stores rental data.

film – stores films data such as title, payment – stores customer’s


release year, length, rating, etc. payments.

film_actor – stores the relationships staff – stores staff data.


between films and actors. customer – stores customers data.
category – stores film’s categories address – stores address data for
data. staff and customers
film_category- stores the city – stores the city names.
relationships between films and
categories. country – stores the country
names.
store – contains the store data
including manager staff and
address.
PostgreSQL
Open pgAdmin 4
PostgreSQL
Enter password for the superuser.
PostgreSQL
On the leftmost side, click on Servers, then PostgreSQL 12.
Enter password connect to this server.
PostgreSQL
Connection is established to the database
“dvdrental” if the icon is colored.
PostgreSQL
To start querying, right click on “dvdrental”, choose
“Query Tool…”.
PostgreSQL
PostgreSQL

To see all the tables under


“dvdrental”, expand Schemas, then
expand Tables.
Writing SQL Commands
Use extended form of BNF (Backus Naur Form) notation:

- UPPER-CASE letters represent reserved words.


- LOWER-CASE letters represent user-defined words.
- | indicates a choice among alternatives. (a|b|c)
- Curly braces indicate a required element. {a}
- Square brackets indicate an optional element. [a]
- an ellipsis (…) indicates optional repetition (0 or more).

Example: {a | b} (, c…)
The SELECT Syntax
SELECT [DISTINCT | ALL]
{* | [columnExpression [AS newName]] [,...] }
FROM TableName [alias] [, ...]
[WHERE condition]
[GROUP BY columnList] [HAVING condition]
[ORDER BY columnList]

FROM Specifies table(s) to be used.


WHERE Filters rows.
GROUP BY Forms groups of rows with same
column value.
HAVING Filters groups subject to some
condition.
SELECT Specifies which columns are to
appear in output.
ORDER BY Specifies the order of the output.
Showing entire tables
Select list full details of cities data columns
Can use * as an abbreviation for ‘all columns’:

At this point, we know that SELECT * tableName; is equivalent to


TABLE tableName;
Showing specific columns
Produce a list of actors with actor’s first_name and last_name as the
only columns
Showing Unique Values
List only distinct continents to know existing continents

Use DISTINCT to eliminate duplicates


Creating Additional Columns
Produce a list of customer payments along with customer_id and the
corresponding payment multiplied by PHP50.
Filtering
List all payments with amount greater than a number
Use WHERE clause
Filtering: Multiple Conditions
List all films with more than 1 condition
Filtering 3: Ranges
List all films with length between 160 and 180 minutes only
Pattern Matching
Find all countries with the string ‘Islam’ in their Government Form
SQL has two special pattern matching symbols:
◦ %: sequence of zero or more characters;
◦ _ (underscore): any single character.
LIKE ‘%Islam%’ means a sequence of characters of any length
containing ‘Islamic Emirate’ and ‘Islamic Republic’.
Pattern Matching 2
Find all films with the string ‘nocent’ in their title, with lengths
between 160 and 180 characters
Pattern Matching Note
Percent character (%) represents any sequence of zero or more characters
(wildcard).
Underscore character represents any single character.

More details from PostgreSQL Documentation on Pattern Matching


Pattern Matching Notes
All other characters in the pattern represent themselves.
For example:
◦ address LIKE ‘H%’ means the first character must be
H, but the rest of the string can be anything.
◦ address LIKE ‘H_ _ _’ means that there must be
exactly four characters in the string, the first of which
must be an H.
◦ address LIKE ‘%e’ means any sequence of
characters, of length at least 1, with the last character
an e.
◦ address LIKE ‘%Glasgow%’ means a sequence of
characters of any length containing Glasgow.
◦ address NOT LIKE ‘H%’ means the first character
cannot be an H.
Pattern Matching
Pattern Matching
Sorting
List films based on descending ‘length’
Sorting: Multiple Conditions
List films with descending ‘length’ and ascending ‘rating’
Aggregating
ISO standard defines five aggregate functions:
◦ COUNT → returns number of values in specified column.
◦ SUM → returns sum of values in specified column.
◦ AVG → returns average of values in specified column.
◦ MIN → returns smallest value in specified column.
◦ MAX → returns largest value in specified column.
Aggregating
Each operates on a single column of a table and returns a single
value.
COUNT, MIN, and MAX apply to numeric and non-numeric fields,
but SUM and AVG may be used on numeric fields only.
Apart from COUNT(*), each function eliminates nulls first and
operates only on remaining non-null values.
Aggregating
COUNT(*) counts all rows of a table, regardless of whether nulls or
duplicate values occur.
Can use DISTINCT before column name to eliminate duplicates.
DISTINCT has no effect with MIN/MAX, but may have with
SUM/AVG.
COUNT(*)
How many films have Rating = G?
Count(DISTINCT)
How many titles have rating = G?

VS. VS.

34 PREPARED BY CASONDAY
MAX, MIN, and AVG
Find minimum, maximum, and average title lengths from table film

35 PREPARED BY CASONDAY
Grouping
Use GROUP BY clause to get sub-totals of your chosen
categories.
SELECT and GROUP BY closely integrated: each item in
SELECT list must be single-valued per group, and SELECT
clause may only contain:
◦ column names
◦ aggregate functions
◦ constants
◦ expression involving combinations of the above.

36 PREPARED BY CASONDAY
Grouping
All column names in SELECT list must appear in GROUP BY
clause unless name is used only in an aggregate function.
If WHERE is used with GROUP BY, WHERE is applied first,
then groups are formed from remaining rows satisfying
predicate.
ISO considers two nulls to be equal for purposes of GROUP
BY. (meaning, null value = null value)

37 PREPARED BY CASONDAY
Grouping
Find rating with min, max and average movie lengths for
each rating grade.

38 PREPARED BY CASONDAY
HAVING (Restricted GROUP BY)
HAVING clause is designed for use with GROUP BY to restrict
groups that appear in final result table.
Similar to WHERE, but WHERE filters individual rows whereas
HAVING filters groups.
Column names in HAVING clause must also appear in the GROUP
BY list or be contained within an aggregate function.

39 PREPARED BY CASONDAY
HAVING
Find the minimum, maximum, and average length for
Rated G films

40 PREPARED BY CASONDAY
Sub-queries
Some SQL statements can have a SELECT embedded within them.
A subselect can be used in WHERE and HAVING clauses of an outer
SELECT, where it is called a subquery or nested query.
Subselects may also appear in INSERT, UPDATE, and DELETE
statements.

41 PREPARED BY CASONDAY
WHERE based on a table
List all countries from table CITY where country is ‘Algeria’
in table COUNTRY

42 PREPARED BY CASONDAY
FROM
based on
a SELECT
How many copies of each
movie are there? Sort the
list in ascending counts of
inventory

PREPARED BY CASONDAY 43
Joining Tables
If result columns come from more than one table must
use a join.
To perform join, include more than one table in FROM
clause.

44 PREPARED BY CASONDAY
Sample
DB
DVD Rental

15 Tables
INNER JOIN
List names of all clients who have viewed a property along with any
comment supplied.

46 PREPARED BY CASONDAY
INNER JOIN
List all films with the category name ‘Horror’

We use the ON clause to


indicate that we match
the film_id from the
table film to the
film_id in the table
film_category

Same concept is applied


for category_id
We use the notation
table.tableName to
refer to a column in a
specific table to reduce
ambiguity (i.e. Multiple
tables with same column
names, film_id)

47 PREPARED BY CASONDAY
INNER JOIN
If one row of a joined table is unmatched, row is omitted from result
table.
◦ If there is no branch in the property city, it will not be shown in the joined
table
◦ If there is no property in the branch city, it will not be shown in the joined
table

48 PREPARED BY CASONDAY
LEFT JOIN
Lists all unmatched rows of data on the right table

SELECT b.*, p.*


FROM Branch1 b LEFT JOIN PropertyForRent1 p
ON b.bCity = p.pCity;

49 PREPARED BY CASONDAY
RIGHT JOIN
Lists all unmatched rows of data on the right table

SELECT b.*, p.*


FROM Branch1 b Right PropertyForRent1 p b and p are known as
ON b.bCity = p.pCity;
aliases. They are defined
in the FROM clause.

Instead of
Branch1.bCity, aliases
allow as to type b.bCity
instead to refer to the
same column
50 PREPARED BY CASONDAY
FULL OUTER JOIN
Shows all unmatched rows

SELECT b.*, p.*


FROM Branch1 b FULL OUTER JOIN PropertyForRent1 p
ON b.bCity = p.pCity;

51 PREPARED BY CASONDAY
Creating Tables
CREATE TableName [ (columnList datatype) ]
Inserting Rows
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)
columnList is optional; if omitted, SQL assumes a list of all columns in their
original CREATE TABLE order.
Any columns omitted must have been declared as NULL when table was
created, unless DEFAULT was specified when creating column
Inserting Rows
Insert new rows into basket_a and basket_b tables supplying data for
all columns.
Let’s go back to JOINs!
Let’s go back to JOINs!
Let’s go back to JOINs!
Let’s go back to JOINs!
Let’s go back to JOINs!
Let’s go back to JOINs!
Let’s go back to JOINs!
Exercise: Write the Queries for the Following
Count all the rentals that staff Jon Stephens worked on

List the number of films made by each actor.


◦ + difficulty: sort in decreasing film counts
Thank you for coming to
class! Have a nice day!

PREPARED BY CASONDAY 63

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy