ims 4212: intro to sql 1 dr. lawrence west, management dept., university of central florida...

28
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida [email protected] Introduction to SQL—Topics Introduction to SQL SQL & Programming Categories of SQL Statements The SELECT Query Limiting columns Limiting rows with WHERE Sorting (ordering) results Renaming the output columns with AS Computed columns Functions in SQL

Upload: willa-webb

Post on 02-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

1Dr. Lawrence West, Management Dept., University of Central [email protected]

Introduction to SQL—Topics

• Introduction to SQL

• SQL & Programming

• Categories of SQL Statements

• The SELECT Query

– Limiting columns

– Limiting rows with WHERE

– Sorting (ordering) results

– Renaming the output columns with AS

– Computed columns

– Functions in SQL

Page 2: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

2Dr. Lawrence West, Management Dept., University of Central [email protected]

What is SQL?

• SQL stands for "Structured Query Language" and is a language for manipulating relational databases

• Pronounced "S"-"Q"-"L" or "SEQUEL"

• ANSI SQL is the 'base' version of SQL

• Each manufacturer has their own dialect of SQL

• Most differences are in special purpose corners of the language

Page 3: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

3Dr. Lawrence West, Management Dept., University of Central [email protected]

What is SQL (cont.)

• SQL is not a programming language

– SQL comes with the database

– Database engine interprets SQL statements, acts on them, and (if pertinent) returns a result

• SQL can be entered directly in most DBMS

• SQL can be embedded in a programming language and passed to the database engine

• We will learn SQL and then use it in our applications

Page 4: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

4Dr. Lawrence West, Management Dept., University of Central [email protected]

SQL and Programming

• SQL represents a division of labor between the database and the program you write

– You create the interface for input and output

– You translate user needs into SQL 'behind the scenes' and pass SQL to the DBMS

– DBMS executes commands

– You take results (including errors!) and display them to the user through your interface

• SQL can contain complex procedural code in addition to data manipulation statements

Page 5: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

5Dr. Lawrence West, Management Dept., University of Central [email protected]

SQL & Programming (cont.)

• You will only rarely enter SQL directly at the DBMS level except for instructional needs and testing

– Most have front ends for creating and modifying database structures

– In large systems the database administrator (DBA) will do the database structure creation

• You will constantly use SQL in programs, though and need to be expert in its use

Page 6: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

6Dr. Lawrence West, Management Dept., University of Central [email protected]

SQL & Programming (cont.)

• SQL follows an 80/20 rule

– You will use 20% of the language to do 80% of the necessary tasks

– You need to be aware of what exists in the other 80% of the language

• Sometimes you're going to have one of those 20% tasks

• Many employers ask about SQL skills in interviews

Page 7: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

7Dr. Lawrence West, Management Dept., University of Central [email protected]

Categories of SQL Statements

• SQL statements are divided into two groups– Data definition language: Create and modify the

structure of the database• Tables• Relationships• Rules• Indices

– Data manipulation language• Add and delete records• Retrieve records• Update records

Page 8: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

8Dr. Lawrence West, Management Dept., University of Central [email protected]

Categories of SQL Statements (cont)

• Data Definition Language

– CREATE TABLE statement

– CREATE INDEX statement

– ALTER TABLE statement

– CONSTRAINT clauses

– DROP statement

Page 9: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

9Dr. Lawrence West, Management Dept., University of Central [email protected]

Categories of SQL Statements (cont.)

• Data Manipulation Language

– SELECT statement

– INSERT INTO statement

– UPDATE statement

– DELETE statement

– JOIN operations

• INNER JOIN, LEFT JOIN, RIGHT JOIN, OUTER JOIN

– WHERE, ORDER BY, & HAVING clauses

Page 10: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

10Dr. Lawrence West, Management Dept., University of Central [email protected]

The SELECT Statement (Query)

• SELECT provides the mechanism for retrieving data from the database

– Can assemble data together from multiple tables into logical records

– Can limit which records you retrieve

– Can limit which fields you retrieve

– Can perform calculations and display the results along with 'raw' data values

• SELECT will be a workhorse in your database programming and you should understand it thoroughly

Page 11: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

11Dr. Lawrence West, Management Dept., University of Central [email protected]

Introduction To the Query Editor

Page 12: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

12Dr. Lawrence West, Management Dept., University of Central [email protected]

SELECT Statement—Simple Example

SELECT *FROM Suppliers;

SELECT SQL keyword Return all fields (columns)

FROM SQL keyword indicatestables involved in the query

Indicates only Supplierstable is used

This query returns all fields from all records in the Supplierstable

Note that SQLkeywords arein all capital letters

Page 13: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

13Dr. Lawrence West, Management Dept., University of Central [email protected]

SELECT Statement—Exercise

• Change active database toNorthWind

• Enter the query below andclick Execute or press "F5"

SELECT *FROM Products

Page 14: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

14Dr. Lawrence West, Management Dept., University of Central [email protected]

Query Results Pane

Editingwindow

ResultsPane

Recordsreturned

(Ctrl-R will eliminate the results pane after a query has run)

Page 15: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

15Dr. Lawrence West, Management Dept., University of Central [email protected]

The SELECT Clause—Limiting Output Columns

• SELECT keyword may be followed by a list of fields or other expressions

• Only these fields will be returned in the result set!

• Fields may be specified in any order (very important)

SELECT CompanyName, Phone, FaxFROM Suppliers;

Page 16: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

16Dr. Lawrence West, Management Dept., University of Central [email protected]

Exercises

• Enter and run the following queries

• Write the query to return just Customer company names and countries

SELECT ProductID, ProductName, UnitsInStockFROM Products

SELECT ProductName, ProductID, UnitsInStockFROM Products

Page 17: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

17Dr. Lawrence West, Management Dept., University of Central [email protected]

The WHERE Clause—Limiting Records

• The WHERE clause establishes a condition that can be tested to be either True or False for any record

– Usually tests value of one or more fields

• Only the records whose values are TRUE for the specified WHERE clause criteria are returned in the result set

SELECT CompanyName, Phone, FaxFROM SuppliersWHERE Country = 'USA';

Page 18: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

18Dr. Lawrence West, Management Dept., University of Central [email protected]

The WHERE Clause—Limiting Records (cont.)

• String and Date literal values must be delimited

– SQL Server uses single quotes as delimiters for all data types needing delimiters

– Some databases use different delimiters

• String values in single or double quotes

• Date values in pound signs (#) or single quotes

• Numeric literals do not use delimiters

Page 19: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

19Dr. Lawrence West, Management Dept., University of Central [email protected]

The WHERE Clause—Compound Tests

• The WHERE Clause can contain complex tests

• Entire test must evaluate to True for record to be displayed

• Use logical operators

– NOT

– AND or OR

– Parenthetical grouping

– <> (notequal), =, <, <=, >, >=

• Follows the same precedence rules as compound logical tests in VB programming

SELECT *FROM SuppliersWHERE Country = 'USA' OR Country = 'Germany';

Page 20: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

20Dr. Lawrence West, Management Dept., University of Central [email protected]

Exercises

• List all of the customers in Germany

• List all of the products where the units in stock are less than the reorder point

• List all products in Category 2

• List all products in Category 2 where the units in stock is less than 20 but do not list the product if it has been discontinued (Discontinued = 1 indicates the product has been discontinued)

Page 21: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

21Dr. Lawrence West, Management Dept., University of Central [email protected]

Some Interesting Tricks

• Run each of these queries:

SELECT 4

SELECT 4, 'Test Value', ProductNameFROM Products

SELECT *FROM ProductsWHERE 4 = 4

Page 22: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

22Dr. Lawrence West, Management Dept., University of Central [email protected]

Reordering Query Output with ORDER BY

• Run these four queries:

SELECT ProductID, ProductName, UnitPriceFROM Products

SELECT ProductID, ProductName, UnitPriceFROM ProductsORDER BY ProductName

SELECT ProductID, ProductName, UnitPriceFROM ProductsORDER BY ProductName DESC

SELECT ProductID, ProductName, UnitPriceFROM ProductsORDER BY SupplierID

Page 23: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

23Dr. Lawrence West, Management Dept., University of Central [email protected]

Reordering Query Output with ORDER BY (cont)

SELECT ProductID, ProductName, SupplierIDFROM Products

SELECT ProductID, ProductName, SupplierIDFROM ProductsORDER BY SupplierID

SELECT ProductID, ProductName, SupplierIDFROM ProductsORDER BY SupplierID, ProductName

Page 24: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

24Dr. Lawrence West, Management Dept., University of Central [email protected]

Aliasing Column Names with AS

SELECT CustomerID, CompanyNameFROM Customers

SELECT CustomerID, CompanyName AS 'Company Name'FROM Customers

SELECT CustomerID, CompanyName AS CompanyFROM Customers

SELECT CustomerID, CompanyName AS Company NameFROM Customers

Msg 102, Level 15, State 1, Line 1Incorrect syntax near 'Name'.

Page 25: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

25Dr. Lawrence West, Management Dept., University of Central [email protected]

Calculated Columns

SELECT ProductID, ProductName, UnitsInStock * UnitPrice AS 'Value'FROM ProductsORDER BY Value

SELECT LastName, FirstName, LastName + ', ' + FirstName AS 'Employee Name'FROM Employees

Always provide a column name to a calculated column with the AS expression

Page 26: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

26Dr. Lawrence West, Management Dept., University of Central [email protected]

Functions

• SQL Server has many intrinsicfunctions that may be used inSQL statements

• We will be mixing these inwith examples throughout thelab

• Browsing these on your owncan pay off for you

• Pay special attention to dateand time functions!!!

Page 27: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

27Dr. Lawrence West, Management Dept., University of Central [email protected]

Some Date Functions in Action

• List all of the order information where the orders took more than five days to ship

SELECT GetDate()

SELECT DatePart(mm, GetDate())

SELECT DateName(mm, GetDate())

SELECT OrderID, OrderDate, ShippedDate, DateDiff(dd, OrderDate, ShippedDate) AS 'Fulfillment Time'FROM OrdersWHERE ShippedDate IS NOT NULL

Page 28: IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Introduction to SQL—Topics Introduction to

IMS 4212: Intro to SQL

28Dr. Lawrence West, Management Dept., University of Central [email protected]

Commenting SQL Statements

CREATE PROCEDURE [dbo].[up_Order_Invoice_OrderInfo] /**********************************************************SP: up_Order_InvoiceTakes an OrderID as a parameter and returns all data neededto create an invoice for the order except order details

Must work with the SP up_Order_Invoice_Details to createall order invoice information.

Created by Dr. Larry West, MIS Department, UCFLast Modified: 9 January 2007**********************************************************/--Create parameter@OrderID intAS

--Execute the querySELECT CUSTOMERS.*, ORDERS.*, EMPLOYEES.LastName, EMPLOYEES.FirstNameFROM CUSTOMERS, ORDERS, EMPLOYEESWHERE ORDERS.OrderID = @OrderID AND ORDERS.CustomerID = CUSTOMERS.CustomerID AND ORDERS.EmployeeID = EMPLOYEES.EmployeeID

Block comment/* … */

Single line comment-- (two hyphens)