Basic SQL Queries Beginner
By: Andrew Glasfeld with Sean Lee
2
• Provide a basic understanding of Microsoft SQL Server and how it is used in Siriusware applications.
• Introduce the client tools available for accessing your data. • Introduce the basics of the Transact-SQL programming language.
Class Objectives
3
• SQL Server is a relational database management system (RDMS) – It maintains valid relationships between data in the database. – Ensures that data is stored correctly and that the rules defining the
data and relationships between the data are not violated. – Acts as the “back end” for Siriusware’s software, storing (most) of the
data saved. • Transact-SQL (T-SQL) is the Microsoft version of the Structured Query
Language (SQL) – SQL is a set of commands that allow you to control a database. The
American National Standards Institute (ANSI) defines the language’s standards.
– T-SQL conforms to the ANSI standard, but adds many extensions to make it a more powerful tool for SQL Server users.
What is SQL?
4
• SQL Server 2005, 2008, & 2008 R2: – SQL Server Management Studio (SSMS)
• Other possibilities (that aren’t really recommended): – Microsoft Office Query Builder – Microsoft Access
Where do I go to start writing SQL?
5
• Databases • Tables • Rows • Columns • Data Types • Relationships • Keys
Relational Database Basics
6
• CHAR(n) • VARCHAR(n) • INT • NUMERIC(n, n) • MONEY • BIT
Common Data Types Used in SiriusSQL
7
• Open SQL Server Express Management Studio • Explore the Object Explorer • Open the file “Basic SQL Queries.sql” • Change the database to “SiriusSQL_Seminar”
SQL Server Management Studio
8
Some of these example queries could cripple your production server if run during business hours. They are used for illustrative purposes only.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
WARNING!!!
9
• The SELECT statement • Filtering data with the WHERE clause • Comparison operators (=, <, >, <=, >=, <>…) • Logical (Boolean) operators (AND, OR…)
Basic SQL…
10
• Write a query to list all guests. Result set should have two columns: last_name and first_name.
• Write a query to list all guests (first_name, last_name) who were born in 1990 or later.
• Write a query to list all transactions that occurred in the month of September. Result set should include six columns: department, category, item, quantity, extension, date_time.
Your turn…
11
• More Logical (Boolean) operators (IN, BETWEEN, LIKE…) • Sorting results with the ORDER BY clause • Aliases in SQL
Basic SQL…
12
• Write another query to list all transactions that occurred in the month of September. Result set should include six columns: department, category, item, quantity, extension, date_time.
• Write a query to list all guests whose last names begin with the letter “S”. Sort the results by last name then first name.
• Write a query to list all transactions from any of these three departments: ACTIVITIES, EVENTS, IMAX-EXHIB. Result set should include six columns: department, category, item, quantity, extension, date_time.
• What other way could you have written the above query?
Your turn…
13
String Functions • LEFT • RIGHT • SUBSTRING • LTRIM • RTRIM • REPLACE • PATINDEX
SQL Functions
14
• Write a query that includes six columns: the department nickname (department), the first letter of the department (initial), everything but the first letter of the department (epartment), the department description (descrip), the department description but with underscores substituted for all spaces (de_scrip), and the department description without any trailing spaces (make up your own column name).
Your turn…
15
Date Functions • DATEADD • DATEDIFF • DATEPART • DATENAME • CURRENT_TIMESTAMP
SQL Functions
16
• Write a query against the guests table that includes six columns: first_name, last_name, birth_date, the number of the month they were born (MonthNum), the month name (MonthName), the number of years between now and their birth_date (Years).
Your turn…
17
System Functions • ISNULL • CONVERT/CAST
SQL Functions
18
• Write a query against the guests table that includes six columns: first_name, last_name, and the guest’s birthday, formatted as “MM/dd/yyyy”, with “unavailable” returned if there is no birth_date on record.
Your turn…
19
Aggregate Functions • SUM • COUNT • AVG • MIN • MAX
Using the GROUP BY clause and filtering grouped data with the HAVING clause
SQL Functions
20
• Write a query to get the total gross revenue by department. The results will have two columns: department and GrossRevenue.
• Write a query to get the total gross revenue by transaction date. The results will have two columns: TransactionDate and GrossRevenue.
• Write the same query as above, except with NetRevenue instead of Gross. (extension – tax_amount – tax_amt2 – fee_amount)
Your turn
21
Combining similar data with Unions:
first_name last_name Avery Alesi Andrew Glasfeld Alec Hampton Naomi Nosonovsky John Tappero
first_name last_name Sean Lee Naomi Nosonovsky John Tappero
SQL Developers FoxPro Developers
22
SELECT first_name, last_name FROM [SQL Developers]
UNION
SELECT first_name, last_name FROM [FoxPro Developers]
first_name last_name Avery Alesi Andrew Glasfeld Alec Hampton Sean Lee Naomi Nosonovsky John Tappero
Result Set:
Union:
23
• Write a query that returns a list of all guests whose last name begins with “G”. The result set should have two columns: last_name, first_name
• Write a query that returns a list of all guests whose first name begins with “M”. The result set should have two columns: last_name, first_name
• Write a query that combines the data from both of the above queries
Your turn
24
SELECT first_name, last_name FROM [SQL Developers]
UNION ALL
SELECT first_name, last_name FROM [FoxPro Developers]
first_name last_name Avery Alesi Andrew Glasfeld Alec Hampton Sean Lee Naomi Nosonovsky Naomi Nosonovsky John Tappero John Tappero
Result Set:
Union All:
25
• Write a query that returns the first profit center number and profit center split amount for each item sold in transact (that is not in the **TRANS** department). Result set should have five columns: department, category, item, pr_ctr_1, pcsplit_1
• Write the same query five more times, but for the 2nd, 3rd, 4th, 5th, and 6th profit centers.
• Combine the data from all six queries into a single result set.
Your turn
26
• In a Relational Database, you want to repeat as little information as possible (Normalization). – Example: sale_hdr and transact tables
• This is the most efficient method of storing data. • In order to retrieve the data in a more complete fashion, you must JOIN
together two (or often many more) tables. • Table relationships are often based on Primary Keys and Foreign Keys,
though not always.
Joins:
27
Combining related data with Inner Joins
sale_no pmt_type1 pmt_amt1
1001001 0 10.4500
2001001 4 25.9900
sale_no trans_no item quantity 1001001 1001001 AD1DAY 2
1001001 2001001 CH1DAY 1
2001001 3001001 SR2DAY 2
sale_hdr transact
28
SELECT *
FROM sale_hdr sh
JOIN transact t ON t.sale_no = sh.sale_no
sale_no pmt_type1 pmt_amt1 sale_no trans_no item quantity 1001001 0 10.4500 1001001 1001001 AD1DAY 2
1001001 0 10.4500 1001001 2001001 CH1DAY 1
2001001 4 25.9900 2001001 3001001 SR2DAY 2
Result Set:
Inner Join:
29
• Write a query that returns the department nickname, category nickname, item nickname, item description, quantity sold, and gross revenue.
• Write the same query as above, but returning only one row for each item with the item’s total sales.
Your turn
30
Combining related data with Outer Joins:
pass_no guest_no department
9801001 1001001 EMPPASS
9901001 3001001 GOLDPASS
guest_no first_name last_name
1001001 Sean Lee
2001001 Alec Hampton
3001001 Andrew Glasfeld
gst_pass guests
31
SELECT *
FROM guests g
LEFT JOIN gst_pass gp ON gp.guest_no = g.guest_no
guest_no first_name last_name pass_no guest_no department
1001001 Sean Lee 9801001 1001001 EMPPASS
2001001 Alec Hampton NULL NULL NULL
3001001 Andrew Glasfeld 9901001 3001001 GOLDPASS
Result Set:
Outer Join:
32
• Write a query that returns each guests’ first name, last name, and the city and state of their mailing address (if we have one on file).
Your turn
33
(or “Holy Cabooses, I can’t believe we got this far!!!”) • Subqueries and Derived Tables! • CASE statements! • Variables!
Bonus time!!!
34
• SQL Help Files (Shift-F1) • MSDN Transact-SQL Reference • http://www.sqlcourse.com/ • W3 school’s SQL Tutorial • Siriusware’s SiriusSQL Data Dictionary (NDA required)
For more information
Thank You!