Using Structured Query Language (SQL) Jeffery S. Horsburgh Hydroinformatics Fall 2014 This work was funded by National Science Foundation Grants EPS 1135482.

Slides:



Advertisements
Similar presentations
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Advertisements

Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Structured Query Language Part I Chapter Three CIS 218.
Microsoft Access 2010 Chapter 7 Using SQL.
Using HydroServer Organize, Manage, and Publish Your Data Support EAR CUAHSI HIS Sharing hydrologic data Jeffery S. Horsburgh.
CORE 2: Information systems and Databases STORAGE & RETRIEVAL 2 : SEARCHING, SELECTING & SORTING.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
ASP.NET Programming with C# and SQL Server First Edition
Learningcomputer.com SQL Server 2008 – Introduction to Transact SQL.
Chapter 10 Queries and Updating Part C. SQL Copyright 2005 Radian Publishing Co.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Exercises: Organizing, Loading, and Managing Point Observations Using HydroServer Support EAR CUAHSI HIS Sharing hydrologic data
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
SQL 101 – Class 1 Lee Turner. Agenda 1. This is your life – SQL A brief history of SQL What SQL is and what it is not Normalization 2. Some Super Simple.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 DBS201: Introduction to Structure Query Language (SQL) Lecture 1.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
SQL.. AN OVERVIEW lecture3 1. Overview of SQL 2  Query: allow questions to be asked of the data and display only the information required. It can include.
Data Model / Database Implementation (continued) Jeffery S. Horsburgh Hydroinformatics Fall 2014 This work was funded by National Science Foundation Grants.
IS6146 Databases for Management Information Systems Lecture 1: Introduction to IS6146 Rob Gleasure robgleasure.com.
Selecting Data Database Administration Fundamentals LESSON 3.1a.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Lecture 9 Using Structured Query Language (SQL) Jeffery S. Horsburgh Hydroinformatics Fall 2012 This work was funded by National Science Foundation Grant.
Lecture 10 Aggregating & Pivoting Data in SQL and Excel David E. Rosenberg CEE 6930 – Hydroinformatics Fall 2012 This work was funded by National Science.
Lecture 5 Data Model Design Jeffery S. Horsburgh Hydroinformatics Fall 2012 This work was funded by National Science Foundation Grant EPS
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
Using Python to Retrieve Data from the CUAHSI HIS Web Services Jeffery S. Horsburgh Hydroinformatics Fall 2015 This work was funded by National Science.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
1 of 42 Lecture 5 Data Model Design Jeffery S. Horsburgh Hydroinformatics Fall 2013 This work was funded by National Science Foundation Grants EPS
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Jeffery S. Horsburgh Hydroinformatics Fall 2014
More SQL: Complex Queries, Triggers, Views, and Schema Modification
ORDER BY Clause The result of a query can be sorted in ascending or descending order using the optional ORDER BY clause. The simplest form of.
Web Systems & Technologies
CHAPTER 7 DATABASE ACCESS THROUGH WEB
SQL Query Getting to the data ……..
Chapter 5 Introduction to SQL.
Access Tutorial 3 Maintaining and Querying a Database
Jeffery S. Horsburgh Utah State University
Lecture 6 Data Model Design (continued)
Using Structured Query Language (SQL) (continued)
Lecture 8 Database Implementation
Database Systems: Design, Implementation, and Management Tenth Edition
JDBC.
Using SQL to Prepare Data for Analysis
SQL 101.
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
CIS16 Application Programming with Visual Basic
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Access: SQL Participation Project
SQL .. An overview lecture3.
Introduction To Structured Query Language (SQL)
Chapter 8 Advanced SQL.
CSC 453 Database Systems Lecture
Database Systems: Design, Implementation, and Management Tenth Edition
Shelly Cashman: Microsoft Access 2016
Assignment 3 Querying and Maintaining a Database
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

Using Structured Query Language (SQL) Jeffery S. Horsburgh Hydroinformatics Fall 2014 This work was funded by National Science Foundation Grants EPS and EPS

2 of 40 Quick Review What we have learned so far – Describing data with effective metadata – Data model design – organizing your data/metadata – Database implementation – creating a database and loading data Today: What you can do once you get your data in a database!!

3 of 40 Objectives Retrieve and use data from data models used in Hydrology such as the Observations Data Model (ODM) Introduce the syntax of Structured Query Language (SQL) for common query types Construct SQL queries to retrieve data

4 of 40 What is Structured Query Language? Special purpose programming language for managing data in relational database management systems (RDBMS) Adopted by the American National Standards Institute (ANSI) and the International Standards Organization (ISO) as the standard data access language Set of standard commands + proprietary extensions – “SELECT” – “INSERT” – “UPDATE” – “DELETE” – … Mostly human readable

5 of 40 Structured Query Language (SQL) Data Definition Language (DDL) – Definition of database structure (relational schemas) – Data access control Data Manipulation Language (DML) – Query language to create, read, update, and delete database objects

6 of 40 Ways to Execute SQL Commands Through a database client application like MySQL Workbench Via code (e.g., Visual Basic, C#, Java, R, Python, etc.) that sends a query to a database and returns results

7 of 40 The Data We Will be Using 7 water quality and streamflow monitoring sites – Temperature – Dissolved Oxygen – pH – Specific Conductance – Turbidity – Water level/discharge 4 weather stations – Temperature – Relative Humidity – Solar radiation – Precipitation – Barometric Pressure – Wind speed and direction – Soil moisture Spread spectrum radio telemetry network

8 of 40 Observations Data Model

9 of 40 Basic SQL Query Structure A basic SQL query consists of a SELECT, a FROM, and a WHERE clause – SELECT Specifies the columns to appear in the result – FROM Specifies the tables to use – WHERE Filters the results based on criteria The order of the clauses cannot be changed

10 of 40 Create a New Query in MySQL Workbench USE LBRODM; Tells MySQL which database to use Create a new SQL tab for executing queries

11 of 40 Selecting Data “SELECT” is used to query the database and retrieve data that match specified criteria SELECT is the core of SQL and covers the vast majority of queries SELECT statement syntax: SELECT Field_1, Field_2, Field_n FROM TableName

12 of 40 Example Select Queries Select all fields from a table: SELECT * FROM Sites; – The “*” means – give me all of the fields/columns in the table

13 of 40 Example Select Queries Retrieve only selected fields from a table: SELECT SiteID, SiteCode, SiteName FROM Sites;

14 of 40 Adding Criteria to SELECT Queries The “WHERE” clause specifies which data values or records will be returned based on criteria Conditional operators used with the WHERE clause: = Equal > Greater than < Less than <= Less than or equal >= Greater than or equal <> Not equal to LIKE Match a substring, with “%” as a wildcard character IN/NOT IN Supply a list of items to test BETWEEN Test between two given values …

15 of 40 Adding Criteria to SELECT Queries Syntax for adding criteria to a SELECT query: SELECT Field_1, Field_2, Field_n FROM TableName WHERE Field_1 = SomeCondition AND/OR Field_2 = AnotherCondition

16 of 40 Adding Criteria to SELECT Queries Example: “Which sites in the database are north of degrees latitude?” SELECT * FROM Sites WHERE Latitude > ; Latitude > ?

17 of 40 Adding Criteria to SELECT Queries Example: “Select sites whose name contains ‘Little Bear River’” SELECT * FROM Sites WHERE SiteName LIKE '%Little Bear River%’;

18 of 40 Adding Criteria to SELECT Queries Example: Select Sites with SiteID 1 and 2 SELECT * FROM Sites WHERE SiteID < 3; SELECT * FROM Sites WHERE SiteID IN (1,2);

19 of 40 Multiple Criteria and Boolean Operators AND – both sides must be true OR – either side can be true SELECT * FROM Sites WHERE SiteID = 1 AND SiteID = 2; Returns no results (0 records) SELECT * FROM Sites WHERE SiteID = 1 OR SiteID = 2; Returns 2 records

20 of 40 Sorting Results Using ORDER BY The ORDER BY clause can be used to arrange query results in ascending (ASC) or descending (DESC) order Example: “Give me quality controlled (QualityControlLevelID = 1) water temperature observations (VariableID = 36) for SiteIDs 1 and 2, order the results by SiteID and then by LocalDateTime in ascending order.” SELECT * FROM DataValues WHERE SiteID IN (1,2) AND VariableID = 36 AND QualityControlLevelID = 1 ORDER BY SiteID ASC, LocalDateTime ASC;

21 of 40 MySQL Defaults MySQL defaults to queries only returning the first 1000 records Turn it off by clicking on the toggle button on the SQL query tab

22 of 40 Selecting DISTINCT Values Select a list containing distinct values Example: “Give me a non-repetitive list of Variable Names used in the Variables table.” This gives me repetitive values: SELECT VariableName FROM Variables; Do this instead: SELECT DISTINCT VariableName FROM Variables;

23 of 40 NULL Values Missing (unknown) info is represented by NULL values Result of any comparison involving a NULL value is Unknown SELECT * FROM Sites WHERE LocalX IS NULL; SELECT * FROM Sites WHERE LocalX IS NOT NULL; What if I do: SELECT * FROM Sites WHERE LocalX < ;

24 of 40 Selecting from More than One Table The “JOIN” statement makes queries relational Joins allow you to select information from more than one table using one SELECT statement JOIN syntax: SELECT LeftTable.Field1, LeftTable.Field1, RightTable.Field1, RightTable.Field2 FROM LeftTable Join_Type RightTable ON JoinCondition

25 of 40 Join Example SiteIDSiteName 1Little Bear River 2Logan River ValueIDSiteIDVariableIDDataValue SiteIDSiteNameVariableIDDataValue 1Little Bear River Logan River SELECT Sites.SiteID, Sites.SiteName, DataValues.VariableID, DataValues.DataValue FROM Sites INNER JOIN DataValues ON Sites.SiteID = DataValues.SiteID; Sites (LeftTable) DataValues(RightTable) Result

26 of 40 Types of Joins INNER JOIN: Takes every record in the LeftTable and looks for 1 or more matches in the RightTable based on the JoinCondition. All matched records are added to the result. OUTER JOIN: Brings two tables together but includes data even if the JoinCondition does not find matching records – 3 Variations: LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN

27 of 40 Source:

28 of 40 Example Using Joins “What are the names of the variables that have been measured in the Little Bear River at Mendon Road?”

29 of 40 Example Using Joins Join on SiteID Join on VariableID

30 of 40 Example Using Joins “What are the names of the variables that have been measured in the Little Bear River at Mendon Road?” SELECT DISTINCT Sites.SiteCode, Sites.SiteName, Variables.VariableName FROM Sites INNER JOIN DataValues ON Sites.SiteID = DataValues.SiteID INNER JOIN Variables ON DataValues.VariableID = Variables.VariableID WHERE Sites.SiteCode = 'USU-LBR-Mendon' ORDER BY VariableName ASC; “DISTINCT” ensures that I only get unique combinations Select what we want in the output. FROM the left table INNER JOIN to the right table on the common field Specify criteria and sort output

31 of 40 Quick Summary: Formulating a SQL Statement 1. Identify the field(s) containing the source data SELECT Field_1, Field_2, Field_n 2. Identify the table(s) where the fields are located FROM Table_1 3. Specify criteria to narrow the results WHERE Field_1 = SomeCriteria 4. Determine the order to present records in the results ORDER BY Field_1 ASC

32 of 40 Challenge Query 1 Select the quality controlled (QualityControlLevelID = 1) turbidity (VariableID = 6) data values for the Little Bear River at Mendon Road (SiteID = 1).

33 of 40 Challenge Query 1 - Solution Select the quality controlled (QualityControlLevelID = 1) turbidity (VariableID = 6) data values for the Little Bear River at Mendon Road (SiteID = 1). SELECT * FROM DataValues WHERE SiteID = 1 AND VariableID= 6 AND QualityControlLevelID = 1;

34 of 40 Challenge Query 2 What is the SiteCode and SiteName for each of the sites at which water temperature (VariableID = 36) has been measured?

35 of 40 Challenge Query 2 - Solution What is the SiteCode and SiteName for each of the sites at which water temperature (VariableID = 36) has been measured? The harder way: SELECT DISTINCT Sites.SiteCode, Sites.SiteName FROM Sites INNER JOIN DataValues ON Sites.SiteID = DataValues.SiteID WHERE DataValues.VariableID = 36 The easier way: SELECT DISTINCT SiteCode, SiteName FROM SeriesCatalog WHERE VariableID = 36

36 of 40 Summary SQL provides a very powerful standard language for querying table-based data SQL enables you to quickly isolate subsets of data SQL is mostly standardized, with some vendor- specific extensions Most database functions can be automated using SQL

37 of 40 Resources for Learning SQL Microsoft Developer Network (MSDN) SQL Reference – us/library/bb510741%28v=sql.105%29.aspx us/library/bb510741%28v=sql.105%29.aspx Google Various books – but may want to start with one that is specific to the RDBMS you plan to use (e.g., MySQL) Another nice discussion on joins: tips.com/faqs.cfm?fid=4785http:// tips.com/faqs.cfm?fid=4785