SQL Workshop. Introduction Queries. Doug Shook

Similar documents
HNDIT 1105 Database Management Systems

Chapter 3 How to retrieve data from a single table

Database Management Systems

SQL Workshop. Joins. Doug Shook

Lesson 05: How to Insert, Update, and Delete Data. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Chapter 7 How to code subqueries

SQL Workshop. Database Design. Doug Shook

SQL Workshop. Subqueries. Doug Shook

Chapter 1 An introduction to relational databases and SQL

Lecture 3: Continuing SQL. Monday, February 2, 2015

Chapter 4 How to retrieve data from two tables

Chapter 11 How to create databases, tables, and indexes

SQL Workshop. Summaries. Doug Shook

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Relational Database Management Systems for Epidemiologists: SQL Part I

SQL functions fit into two broad categories: Data definition language Data manipulation language

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Lecture 9: Database Design. Wednesday, February 18, 2015

Homework Assignment. 1. Stored Procedures (SPs)

Conceptual Design. The Entity-Relationship (ER) Model

Oracle Syllabus Course code-r10605 SQL

MIT Database Management Systems

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

CSC Web Programming. Introduction to SQL

Oracle SQL. murach s. and PL/SQL TRAINING & REFERENCE. (Chapter 2)

Chapter 8 How to work with data types

DB2 SQL Class Outline

Full file at

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

You can write a command to retrieve specified columns and all rows from a table, as illustrated

Oracle Database: Introduction to SQL Ed 2

12. MS Access Tables, Relationships, and Queries

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

Database Programming with SQL

SQL Interview Questions

Querying Data with Transact SQL

Oracle Database 10g: Introduction to SQL

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Greenplum SQL Class Outline

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

II. Structured Query Language (SQL)

Chapter-14 SQL COMMANDS

II. Structured Query Language (SQL)

Data Infrastructure IRAP Training 6/27/2016

Ken s SQL Syntax Refresher

5. Single-row function

CGS 3066: Spring 2017 SQL Reference

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Teradata SQL Features Overview Version

Lecture 06. Fall 2018 Borough of Manhattan Community College

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Lesson 2. Data Manipulation Language

EE221 Databases Practicals Manual

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object.

RETRIEVING DATA USING THE SQL SELECT STATEMENT

Data Manipulation Language (DML)

Oracle Database 10g: SQL Fundamentals I

CMPT 354: Database System I. Lecture 3. SQL Basics

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

Fundamental Microsoft Jet SQL for Access 2000

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Oracle Database: SQL and PL/SQL Fundamentals

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

SQL QUERIES. CS121: Relational Databases Fall 2017 Lecture 5

Sql Server Syllabus. Overview

Oracle Database 10g: SQL Fundamentals I

CST272 SQL Server, SQL and the SqlDataSource Page 1

SQL Queries. for. Mere Mortals. Third Edition. A Hands-On Guide to Data Manipulation in SQL. John L. Viescas Michael J. Hernandez

Advanced SQL. Chapter 8 finally!

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

MIS2502: Data Analytics SQL Getting Information Out of a Database Part 1: Basic Queries

Instructor: Craig Duckett. Lecture 02: Thursday, March 29 th, 2018 SQL Basics and SELECT, FROM, WHERE

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Oracle Developer Track Course Contents. Mr. Sandeep M Shinde. Oracle Application Techno-Functional Consultant

Oracle Database 11g: SQL Fundamentals I

Working with Columns, Characters and Rows. Copyright 2008, Oracle. All rights reserved.

Outer Join, More on SQL Constraints

MariaDB Crash Course. A Addison-Wesley. Ben Forta. Upper Saddle River, NJ Boston. Indianapolis. Singapore Mexico City. Cape Town Sydney.

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

Chapter # 7 Introduction to Structured Query Language (SQL) Part II

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Follow these steps to get started: o Launch MS Access from your start menu. The MS Access startup panel is displayed:

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

Deepak Bhinde PGT Comp. Sc.

Lecture 2: Chapter Objectives. Relational Data Structure. Relational Data Model. Introduction to Relational Model & Structured Query Language (SQL)

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Physical Design of Relational Databases

Lecture 2: Chapter Objectives

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Transcription:

SQL Workshop Introduction Queries Doug Shook

SQL Server As its name implies: its a data base server! Technically it is a database management system (DBMS) Competitors: Oracle, MySQL, DB2 End users (that s you!) interact as clients Queries formed on the client and passed to the server 2

SQL Server Database server ` Network ` Client Client ` Client 3

Relational database model Data is stored in tables One or more columns (fields) Many, many, rows (records) Modeled after real world entities Attributes Instances Primary keys are used to identify each record Must be unique! 4

Relational database model Primary key Columns Rows 5

Relational database model Relationships are defined between two tables by foreign keys One-to-one One-to-many Many-to-many Primary key -> foreign key 6

Relational database model Primary key Foreign key 7

Columns Columns have associated properties Data type Null? Default value Identity column 8

Comparison with file systems Databases... Are consistent Same basic structure for all data Are easier to maintain Due to centralization Can perform validations Can enforce relationships Can access many records at once Allow concurrent access Performance considerations? 9

SQL Forms the basis of all DBMS Basic statements will work (mostly) regardless of platform Each vendor adds extensions Two main categories Data Manipulation Language Data Definition Language 10

SQL SQL DML statements SELECT INSERT UPDATE DELETE SQL DDL statements CREATE DATABASE, TABLE, INDEX ALTER TABLE, INDEX DROP DATABASE, TABLE, INDEX 11

SQL Coding Guidelines Freeform Lines, spaces, linebreaks do not affect code Not case sensitive (!) Comments Block /* */ Single line -- 12

SQL Coding Guidelines Recommendations: Each clause should be on a new line Break up long clauses and indent Keywords should be capatalized (or in all caps) Column and table names should use CamelCase Each statement should end with a semicolon Technically not required by SQL Server but... 13

SQL Coding Guidelines A SELECT statement that s difficult to read select invoicenumber, invoicedate, invoicetotal, invoicetotal paymenttotal credittotal as balancedue from invoices where invoicetotal paymenttotal credittotal > 0 order by invoicedate A SELECT statement that s coded with a readable style Select InvoiceNumber, InvoiceDate, InvoiceTotal, InvoiceTotal PaymentTotal CreditTotal As BalanceDue From Invoices Where InvoiceTotal PaymentTotal CreditTotal > 0 Order By InvoiceDate; 14

Our Setup Server set up for us We'll be sharing...so be nice! Need a client DBVisualizer 15

Connecting to the DB Server name: supplied to you Authentication Username: washu Password: workshop 16

Database Diagrams Shows: Table relationships Column names Primary keys Great for visualizing the database as a whole 17

Queries Click the green triangle SQL Commander Ensure that the DB you d like to work with is selected in the combobox Type in the query Execute button Results displayed at the bottom Once a query works the way you want, save it! 18

Syntax Errors Sometimes detected by the query editor Common mistakes Wrong DB selected in combobox Misspellings Missing quotation/parentheses 19

Documentation Short version: Use it! Long version: It will save you time and effort. Use it! 20

SELECT Used to retrieve information (Up to) four clauses: SELECT Column name(s) FROM Table name WHERE (Optional) Conditional statement(s) ORDER BY (Optional) Column name(s) 21

SELECT Examples A simple SELECT statement SELECT * FROM Invoices; A SELECT statement that retrieves and sorts rows SELECT InvoiceNumber, InvoiceDate, InvoiceTotal FROM Invoices ORDER BY InvoiceTotal; A SELECT statement that retrieves a calculated value SELECT InvoiceID, InvoiceTotal, CreditTotal + PaymentTotal AS TotalCredits FROM Invoices WHERE InvoiceID = 17; A SELECT statement that retrieves all invoices between given dates SELECT InvoiceNumber, InvoiceDate, InvoiceTotal FROM Invoices WHERE InvoiceDate BETWEEN '2012-01-01' AND '2012-05-31' ORDER BY InvoiceDate; 22

Column Specifications The expanded syntax of the SELECT clause SELECT [ALL DISTINCT] [TOP n [PERCENT] [WITH TIES]] column_specification [[AS] result_column] [, column_specification [[AS] result_column]]... Five ways to code column specifications All columns in a base table Column name in a base table Arithmetic expression String expression Function 23

Column Specifications Column specifications that use base table values The * is used to retrieve all columns SELECT * Column names are used to retrieve specific columns SELECT VendorName, VendorCity, VendorState Column specifications that use calculated values An arithmetic expression is used to calculate BalanceDue SELECT InvoiceNumber, InvoiceTotal - PaymentTotal CreditTotal AS BalanceDue A string expression is used to calculate FullName SELECT VendorContactFName + ' ' + VendorContactLName AS FullName A function is used to calculate CurrentDate SELECT InvoiceNumber, InvoiceDate, GETDATE() AS CurrentDate 24

Naming Columns Two ways to name the columns in a result set Using the AS keyword (the preferred technique) SELECT InvoiceNumber AS [Invoice Number], InvoiceDate AS Date, InvoiceTotal AS Total FROM Invoices; Using the equal operator (an older technique) SELECT [Invoice Number] = InvoiceNumber, Date = InvoiceDate, Total = InvoiceTotal FROM Invoices; The result set for both SELECT statements 25

String Expressions How to concatenate string data SELECT VendorCity, VendorState, VendorCity + VendorState FROM Vendors; How to format string data using literal values SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors; How to include apostrophes in literal values SELECT VendorName + '''s Address: ', VendorCity + ', ' + VendorState + ' ' + VendorZipCode FROM Vendors; 26

Functions A SELECT statement that uses the LEFT function SELECT VendorContactFName, VendorContactLName, LEFT(VendorContactFName, 1) + LEFT(VendorContactLName, 1) AS Initials FROM Vendors; A SELECT statement that uses the CONVERT function SELECT 'Invoice: #' + InvoiceNumber + ', dated ' + CONVERT(char(8), PaymentDate, 1) + ' for $' + CONVERT(varchar(9), PaymentTotal, 1) FROM Invoices; A SELECT statement that computes the age of an invoice SELECT InvoiceDate, GETDATE() AS 'Today''s Date', DATEDIFF(day, InvoiceDate, GETDATE()) AS Age FROM Invoices; 27

DISTINCT A SELECT statement that returns all rows SELECT VendorCity, VendorState FROM Vendors ORDER BY VendorCity; A SELECT statement that eliminates duplicate rows SELECT DISTINCT VendorCity, VendorState FROM Vendors; 28

TOP A SELECT statement with a TOP clause SELECT TOP 5 VendorID, InvoiceTotal FROM Invoices ORDER BY InvoiceTotal DESC; A SELECT statement with a TOP clause and the PERCENT keyword SELECT TOP 5 PERCENT VendorID, InvoiceTotal FROM Invoices ORDER BY InvoiceTotal DESC; A SELECT statement with a TOP clause and the WITH TIES keyword SELECT TOP 5 WITH TIES VendorID, InvoiceDate FROM Invoices ORDER BY InvoiceDate ASC; 29

WHERE Recall that this is optional! Examples of WHERE clauses that retrieve Vendors located in Iowa WHERE VendorState = 'IA' Invoices with a balance due (two variations) WHERE InvoiceTotal PaymentTotal CreditTotal > 0 WHERE InvoiceTotal > PaymentTotal + CreditTotal Vendors with names from A to L WHERE VendorName < 'M' Invoices on or before a specified date WHERE InvoiceDate <= '2012-05-31' Invoices on or after a specified date WHERE InvoiceDate >= '5/1/12' Invoices with credits that don t equal zero WHERE CreditTotal <> 0 30

Logical Operators The syntax of the WHERE clause with logical operators WHERE [NOT] search_condition_1 {AND OR} [NOT] search_condition_2... Examples of queries using logical operators The AND operator WHERE VendorState = 'NJ' AND YTDPurchases > 200 The OR operator WHERE VendorState = 'NJ' OR YTDPurchases > 200 The NOT operator WHERE NOT (InvoiceTotal >= 5000 OR NOT InvoiceDate <= '2012-07-01') The same condition without the NOT operator WHERE InvoiceTotal < 5000 AND InvoiceDate <= '2012-07-01' 31

IN The syntax of the WHERE clause with an IN phrase WHERE test_expression [NOT] IN ({subquery expression_1 [, expression_2]...}) Examples of the IN phrase An IN phrase with a list of numeric literals WHERE TermsID IN (1, 3, 4) An IN phrase preceded by NOT WHERE VendorState NOT IN ('CA', 'NV', 'OR') An IN phrase with a subquery WHERE VendorID IN (SELECT VendorID FROM Invoices WHERE InvoiceDate = '2012-05-01') 32

BETWEEN The syntax of the WHERE clause with a BETWEEN phrase WHERE test_expression [NOT] BETWEEN begin_expression AND end_expression Examples of the BETWEEN phrase A BETWEEN phrase with literal values WHERE InvoiceDate BETWEEN '2012-05-01' AND '2012-05-31' A BETWEEN phrase preceded by NOT WHERE VendorZipCode NOT BETWEEN 93600 AND 93799 A BETWEEN phrase with a test expression coded as a calculated value WHERE InvoiceTotal PaymentTotal CreditTotal BETWEEN 200 AND 500 A BETWEEN phrase with calculated values WHERE InvoiceDueDate BETWEEN GetDate() AND GetDate() + 30 33

Dates Datetime data type includes date and time (duh) So what happens when you compare just the date to a datetime column? More about dates to come... 34

LIKE Used for matching string patterns Symbols %: match zero or more characters _: match any single character []: match anything contained within [ - ]: match anything within the given range [ ^ ]: match anything except what is given 35

LIKE WHERE clauses that use the LIKE phrase Example 1 WHERE VendorCity LIKE 'SAN%' Cities that will be retrieved San Diego and Santa Ana Example 2 WHERE VendorName LIKE 'COMPU_ER%' Vendors that will be retrieved Compuserve and Computerworld Example 3 WHERE VendorContactLName LIKE 'DAMI[EO]N' Names that will be retrieved Damien and Damion 36

LIKE WHERE clauses that use the LIKE phrase (cont.) Example 4 WHERE VendorState LIKE 'N[A-J]' States that will be retrieved NC and NJ but not NV or NY Example 5 WHERE VendorState LIKE 'N[^K-Y]' States that will be retrieved NC and NJ but not NV or NY Example 6 WHERE VendorZipCode NOT LIKE '[1-9]%' Zip codes that will be retrieved 02107 and 08816 37

NULL What qualifies as NULL? 0? Empty string? ( ) A single space? ( ) 38

NULL A SELECT statement that retrieves rows with zero values SELECT * FROM NullSample WHERE InvoiceTotal = 0; A SELECT statement that retrieves rows with non-zero values SELECT * FROM NullSample WHERE InvoiceTotal <> 0; A SELECT statement that retrieves rows with null values SELECT * FROM NullSample WHERE InvoiceTotal IS NULL; A SELECT statement that retrieves rows without null values SELECT * FROM NullSample WHERE InvoiceTotal IS NOT NULL; 39

ORDER BY Can sort by one or more columns Sorts ascending by default Sorting order (ascending) Null Special Characters (&,!, etc.) Numbers Letters Can also use aliases, expressions, and column positions 40

ORDER BY An ORDER BY clause that sorts by one column in descending sequence SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY VendorName DESC; An ORDER BY clause that sorts by three columns SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY VendorState, VendorCity, VendorName; 41

ORDER BY An ORDER BY clause that uses an alias SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY Address, VendorName; An ORDER BY clause that uses an expression SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY VendorContactLName + VendorContactFName; An ORDER BY clause that uses column positions SELECT VendorName, VendorCity + ', ' + VendorState + ' ' + VendorZipCode AS Address FROM Vendors ORDER BY 2, 1; 42

ORDER BY OFFSET and FETCH can optionally be used to retrieve a range of rows OFFSET: Starting position FETCH: Number to retrieve after offset 43

ORDER BY The syntax of the ORDER BY clause for retrieving a range of rows ORDER BY order_by_list OFFSET offset_row_count {ROW ROWS} [FETCH {FIRST NEXT} fetch_row_count {ROW ROWS} ONLY] An ORDER BY clause that retrieves the first five rows SELECT VendorID, InvoiceTotal FROM Invoices ORDER BY InvoiceTotal DESC OFFSET 0 ROWS FETCH FIRST 5 ROWS ONLY; An ORDER BY clause that retrieves rows 11 through 20 SELECT VendorName, VendorCity, VendorState, VendorZipCode FROM Vendors WHERE VendorState = 'CA' ORDER BY VendorCity OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY; 44

45 Exercises Write a SELECT statement that returns three columns from the Vendors table: VendorContactFName, VendorContactLName, and VendorName. Sort the result set by last name, then by first name.

46 Exercises Write a SELECT statement that returns four columns from the Invoices table, named Number, Total, Credits, and Balance: Number Column alias for the InvoiceNumber column Total Column alias for the InvoiceTotal column Credits Sum of the PaymentTotal and CreditTotal columns Balance InvoiceTotal minus the sum of PaymentTotal and CreditTotal

47 Exercises Write a SELECT statement that returns one column from the Vendors table named Full Name. Create this column from the VendorContactFName and VendorContactLName columns. Format it as follows: last name, comma, first name (for example, "Doe, John"). Sort the result set by last name, then by first name.

48 Exercises Write a SELECT statement that returns three columns: InvoiceTotal From the Invoices table 10% 10% of the value of InvoiceTotal Plus 10% The value of InvoiceTotal plus 10% Only return those rows with a balance due greater than 1000. Sort the result set by InvoiceTotal, with the largest invoice first.

49 Exercises Modify the solution to the problem on slide 51 to filter for invoices with an InvoiceTotal that's greater than or equal to $500 but less than or equal to $10,000.

50 Exercises Modify the solution to the problem on slide 52 to filter for contacts whose last name begins with the letter A, B, C, or E.

51 Exercises Write a SELECT statement that determines whether the PaymentDate column of the Invoices table has any invalid values. To be valid, PaymentDate must be a null value if there's a balance due and a non-null value if there's no balance due. Code a compound condition in the WHERE clause that tests for these conditions.