Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Sq lite module6


Published on

Module 6 out of 9; SQLite training slides, databases, SQL, ERD, software design, database

Published in: Software
  • Be the first to comment

  • Be the first to like this

Sq lite module6

  1. 1. MODULE 6: SQLITE AND THE STUNES DATABASE SQL and Scripting Training (C) 2020-2021 Highervista, LLC 1
  2. 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. 3. NEXT STEPS WITH SQLITE AND DB BROWSER SQL and Scripting Training
  4. 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. 5. LAUNCHING THE DB BROWSER SOFTWARE SQL and Scripting Training
  6. 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.
  8. 8. OPEN THE STUNES DATABASE SQL and Scripting Training
  11. 11. EXPLORING THE STUNES DATABASE SQL and Scripting Training
  12. 12. 12 STUNES EXAMPLE DATABASE Located in student resources (place in a folder like SQL Class) Open DB Browser for SQLite
  14. 14. 14 STUNES: 13 TABLES
  15. 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. 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. 17 EXAMINE THE DATABASE STRUCTURE WINDOW 13 tables Fields: Expand the arrow to the left of the table names.
  18. 18. 18 TABLES (13) AND FIELDS IN THE ALBUMS TABLE What are the data types? What is a database record?
  19. 19. THE BROWSE DATA TAB AWS SQL and Scripting Training
  20. 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. 21. THE EXECUTE TAB SQL and Scripting Training
  22. 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. 23 EXECUTE SQL TAB SQL code entered: SELECT * FROM albums;
  24. 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. 25. SQLITE QUERIES: GETTING STARTED SQL and Scripting Training
  26. 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. 27 GENERAL SQL SYNTAX SELECT id from foods where name=’JujyFruit’ | ___________ ================= |. | | | | | | | predicate | subject verb
  28. 28. 28 EXAMPLE SQL QUERY (COMMANDS) select burger from kitchen where patties=2 and toppings=‘jalopenos’ and condiment != ‘mayo’ limit 1;
  29. 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. 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. 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. 32 WRITING THE QUERY Open the Query pane. Identify who wrote it, a date, and a description.
  33. 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. 34 RESULTS Messages Pane: 59 rows in 3 milliseconds Note: Writing SQL in a consistent way is known as coding standards.
  35. 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. 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. 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. 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. 39 FIELD NAMES WITH/WITHOUT ALIAS Without Alias With Alias
  40. 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. 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. 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. 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. 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. 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. 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. 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. 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. 50 WHERE CLAUSE Note: The WHERE Clause always comes after FROM but before ORDER BY.
  51. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 74 CASE STATEMENT APPLIED TO THE STUNES DB Note: Use the ORDER BY to order results, perhaps in the new PurchaseType field.
  75. 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. 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′
  78. 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. 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. 80 REFERENCES Allen, G., & Owens, M. (2010). The definitive guide to SQLite. (2020). Free flowchart maker and diagrams online. Retrieved November 23, 2020, from 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 SQLite. (2020). SQLite Main Website. Retrieved November 23, 2020, from Tutorialspoint. (2020). SQLite Tutorial. Retrieved November 23, 2020, from
  81. 81. 81 INTRODUCTION Ron McFarland Technologist, Educator Source: Microsoft Images
  82. 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. 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: tech/sql-quickstart-guide