SlideShare a Scribd company logo
1 of 83
Download to read offline
MODULE 6: SQLITE AND THE STUNES
DATABASE
SQL and Scripting Training
(C) 2020-2021 Highervista, LLC 1
2
TOPICS
Next Steps with SQLite and DBBrowser
­ Launching the DBBrowser software
­ Open the sTunes Database
­ Exploring the sTunes Database
­ The Browse Data tab
­ The Execute tab
Getting started with SQLite queries
­ Notation techniques for queries
­ SQL query basics
­ Using an alias
­ Sorting results alphabetically
­ Limiting query results
Operators in SQL
­ The WHERE clause
­ Searching for text using wildcard values
­ The DATE ( ) function
­ Using OR and AND together
­ The CASE Statement
Summary
NEXT STEPS WITH SQLITE AND
DB BROWSER
SQL and Scripting
Training
4
SQLITE CLI AND DB BROWSER GUI: WHAT
WE′LL DO
Examine an existing database to get familiar with the SELECT commands
in order to Report and View the database (sTunes database)
­ Use a browser tool—DB Browser for SQLite
­ Explore several database query and view items using DB Browser and a
preconfigured sTunes Database
After using the GUI, return to the use of the command line CLI to
­ Create a database in SQLite CLI
­ Create a new database, create and load several tables, and enter code into the
CLI.
­ Briefly discuss how to use Python with SQLite
LAUNCHING THE DB BROWSER
SOFTWARE
SQL and Scripting
Training
6
MOVE THE STUNES DATABASE
Move the sTunes database to a location on your computer where
you can easily locate it.
The sTunes database is available in the SQL course resources.
7
FROM A BROWSER, LAUNCH THE DB
BROWSER
OPEN THE STUNES DATABASE
SQL and Scripting
Training
9
WITH THE DB BROWSER OPEN, CLICK OPEN
DATABASE
10
FROM THE DIALOG BOX, SELECT THE STUNES
DB
EXPLORING THE STUNES
DATABASE
SQL and Scripting
Training
12
STUNES EXAMPLE DATABASE
Located in student resources (place in a folder like SQL Class)
Open DB Browser for SQLite
13
OPEN STUNES DATABASE
14
STUNES: 13 TABLES
15
STUNES DATABASE—INTENTION
Intention and scope:
­ Online retail music sales data
­ Contains product information (songs and albums), personal customer
information, employee records, and sales data.
Tasks will be to analyze the database and discover insights about
the data using SQL commands.
Explore the sTunes Database
16
USING THE STUNES DATABASE
Think in terms of natural language questions. Example:
­ Instead of
­ How many entries are in the customer table?
­ Think
­ How many customers do we have?
17
EXAMINE THE DATABASE STRUCTURE
WINDOW
13 tables
Fields: Expand the arrow to the left of the
table names.
18
TABLES (13) AND FIELDS IN THE ALBUMS TABLE
What are the data types?
What is a database record?
THE BROWSE DATA TAB AWS SQL and Scripting Training
20
VIEWING INDIVIDUAL RECORDS
Browse Data tab can be used to see
the records contained in each table.
Example: Albums table
In row 1:
o AlbumID = 1
o Title = For Those About to Rock We
Salute You
o ArtistId = 1
Note: ArtistId is a FK
THE EXECUTE TAB SQL and Scripting
Training
22
EXECUTE SQL TAB
The Execute SQL Tab is where you write your SQL statements
(instead of writing SQL in a CLI, you are writing SQL in a window
or GUI)
Three main window components:
­ Query pane
­ Results pane
­ Messages pane
23
EXECUTE SQL TAB
SQL code entered:
SELECT
*
FROM
albums;
24
EXECUTE SQL TAB Results (below) include:
­ Number of rows returned
­ How much time the query
took to run
­ Error messages?
Entry screen below:
SQLITE QUERIES: GETTING
STARTED
SQL and Scripting
Training
26
NOTATION TECHNIQUES FOR QUERIES:
COMMENTS
Comments are not processed by the SQL
engine.
Helps and provides insight into the SQL
(especially important in maintenance)
Industry best practice
Comments: -- for a line comment or /*
*/ for a comment ‘block’
27
GENERAL SQL SYNTAX
SELECT id from foods where name=’JujyFruit’
| ___________ =================
|. | |
| | |
| | predicate
| subject
verb
28
EXAMPLE SQL QUERY (COMMANDS)
select burger
from kitchen
where patties=2
and toppings=‘jalopenos’
and condiment != ‘mayo’
limit 1;
29
REVIEW: TYPES OF QUERIES
DDL (Data Definition Language): Used to create tables
create [temp] table table_name (column_definitions [,
constraints]);
DML (Data Manipulation Language): Used to insert data, modify, data
and/or update data in a database
select …
30
THE STRUCTURE OF A BASIC QUERY
A query is like asking a question in a natural
language.
The order of words matters.
1.What database?
2.What table(s) within a database are we requesting information
from?
3.What fields are we interested in?
4.What do we want to exclude, filter, or omit? (a range of time, for
example)
5.In one concise sentence, what does the query do?
Questions when writing a query:
31
WRITING THE QUERY
Write directly into the Query pane or ...
Write in a text editor (now a word processor) to save it.
32
WRITING THE QUERY
Open the Query pane.
Identify who wrote it, a date,
and a description.
33
THE STRUCTURE OF A BASIC QUERY
/*
Created by: Ron McFarland
Created on: October 5, 2020
Description: This query selects the first name, last name, and email from the
Customers table on the sTunes database.
*/
SELECT
FirstName,
LastName,
Email
FROM
customers;
34
RESULTS
Messages Pane: 59 rows
in 3 milliseconds
Note: Writing SQL in a
consistent way is known
as coding standards.
35
CODING SYNTAX VS. CODING
CONVENTION
All queries must conform with SQL syntax in order to be understood by the
SQL engine.
Coding convention varies based on the database environment.
Some conventions:
­ The * (asterisk) in the SELECT * means ″all.″ Some engines allow SELECT ALL (use * in SQLite).
­ The ; (semi-colon) at the end of a single line in SQLite is optional for some database engines.
­ When selecting fields in the SELECT clause, use a comma ( , ) between field names (except
the last one):
­ SELECT name, address, phone_number from xxx;
­ Use this notation in SQLite, yet other engines may not require the comma (,).
36
CODING SYNTAX VS. CODING
CONVENTION
SQLite uses the SQL-92 standard, core to modern
RDBMS tools.
Some RDBMS tools go beyond SQL-92 standards.
SQL-92 is a major subset of several RDBMS products.
SQL-92 standard
Other RDBMS tools
(probable) extensions
37
ALIAS
An alias allows you to provide an alternate name to a
display/report.
For example, an alias may be used if the table field name does
not reflect the field name the user would like to see on a report
or screen.
38
ALIAS/*
Created by: Ron McFarland
Created on: 10/5/2020
Description: This query selects the first name, last name, email, and
phone number fields from the customers table and shows 4 different
ways to report/display the field information.
*/
SELECT
FirstName AS ‘First Name’,
LastName AS [Last Name],
Email AS EMAIL,
Phone CELL
FROM
customers;
Note: For most RDBMS tools, the
alias notation will work fine.
However, if you get an error on an
alias using another RDBMS tool,
double check the documentation
pertaining to alias.
39
FIELD NAMES WITH/WITHOUT ALIAS
Without Alias With Alias
40
SORTING: USING THE ORDER BY
Scenario: In the sTunes database, the customer service department may want a list of
customers sorted by customer last name.
The ORDER BY clause provides the option to sort based on the fields chosen.
The default sort order in the ORDER BY clause is in descending order. You could add
the DESC keyword if desired.
To sort in ascending order, use the ASC keyword with the ORDER BY clause.
41
ORDER BY. ASC RESULTS
Note: Without the ORDER BY
clause, every query will return
data in the order that it was
initially saved in the table (FIFO).
SELECT
FirstName AS 'First Name',
LastName AS [Last Name],
Email AS EMAIL
FROM
customers
ORDER BY
LastName ASC
42
SORTING ON MULTIPLE FIELDS
You can sort on multiple fields to create output that meets the user′s
requirements.
Sorting is in order of the field names.
Both ASC and DESC can be used in a sort.
43
ORDER BY WITH MULTIPLE FIELDS (ASC AND
DESC KEYWORDS)
Note: If you use the ORDER BY
statement on a column where
some of the corresponding rows
have empty values, these values
will show as NULL at the top if
you are using ASC order.
44
LIMITING QUERY RESULTS: LIMIT KEYWORD
You can limit results to a specified number of rows using the LIMIT
keyword.
The LIMIT keyword is useful in testing scenarios or, for example, when
you are creating a query to look for the top values (e.g., highest sales).
45
LIMIT—CHECK YOUR
MESSAGES
46
COMPARISON, LOGICAL, AND
ARITHMETIC OPERATORS IN SQL
• Operators are special keywords used
with SQL clauses to compare the
values of fields, select subsets of
fields, or perform operators.
• Operators cannot exist as their own
SQL clause. They must be used with
other clauses like SELECT and
WHERE.
• These different types of operators can
be combined to make more complex
queries.
47
ARITHMETIC OPERATORS USED WITH A
SELECT CLAUSE
SELECT
Total AS [Original Amount],
Total + 10 AS [Addition Operator],
Total – 10 AS [Subtraction Operator],
Total / 10 AS [Division Operator],
Total * 10 AS [Multiplication Operator],
Total % 10 AS [Modulus Operator]
FROM
invoices
ORDER BY
Total DESC
48
FILTERING RECORDS BY NUMBERS WITHIN
THE WHERE CLAUSE
The WHERE operator clause will be encountered often.
WHERE limits the results of queries so that only data
satisfying the query is displayed.
1.Numbers
2.Text
3.Dates
Common types of data that can be filtered:
49
USING THE WHERE CLAUSE
On sTunes, how many customers
purchased just two $.0.99
songs? One way to find out is
by looking in the invoices table
for amounts of $1.98, which
would probably represent two
songs.
50
WHERE CLAUSE
Note: The WHERE Clause always
comes after FROM but before
ORDER BY.
51
LOGICAL OPERATORS
Logical operators can help you
write more complex and
specific queries.
For example, if you were
asked to find out how many
invoices existed within a range,
such as $1.98 to $5.00.
52
LOGICAL OPERATORS
Note: Using comparison operators, you could
write:
Total >= 1.98 AND Total <= 5.00
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
Total BETWEEN 1.98 AND 5.00
ORDER BY
InvoiceDate
53
THE IN OPERATOR
IN is used to find a list of
precise values.
Note: BETWEEN is a range,
while IN is specific.
54
THE IN OPERATOR
Note: With the = operator, we can find only one
value.
With the IN operator, we can add as many values,
separated by commas, as we need.
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
Total IN (1.98, 3.96)
ORDER BY
InvoiceDate
55
FILTERING RECORDS BY TEXT
You can search for a specific text string
using the WHERE clause and looking for
a specific value of a field.
The values specified must be surrounded
by single quotes for text fields.
56
RESULTS—ONLY TUCSON SHOWS
57
FILTERING RECORDS BY TEXT: USING THE
IN CLAUSE
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
BillingCity IN ('Tucson', 'Paris', 'London')
ORDER BY
InvoiceDate
58
SEARCHING FOR STRINGS: USING LIKE
TO SEARCH FOR WILDCARDS
Previously, we used the = operator to search for the exact text.
LIKE is useful when you are not sure how a text value is spelled in the
database.
LIKE operators can use wildcards to indicate variability for a given text
item.
The wildcard character is %.
For example: LIKE ′T%; will return any cities that start with T
59
LIKE EXAMPLE
USING A WILDCARD
60
LIKE
EXAMPLE
USING A
WILDCARD
(LIKE T
ANYWHERE)
61
LIKE EXAMPLE: WILDCARD USAGE
62
DATE( ) FUNCTION: FILTERING RECORDS
EXAMPLE
Note: Look at the format of the date. Keep in mind
that the comparison format (the item to the right) must
be the same format as the field (left side).
You may need to look at the data dictionary or the
field description to verify the field format.
Dates are enclosed in single quotes, just as text fields
are.
63
USING THE DATE( ) FUNCTION
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
DATE (InvoiceDate) = ‘2009-01-03’
ORDER BY
Total
Note: The result is identical to the
previous DATE query. However, it can be
more precise by feeding the comparison
value (on the right-hand side) into the
query as a parameter.
64
USING THE AND OPERATORS WITH TWO
SEPARATE FIELDSSELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
DATE (InvoiceDate) > ‘2010-01-02’ AND
Total < 3
ORDER BY
Total
Note: AND means both conditions must be true.
You can add more AND operators. You are
not limited to two values.
65
USING THE OR OPERATORS WITH TWO
SEPARATE FIELDSSELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
WHERE
BillingCity LIKE ‘p%’ OR BillingCity LIKE
‘d%’
ORDER BY
Total
Note: OR means only one condition must be true.
66
USING PARENTHESES WITH AND/OR TO
SPECIFY THE ORDER OF OPERATIONS
Note: As written, SQL processes the two conditions on either side of the
AND condition first (Total > 1.98 AND City begins with a P). Then the
OR condition is applied (City begins with a D). Results are returned for
BOTH conditions on both sides of the OR in ascending order. This may
not be the result you want!
67
USING PARENTHESES WITH AND/OR TO
SPECIFY THE ORDER OF OPERATIONS
Again, SQL processes the AND operator first (like
multiplication) and the OR operator next (like
addition), unless you use parentheses.
Without parenthesis, the AND will be processed in
the same way that 3*2+1 = 7. But with
parenthesis, 3*(2+1) = 9.
68
USING PARENTHESES WITH AND/OR TO
SPECIFY THE ORDER OF OPERATIONS
Note: The results shows invoices > than $1.98 from both cities that
start with a P or a D.
A best practice is to use parenthesis to clearly identify how you want
the query to execute.
69
THE CASE STATEMENT
The CASE statement allows you to create a new, temporary field in your database
that serves as a label for your data, based on unique user-specified conditions.
For example:
­ The sTunes sales team would like sTunes customers to spend $7 to $15 in the online store. They
have created categories: Baseline Purchase, Low Purchase, Target Purchase, and Top Performer.
­ Since the cost of a song varies from $0.99 to $1.99
­ Any invoice in this range is a Baseline Purchase.
­ $2.00 to $6.99 is a Low Purchase.
­ $7.00 to $15.00 is a Target Purchase.
­ Above $15.00 is a Top Performer.
70
THE CASE STATEMENT
The CASE statement is used to create a new field in the invoices table.
Let’s call the new field PurchaseType. This new field will appear
alongside the other pre-existing fields in our query, as if it were another
field in the database.
71
CODING THE CASE STATEMENT: STEP 1
Start with a SELECT statement with
the pre-existing database fields of
interest from the invoices table.
For this example, let’s use sales
totals by city.
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total
FROM
invoices
ORDER BY
BillingCity
72
CODING THE CASE STATEMENT: STEP 2
To add the CASE statement to the query,
place it at the bottom of the SELECT portion
of the query after the existing fields.
Start by adding the keyword CASE followed
by the END keyword.
Each test begins with the keyword WHEN.
The ELSE keyword is the last explicit
condition listed (ELSE is optional and if not
used, fields not identified by the WHEN are
ignored).
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total,
CASE
…
END
FROM
invoices
ORDER BY
BillingCity
73
CODING THE CASE STATEMENT: STEP 3
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total,
CASE
WHEN TOTAL < 2.00 THEN ‘Baseline Purchase’
WHEN TOTAL BETWEEN 2.00 AND 6.99 THEN ‘Low Purchase’
WHEN TOTAL BETWEEN 7.00 AND 15.00 THEN ‘Target
Purchase’
ELSE ‘Top Performers’
END AS PurchaseType
FROM
invoices
ORDER BY
BillingCity
74
CASE STATEMENT APPLIED TO THE
STUNES DB
Note: Use the ORDER BY
to order results, perhaps in
the new PurchaseType
field.
75
USING THE NEW FIELD: PURCHASETYPE
Additional questions using PurchaseType:
­ What cities do the top-performing sales come from?
­ Are the top-performing sales mainly from the US or are they from other
parts of the world?
­ From what cities are the most baseline purchase made?
­ And others …
76
SELECT
InvoiceDate,
BillingAddress,
BillingCity,
Total,
CASE
WHEN TOTAL < 2.00 THEN ‘Baseline Purchase’
WHEN TOTAL BETWEEN 2.00 AND 6.99 THEN ‘Low
Purchase’
WHEN TOTAL BETWEEN 7.00 AND 15.00 THEN ‘Target
Purchase’
ELSE ‘Top Performers’
END AS PurchaseType
FROM
invoices
WHERE PurchaseType = ’Top Performers’
ORDER BY
BillingCity
USING THE NEW FIELD:
PURCHASETYPE = ′TOP
PERFORMERS′
77
RESULTS: PURCHASETYPE = ′TOP
PERFORMERS′
78
SUMMARY
Adding comments to queries is considered a best practice.
When composing a query, it is useful to phrase what you want from the query in a natural language first, then
decide what keywords you need.
The basic query usually begins with a SELECT clause that specifies what fields to display from the table using
the FROM clause. (e.g., SELECT … FROM …).
An alias used after the AS keyword can rename the field names in your query results. The ALIAS does not
affect the data in the database nor does it modify the field metadata.
The ORDER BY clause allows you to sort alphabetically either in ASC (ascending) or DESC (descending) order.
The LIMIT keyword, which is used after the ORDER BY clause, will limit the number of records in the query
results (you must include the number of results you wish to show).
79
SUMMARY
Operators are special SQL keywords that are used with SQL clauses to filter data by specific
conditions.
Using the WHERE clause with a combination of different operators can enable the user to search
records for specific text, dates, and numbers.
The Date ( ) function allows us to exclude the timecode when specifying our date criteria.
The order of operations when using logical operators (such as AND/OR) can be controlled by
parentheses ( ).
The CASE statement allows you to label records with a special field name based on user-specified
logical conditions.
80
REFERENCES
Allen, G., & Owens, M. (2010). The definitive guide to SQLite.
Draw.io. (2020). Diagrams.net. Free flowchart maker and diagrams online. Retrieved
November 23, 2020, from https://app.diagrams.net/
Shields, W. (2019). Sql quickstart guide: the simplified beginner's guide to
managing, analyzing, and manipulating data with Sql. Clydebank Media.
SQLite Browser. (2020, November 09). DB Browser for SQLite. Retrieved November 23, 2020,
from https://sqlitebrowser.org/
SQLite. (2020). SQLite Main Website. Retrieved November 23, 2020, from
https://sqlite.org/index.html
Tutorialspoint. (2020). SQLite Tutorial. Retrieved November 23, 2020, from
https://www.tutorialspoint.com/sqlite/index.htm
81
INTRODUCTION
Ron McFarland
Technologist, Educator
Source: Microsoft Images
82
ABOUT THIS COURSE
This course is distributed free. I use several
sources. But importantly, I use the book noted
on the next slide.
If you are using these PowerPoints, please
attribute Highervista, LLC and me (Ron
McFarland). IN ADDITION, please attribute
the author noted on the next slide, as the
author’s textbook provides essential
information for this course.
Source: Microsoft Images
83
INTRODUCTION
This course is offered to you free. HOWEVER, please
purchase the following book, as it is a primary resource for
this course. I do not make any $ from this course or this
book. So, since a handful of good content is derived from the
following text, please support this author!
Title: SQL Quickstart Guide
Author: Walter Shields
Available: Amazon, B&N, and through ClydeBank media
website at:
https://www.clydebankmedia.com/books/programming-
tech/sql-quickstart-guide

More Related Content

What's hot (20)

Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Internet Environment
Internet  EnvironmentInternet  Environment
Internet Environment
 
Create table
Create tableCreate table
Create table
 
Sql 2009
Sql 2009Sql 2009
Sql 2009
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Fg d
Fg dFg d
Fg d
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
Intro to T-SQL - 1st session
Intro to T-SQL - 1st sessionIntro to T-SQL - 1st session
Intro to T-SQL - 1st session
 
PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)PBDJ 19-4(woolley rev)
PBDJ 19-4(woolley rev)
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
SQL
SQLSQL
SQL
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
lovely
lovelylovely
lovely
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
 

Similar to Sq lite module6

MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresSteven Johnson
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for BeginnersProduct School
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimizationUsman Tariq
 
What Your Database Query is Really Doing
What Your Database Query is Really DoingWhat Your Database Query is Really Doing
What Your Database Query is Really DoingDave Stokes
 
SQL Server Admin Best Practices with DMV's
SQL Server Admin Best Practices with DMV'sSQL Server Admin Best Practices with DMV's
SQL Server Admin Best Practices with DMV'sSparkhound Inc.
 
Unit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptxUnit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptxPetroJoe
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptxKareemBullard1
 

Similar to Sq lite module6 (20)

Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
Oracle notes
Oracle notesOracle notes
Oracle notes
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
7. SQL.pptx
7. SQL.pptx7. SQL.pptx
7. SQL.pptx
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Lab
LabLab
Lab
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for Beginners
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimization
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
What Your Database Query is Really Doing
What Your Database Query is Really DoingWhat Your Database Query is Really Doing
What Your Database Query is Really Doing
 
SQL Server Admin Best Practices with DMV's
SQL Server Admin Best Practices with DMV'sSQL Server Admin Best Practices with DMV's
SQL Server Admin Best Practices with DMV's
 
Unit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptxUnit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptx
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 

More from Highervista

Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Highervista
 
Cyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandCyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandHighervista
 
Intro infosec version 2
Intro infosec version 2Intro infosec version 2
Intro infosec version 2Highervista
 
How to create a maker space v2 ebook
How to create a maker space v2 ebookHow to create a maker space v2 ebook
How to create a maker space v2 ebookHighervista
 
Love and silence v3 scribd slide share
Love and silence v3 scribd slide shareLove and silence v3 scribd slide share
Love and silence v3 scribd slide shareHighervista
 

More from Highervista (6)

Sq lite module3
Sq lite module3Sq lite module3
Sq lite module3
 
Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018Cyber security training using virtual labs 3 cs umuc presentation august 2018
Cyber security training using virtual labs 3 cs umuc presentation august 2018
 
Cyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarlandCyber security for manufacturers umuc cadf-ron mcfarland
Cyber security for manufacturers umuc cadf-ron mcfarland
 
Intro infosec version 2
Intro infosec version 2Intro infosec version 2
Intro infosec version 2
 
How to create a maker space v2 ebook
How to create a maker space v2 ebookHow to create a maker space v2 ebook
How to create a maker space v2 ebook
 
Love and silence v3 scribd slide share
Love and silence v3 scribd slide shareLove and silence v3 scribd slide share
Love and silence v3 scribd slide share
 

Recently uploaded

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

Sq lite module6

  • 1. MODULE 6: SQLITE AND THE STUNES DATABASE SQL and Scripting Training (C) 2020-2021 Highervista, LLC 1
  • 2. 2 TOPICS Next Steps with SQLite and DBBrowser ­ Launching the DBBrowser software ­ Open the sTunes Database ­ Exploring the sTunes Database ­ The Browse Data tab ­ The Execute tab Getting started with SQLite queries ­ Notation techniques for queries ­ SQL query basics ­ Using an alias ­ Sorting results alphabetically ­ Limiting query results Operators in SQL ­ The WHERE clause ­ Searching for text using wildcard values ­ The DATE ( ) function ­ Using OR and AND together ­ The CASE Statement Summary
  • 3. NEXT STEPS WITH SQLITE AND DB BROWSER SQL and Scripting Training
  • 4. 4 SQLITE CLI AND DB BROWSER GUI: WHAT WE′LL DO Examine an existing database to get familiar with the SELECT commands in order to Report and View the database (sTunes database) ­ Use a browser tool—DB Browser for SQLite ­ Explore several database query and view items using DB Browser and a preconfigured sTunes Database After using the GUI, return to the use of the command line CLI to ­ Create a database in SQLite CLI ­ Create a new database, create and load several tables, and enter code into the CLI. ­ Briefly discuss how to use Python with SQLite
  • 5. LAUNCHING THE DB BROWSER SOFTWARE SQL and Scripting Training
  • 6. 6 MOVE THE STUNES DATABASE Move the sTunes database to a location on your computer where you can easily locate it. The sTunes database is available in the SQL course resources.
  • 7. 7 FROM A BROWSER, LAUNCH THE DB BROWSER
  • 8. OPEN THE STUNES DATABASE SQL and Scripting Training
  • 9. 9 WITH THE DB BROWSER OPEN, CLICK OPEN DATABASE
  • 10. 10 FROM THE DIALOG BOX, SELECT THE STUNES DB
  • 11. EXPLORING THE STUNES DATABASE SQL and Scripting Training
  • 12. 12 STUNES EXAMPLE DATABASE Located in student resources (place in a folder like SQL Class) Open DB Browser for SQLite
  • 15. 15 STUNES DATABASE—INTENTION Intention and scope: ­ Online retail music sales data ­ Contains product information (songs and albums), personal customer information, employee records, and sales data. Tasks will be to analyze the database and discover insights about the data using SQL commands. Explore the sTunes Database
  • 16. 16 USING THE STUNES DATABASE Think in terms of natural language questions. Example: ­ Instead of ­ How many entries are in the customer table? ­ Think ­ How many customers do we have?
  • 17. 17 EXAMINE THE DATABASE STRUCTURE WINDOW 13 tables Fields: Expand the arrow to the left of the table names.
  • 18. 18 TABLES (13) AND FIELDS IN THE ALBUMS TABLE What are the data types? What is a database record?
  • 19. THE BROWSE DATA TAB AWS SQL and Scripting Training
  • 20. 20 VIEWING INDIVIDUAL RECORDS Browse Data tab can be used to see the records contained in each table. Example: Albums table In row 1: o AlbumID = 1 o Title = For Those About to Rock We Salute You o ArtistId = 1 Note: ArtistId is a FK
  • 21. THE EXECUTE TAB SQL and Scripting Training
  • 22. 22 EXECUTE SQL TAB The Execute SQL Tab is where you write your SQL statements (instead of writing SQL in a CLI, you are writing SQL in a window or GUI) Three main window components: ­ Query pane ­ Results pane ­ Messages pane
  • 23. 23 EXECUTE SQL TAB SQL code entered: SELECT * FROM albums;
  • 24. 24 EXECUTE SQL TAB Results (below) include: ­ Number of rows returned ­ How much time the query took to run ­ Error messages? Entry screen below:
  • 25. SQLITE QUERIES: GETTING STARTED SQL and Scripting Training
  • 26. 26 NOTATION TECHNIQUES FOR QUERIES: COMMENTS Comments are not processed by the SQL engine. Helps and provides insight into the SQL (especially important in maintenance) Industry best practice Comments: -- for a line comment or /* */ for a comment ‘block’
  • 27. 27 GENERAL SQL SYNTAX SELECT id from foods where name=’JujyFruit’ | ___________ ================= |. | | | | | | | predicate | subject verb
  • 28. 28 EXAMPLE SQL QUERY (COMMANDS) select burger from kitchen where patties=2 and toppings=‘jalopenos’ and condiment != ‘mayo’ limit 1;
  • 29. 29 REVIEW: TYPES OF QUERIES DDL (Data Definition Language): Used to create tables create [temp] table table_name (column_definitions [, constraints]); DML (Data Manipulation Language): Used to insert data, modify, data and/or update data in a database select …
  • 30. 30 THE STRUCTURE OF A BASIC QUERY A query is like asking a question in a natural language. The order of words matters. 1.What database? 2.What table(s) within a database are we requesting information from? 3.What fields are we interested in? 4.What do we want to exclude, filter, or omit? (a range of time, for example) 5.In one concise sentence, what does the query do? Questions when writing a query:
  • 31. 31 WRITING THE QUERY Write directly into the Query pane or ... Write in a text editor (now a word processor) to save it.
  • 32. 32 WRITING THE QUERY Open the Query pane. Identify who wrote it, a date, and a description.
  • 33. 33 THE STRUCTURE OF A BASIC QUERY /* Created by: Ron McFarland Created on: October 5, 2020 Description: This query selects the first name, last name, and email from the Customers table on the sTunes database. */ SELECT FirstName, LastName, Email FROM customers;
  • 34. 34 RESULTS Messages Pane: 59 rows in 3 milliseconds Note: Writing SQL in a consistent way is known as coding standards.
  • 35. 35 CODING SYNTAX VS. CODING CONVENTION All queries must conform with SQL syntax in order to be understood by the SQL engine. Coding convention varies based on the database environment. Some conventions: ­ The * (asterisk) in the SELECT * means ″all.″ Some engines allow SELECT ALL (use * in SQLite). ­ The ; (semi-colon) at the end of a single line in SQLite is optional for some database engines. ­ When selecting fields in the SELECT clause, use a comma ( , ) between field names (except the last one): ­ SELECT name, address, phone_number from xxx; ­ Use this notation in SQLite, yet other engines may not require the comma (,).
  • 36. 36 CODING SYNTAX VS. CODING CONVENTION SQLite uses the SQL-92 standard, core to modern RDBMS tools. Some RDBMS tools go beyond SQL-92 standards. SQL-92 is a major subset of several RDBMS products. SQL-92 standard Other RDBMS tools (probable) extensions
  • 37. 37 ALIAS An alias allows you to provide an alternate name to a display/report. For example, an alias may be used if the table field name does not reflect the field name the user would like to see on a report or screen.
  • 38. 38 ALIAS/* Created by: Ron McFarland Created on: 10/5/2020 Description: This query selects the first name, last name, email, and phone number fields from the customers table and shows 4 different ways to report/display the field information. */ SELECT FirstName AS ‘First Name’, LastName AS [Last Name], Email AS EMAIL, Phone CELL FROM customers; Note: For most RDBMS tools, the alias notation will work fine. However, if you get an error on an alias using another RDBMS tool, double check the documentation pertaining to alias.
  • 39. 39 FIELD NAMES WITH/WITHOUT ALIAS Without Alias With Alias
  • 40. 40 SORTING: USING THE ORDER BY Scenario: In the sTunes database, the customer service department may want a list of customers sorted by customer last name. The ORDER BY clause provides the option to sort based on the fields chosen. The default sort order in the ORDER BY clause is in descending order. You could add the DESC keyword if desired. To sort in ascending order, use the ASC keyword with the ORDER BY clause.
  • 41. 41 ORDER BY. ASC RESULTS Note: Without the ORDER BY clause, every query will return data in the order that it was initially saved in the table (FIFO). SELECT FirstName AS 'First Name', LastName AS [Last Name], Email AS EMAIL FROM customers ORDER BY LastName ASC
  • 42. 42 SORTING ON MULTIPLE FIELDS You can sort on multiple fields to create output that meets the user′s requirements. Sorting is in order of the field names. Both ASC and DESC can be used in a sort.
  • 43. 43 ORDER BY WITH MULTIPLE FIELDS (ASC AND DESC KEYWORDS) Note: If you use the ORDER BY statement on a column where some of the corresponding rows have empty values, these values will show as NULL at the top if you are using ASC order.
  • 44. 44 LIMITING QUERY RESULTS: LIMIT KEYWORD You can limit results to a specified number of rows using the LIMIT keyword. The LIMIT keyword is useful in testing scenarios or, for example, when you are creating a query to look for the top values (e.g., highest sales).
  • 46. 46 COMPARISON, LOGICAL, AND ARITHMETIC OPERATORS IN SQL • Operators are special keywords used with SQL clauses to compare the values of fields, select subsets of fields, or perform operators. • Operators cannot exist as their own SQL clause. They must be used with other clauses like SELECT and WHERE. • These different types of operators can be combined to make more complex queries.
  • 47. 47 ARITHMETIC OPERATORS USED WITH A SELECT CLAUSE SELECT Total AS [Original Amount], Total + 10 AS [Addition Operator], Total – 10 AS [Subtraction Operator], Total / 10 AS [Division Operator], Total * 10 AS [Multiplication Operator], Total % 10 AS [Modulus Operator] FROM invoices ORDER BY Total DESC
  • 48. 48 FILTERING RECORDS BY NUMBERS WITHIN THE WHERE CLAUSE The WHERE operator clause will be encountered often. WHERE limits the results of queries so that only data satisfying the query is displayed. 1.Numbers 2.Text 3.Dates Common types of data that can be filtered:
  • 49. 49 USING THE WHERE CLAUSE On sTunes, how many customers purchased just two $.0.99 songs? One way to find out is by looking in the invoices table for amounts of $1.98, which would probably represent two songs.
  • 50. 50 WHERE CLAUSE Note: The WHERE Clause always comes after FROM but before ORDER BY.
  • 51. 51 LOGICAL OPERATORS Logical operators can help you write more complex and specific queries. For example, if you were asked to find out how many invoices existed within a range, such as $1.98 to $5.00.
  • 52. 52 LOGICAL OPERATORS Note: Using comparison operators, you could write: Total >= 1.98 AND Total <= 5.00 SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE Total BETWEEN 1.98 AND 5.00 ORDER BY InvoiceDate
  • 53. 53 THE IN OPERATOR IN is used to find a list of precise values. Note: BETWEEN is a range, while IN is specific.
  • 54. 54 THE IN OPERATOR Note: With the = operator, we can find only one value. With the IN operator, we can add as many values, separated by commas, as we need. SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE Total IN (1.98, 3.96) ORDER BY InvoiceDate
  • 55. 55 FILTERING RECORDS BY TEXT You can search for a specific text string using the WHERE clause and looking for a specific value of a field. The values specified must be surrounded by single quotes for text fields.
  • 57. 57 FILTERING RECORDS BY TEXT: USING THE IN CLAUSE SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE BillingCity IN ('Tucson', 'Paris', 'London') ORDER BY InvoiceDate
  • 58. 58 SEARCHING FOR STRINGS: USING LIKE TO SEARCH FOR WILDCARDS Previously, we used the = operator to search for the exact text. LIKE is useful when you are not sure how a text value is spelled in the database. LIKE operators can use wildcards to indicate variability for a given text item. The wildcard character is %. For example: LIKE ′T%; will return any cities that start with T
  • 62. 62 DATE( ) FUNCTION: FILTERING RECORDS EXAMPLE Note: Look at the format of the date. Keep in mind that the comparison format (the item to the right) must be the same format as the field (left side). You may need to look at the data dictionary or the field description to verify the field format. Dates are enclosed in single quotes, just as text fields are.
  • 63. 63 USING THE DATE( ) FUNCTION SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE DATE (InvoiceDate) = ‘2009-01-03’ ORDER BY Total Note: The result is identical to the previous DATE query. However, it can be more precise by feeding the comparison value (on the right-hand side) into the query as a parameter.
  • 64. 64 USING THE AND OPERATORS WITH TWO SEPARATE FIELDSSELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE DATE (InvoiceDate) > ‘2010-01-02’ AND Total < 3 ORDER BY Total Note: AND means both conditions must be true. You can add more AND operators. You are not limited to two values.
  • 65. 65 USING THE OR OPERATORS WITH TWO SEPARATE FIELDSSELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices WHERE BillingCity LIKE ‘p%’ OR BillingCity LIKE ‘d%’ ORDER BY Total Note: OR means only one condition must be true.
  • 66. 66 USING PARENTHESES WITH AND/OR TO SPECIFY THE ORDER OF OPERATIONS Note: As written, SQL processes the two conditions on either side of the AND condition first (Total > 1.98 AND City begins with a P). Then the OR condition is applied (City begins with a D). Results are returned for BOTH conditions on both sides of the OR in ascending order. This may not be the result you want!
  • 67. 67 USING PARENTHESES WITH AND/OR TO SPECIFY THE ORDER OF OPERATIONS Again, SQL processes the AND operator first (like multiplication) and the OR operator next (like addition), unless you use parentheses. Without parenthesis, the AND will be processed in the same way that 3*2+1 = 7. But with parenthesis, 3*(2+1) = 9.
  • 68. 68 USING PARENTHESES WITH AND/OR TO SPECIFY THE ORDER OF OPERATIONS Note: The results shows invoices > than $1.98 from both cities that start with a P or a D. A best practice is to use parenthesis to clearly identify how you want the query to execute.
  • 69. 69 THE CASE STATEMENT The CASE statement allows you to create a new, temporary field in your database that serves as a label for your data, based on unique user-specified conditions. For example: ­ The sTunes sales team would like sTunes customers to spend $7 to $15 in the online store. They have created categories: Baseline Purchase, Low Purchase, Target Purchase, and Top Performer. ­ Since the cost of a song varies from $0.99 to $1.99 ­ Any invoice in this range is a Baseline Purchase. ­ $2.00 to $6.99 is a Low Purchase. ­ $7.00 to $15.00 is a Target Purchase. ­ Above $15.00 is a Top Performer.
  • 70. 70 THE CASE STATEMENT The CASE statement is used to create a new field in the invoices table. Let’s call the new field PurchaseType. This new field will appear alongside the other pre-existing fields in our query, as if it were another field in the database.
  • 71. 71 CODING THE CASE STATEMENT: STEP 1 Start with a SELECT statement with the pre-existing database fields of interest from the invoices table. For this example, let’s use sales totals by city. SELECT InvoiceDate, BillingAddress, BillingCity, Total FROM invoices ORDER BY BillingCity
  • 72. 72 CODING THE CASE STATEMENT: STEP 2 To add the CASE statement to the query, place it at the bottom of the SELECT portion of the query after the existing fields. Start by adding the keyword CASE followed by the END keyword. Each test begins with the keyword WHEN. The ELSE keyword is the last explicit condition listed (ELSE is optional and if not used, fields not identified by the WHEN are ignored). SELECT InvoiceDate, BillingAddress, BillingCity, Total, CASE … END FROM invoices ORDER BY BillingCity
  • 73. 73 CODING THE CASE STATEMENT: STEP 3 SELECT InvoiceDate, BillingAddress, BillingCity, Total, CASE WHEN TOTAL < 2.00 THEN ‘Baseline Purchase’ WHEN TOTAL BETWEEN 2.00 AND 6.99 THEN ‘Low Purchase’ WHEN TOTAL BETWEEN 7.00 AND 15.00 THEN ‘Target Purchase’ ELSE ‘Top Performers’ END AS PurchaseType FROM invoices ORDER BY BillingCity
  • 74. 74 CASE STATEMENT APPLIED TO THE STUNES DB Note: Use the ORDER BY to order results, perhaps in the new PurchaseType field.
  • 75. 75 USING THE NEW FIELD: PURCHASETYPE Additional questions using PurchaseType: ­ What cities do the top-performing sales come from? ­ Are the top-performing sales mainly from the US or are they from other parts of the world? ­ From what cities are the most baseline purchase made? ­ And others …
  • 76. 76 SELECT InvoiceDate, BillingAddress, BillingCity, Total, CASE WHEN TOTAL < 2.00 THEN ‘Baseline Purchase’ WHEN TOTAL BETWEEN 2.00 AND 6.99 THEN ‘Low Purchase’ WHEN TOTAL BETWEEN 7.00 AND 15.00 THEN ‘Target Purchase’ ELSE ‘Top Performers’ END AS PurchaseType FROM invoices WHERE PurchaseType = ’Top Performers’ ORDER BY BillingCity USING THE NEW FIELD: PURCHASETYPE = ′TOP PERFORMERS′
  • 77. 77 RESULTS: PURCHASETYPE = ′TOP PERFORMERS′
  • 78. 78 SUMMARY Adding comments to queries is considered a best practice. When composing a query, it is useful to phrase what you want from the query in a natural language first, then decide what keywords you need. The basic query usually begins with a SELECT clause that specifies what fields to display from the table using the FROM clause. (e.g., SELECT … FROM …). An alias used after the AS keyword can rename the field names in your query results. The ALIAS does not affect the data in the database nor does it modify the field metadata. The ORDER BY clause allows you to sort alphabetically either in ASC (ascending) or DESC (descending) order. The LIMIT keyword, which is used after the ORDER BY clause, will limit the number of records in the query results (you must include the number of results you wish to show).
  • 79. 79 SUMMARY Operators are special SQL keywords that are used with SQL clauses to filter data by specific conditions. Using the WHERE clause with a combination of different operators can enable the user to search records for specific text, dates, and numbers. The Date ( ) function allows us to exclude the timecode when specifying our date criteria. The order of operations when using logical operators (such as AND/OR) can be controlled by parentheses ( ). The CASE statement allows you to label records with a special field name based on user-specified logical conditions.
  • 80. 80 REFERENCES Allen, G., & Owens, M. (2010). The definitive guide to SQLite. Draw.io. (2020). Diagrams.net. Free flowchart maker and diagrams online. Retrieved November 23, 2020, from https://app.diagrams.net/ Shields, W. (2019). Sql quickstart guide: the simplified beginner's guide to managing, analyzing, and manipulating data with Sql. Clydebank Media. SQLite Browser. (2020, November 09). DB Browser for SQLite. Retrieved November 23, 2020, from https://sqlitebrowser.org/ SQLite. (2020). SQLite Main Website. Retrieved November 23, 2020, from https://sqlite.org/index.html Tutorialspoint. (2020). SQLite Tutorial. Retrieved November 23, 2020, from https://www.tutorialspoint.com/sqlite/index.htm
  • 82. 82 ABOUT THIS COURSE This course is distributed free. I use several sources. But importantly, I use the book noted on the next slide. If you are using these PowerPoints, please attribute Highervista, LLC and me (Ron McFarland). IN ADDITION, please attribute the author noted on the next slide, as the author’s textbook provides essential information for this course. Source: Microsoft Images
  • 83. 83 INTRODUCTION This course is offered to you free. HOWEVER, please purchase the following book, as it is a primary resource for this course. I do not make any $ from this course or this book. So, since a handful of good content is derived from the following text, please support this author! Title: SQL Quickstart Guide Author: Walter Shields Available: Amazon, B&N, and through ClydeBank media website at: https://www.clydebankmedia.com/books/programming- tech/sql-quickstart-guide