SQL Intermediate Workshop Authored by Jay Mussan-Levy.

Slides:



Advertisements
Similar presentations
SQL – Lesson II Grade 12.
Advertisements

Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
The University of Akron Dept of Business Technology Computer Information Systems The Relational Model: Query-By-Example (QBE) 2440: 180 Database Concepts.
Introduction to Structured Query Language (SQL)
1 SQL-Structured Query Language SQL is the most common language used for creating and querying relational databases. Many users can access a database applications.
1 Creating a Non-Conditional List A- What are you going to do? You will “list” “all of the records” in a database. (it means you will not use any condition!)
Structured Query Language Part I Chapter Three CIS 218.
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
Concepts of Database Management, Fifth Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
CHAPTER 7 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
SQL Unit 5 Aggregation, GROUP BY, and HAVING Kirk Scott 1.
Labs for SQL Training Ashish Raghute, Manager of Applications Development, Fleetwood Enterprises.
Banner and the SQL Select Statement: Part Three (Joins) Mark Holliday Department of Mathematics and Computer Science Western Carolina University 4 November.
SQL 1: GETTING INFORMATION OUT OF A DATABASE MIS2502 Data Analytics.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
MIS2502: Data Analytics SQL – Getting Information Out of a Database David Schuff
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Applications – Microsoft Access Lesson 4 Working with Queries 36 Slides in Presentation.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
SQL LANGUAGE and Relational Data Model TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
Structured Query Language SQL Unit 2 An Introduction to Organizing and Retrieving Data with SQL.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Course title: Database-ii Chap No: 03 “Advanced SQL” Course instructor: ILTAF MEHDI.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com.
MIS2502: Data Analytics SQL – Getting Information Out of a Database.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3),
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
How to: SQL By: Sam Loch.
SQL Query Getting to the data ……..
Rob Gleasure robgleasure.com
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
The Database Exercises Fall, 2009.
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Rob Gleasure robgleasure.com
SQL LANGUAGE and Relational Data Model TUTORIAL
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Section 4 - Sorting/Functions
Presentation transcript:

SQL Intermediate Workshop Authored by Jay Mussan-Levy

Introduction to Querying The power of SQL lies not in the creation of tables, but the ability to attain information from them. Querying is asking the database if it has certain things, then the database gives you the results.

Select Statement The way to query in SQL is through the select statement The select statement has five main clauses but “from” is the only required ones Here is the syntax for a select statement: select all|distinct column1, column2 from table1, table2 where "some condition" group by "some condition" having "some condition" order by "some condition"

Select Statement cont’d Here is an example of a simple query: select quantity, max(price) from items_ordered group by quantity; This gets displays the quantity for the most costly item for every quantity number, and its corresponding price. Groups by quantity (staring with 1)

Select Statement cont’d Here is what the results would look like:

Select Statement cont’d Comparison Operators = equals > greater than < less than >= greater than or equal to <=less than or equal to <> or != not equal to LIKEstring comparison test

Select Statement cont’d Example: select first, last, title from employee where title LIKE 'Pro%'; Now the previous statement gets the first name, last name, and title columns for all employees whose title begins with Pro

Select Statement cont’d BeforeAfter

Select Statement All and Distinct ALL and DISTINCT will select either all or unique records ex) Select DISTINCT age from employee_info; This will return all the unique ages you have in the table

Select Statement All and Distinct cont’d BeforeAfter

Select Statement Review Please go to Scroll to the bottom of the page and do Problems 2 and 3

Select Statement Aggregate Functions Aggregate Functions are: Min - Returns the smallest value in a given column Max - Returns the largest value in a given column Sum - Returns the sum of the numeric values in a given column Avg - Returns the average value of a given column Count - Returns the total number of values in a given column Count(*) - returns the number of rows in a table

Select Statement Aggregate Functions cont’d Aggregate values are used to manipulate numeric values in a column. Here is an example: Select avg(salary) from employee;

Select Statement Aggregate Functions cont’d Before After 57,803.33

Select Statement Group By The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and will allow aggregate functions to be performed on the one or more columns.

Select Statement Group By cont’d Here is the syntax: Select "columnname", SUM("columnname2") from "tablename" Group By “some column name";

Select Statement Group By cont’d Select max(salary), title from employee group by title; This statement will select the maximum salary for each unique position. Basically, the salary for the person who makes the most in each position will be displayed. Their, name, salary, and their position will be returned.

Select Statement Group By cont’d Before After

Select Statement Group By cont’d How do you group everything of quantity 1 together, quantity 2 together, quantity 3 together, etc. ? What if you wanted to determine the largest cost item for each grouped quantity? Here is how: Select quantity, max(price) from items_ordered group by quantity

Select Statement Group By cont’d Results

Select Statement Having Clause Must follow the Group By clause Allows you to specify conditions on the rows for each group Which rows should be selected will be based on the conditions you specify

Select Statement Having Clause cont’d The syntax for Having is: Select "columnname", sum("columnname2") from "tablename" group by "columnlist" having "condition";

Select Statement Having Clause cont’d Let's say you have an employee table containing the employee's name, title, salary, and age. If you would like to select the average salary for each position,you could enter: Select title, avg(salary) from employee group by title;

Select Statement Having Clause cont’d Before After

Select Statement Having Clause cont’d But what if you only wanted to display the average if their salary was over 20000? select quantity, avg(price) from items_ordered group by quantity having avg(price) > 20;

Select Statement Having Clause cont’d Results

Select Statement Order By Order by is sorting through a rule you create Ascending descending Syntax: Select "columnname", Sum("columnname2") from "tablename" order by "rule";

Select Statement Order By Example: Select first, last, id, age, state from employee_info where state = ‘Arizona’ order by last; This statement will select 5 columns, where the State is Arizona. It will sort them by last name in ascending order. If you wanted it to be descending, change the last line to: order by last desc;

Select Statement Order By cont’d Before After

Select Statements Combining Conditions cont’d The AND operator – Used to join 2 conditions in the WHERE clause. Both sides of the AND condition must be true for the condition to be met and for those rows to be displayed The OR operator – Used to join two conditions in the WHERE clause. Either side of the OR operator can be true and the condition will be met or both sides can be true

Select Statements Combining Conditions and Boolean Operations Syntax: Select "columnname", sum("columnname2") from "tablename" where "condition1" and "condition2";

Select Statements Combining Conditions and Boolean Operations example: Select first, last, id, age, city, state from employee_info where (age >= 30) and (state = ‘Arizona');

Select Statements Combining Conditions and Boolean Operations Before After

Select Statements Combining Conditions and Boolean Operations Example: Select first, last, id, age, city, state from employee_info where (age >= 30) or (state = ‘Arizona');

Select Statements Combining Conditions and Boolean Operations Before After

Select Statement In and Between Conditional Operators The In Operator can be thought of as an or Statement. This is why: where lastname IN('Hernandez', 'Jones', 'Roberts', 'Ruiz'); is the same as where lastname = (‘Hernandez’) or lastname = (‘Jones’) or lastname = (‘Roberts’) or lastname = ‘Ruiz’); You can also use not in to exclude people

Select Statement In and Between Conditional Operators cont’d The between operator is used to find something within a range of numbers Here is an example: Select employeeid, age, lastname, salary from employee_info where age Between 30 and 40; This is the same as where age >= 30 and age <= 40; You can also use not between

Select Statements Mathematical Functions The Mathematical Operators are: +addition - subtraction *multiplication / division %modulos (remainder)

Select Statements Mathematical Functions cont’d ABS(x)absolute value of x SIGN(x)-1, 0, 1, returns positive, negative, zero MOD(x,y)returns the remainder of x/y (same as x%y) FLOOR(x)returns the largest integer less than or equal to x CEILING(x) or CIEL(x)returns the smallest Integer that is >= x

Select Statements Mathematical Functions cont’d POWER(x,y)raise x to the y power ROUND(x)returns x rounded to the nearest integer ROUND(x,d)returns the value of x rounded to the number of decimal places specified by d SQRT(x)returns the square-root value of x

Select Statements Mathematical Functions cont’d Here is an example: select round(salary), first, last from employee; This means that everyone’s salary will be rounded to the nearest integer

Select Statements Mathematical Functions cont’d Before After

Select Statement Table Joins All the querying you have seen so far has been for one table, Joins will break the barriers holding you back Joining allows you to relate multiple tables to each other which is the reason the databases you are using are called relational.

Select Statements Table Joins cont’d Here is the BASIC syntax for a join: Select "columnname" from "tablename", "tablename2" where "condition"

Select Statements Table Joins cont’d Joins can be explained easier by demonstrating what would happen if you worked with one table only, and didn't have the ability to use "joins". This single table database is also sometimes referred to as a "flat table". Let's say you have a one-table database that is used to keep track of all of your customers and what they purchase from your store

Select Statements Table Joins cont’d Everytime a new row is inserted into the table, all columns will be be updated, thus resulting in unnecessary "redundant data". For example, every time Wolfgang Schultz purchases something, the following rows will be inserted into the table:

Select Statements Table Joins cont’d An ideal database would have two tables: 1) One for keeping track of your customers 2) And the other to keep track of what they purchase: "Customer_info" table: customer_number|firstname|lastname|address|city|state|zip| "Purchases" table: customer_number|date|item|price|

Select Statements Table Joins cont’d Now, whenever a purchase is made from a repeating customer, the 2nd table, "Purchases" only needs to be updated! We've just eliminated useless redundant data, that is, we've just normalized this database!

Select Statements Table Joins cont’d Normalization - Data Normalization is a database design technique that is used to get the tables in your database into at least the third normal form (3NF). Basically, this means that you want to eliminate the redundancy of non-key data when constructing your tables. Each table should only have columns that depend on the primary key.

Select Statements Table Joins cont’d Notice how each of the tables have a common "cusomer_number" column. This column, which contains the unique customer number will be used to JOIN the two tables. Using the two new tables, let's say you would like to select the customer's name, and items they've purchased. Here is an example of a join statement to accomplish this: SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info, purchases WHERE customer_info.customer_number = purchases.customer_number;

Select Statements Table Joins cont’d This particular "Join" is known as an "Inner Join" or "Equijoin". This is the most common type of "Join" that you will see or use.Notice that each of the colums are always preceeded with the table name and a period. This isn't always required, however, it IS good practice so that you wont confuse which colums go with what tables. It is required if the name column names are the same between the two tables. I recommend preceeding all of your columns with the table names when using joins.

Select Statements Table Joins cont’d example: SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comission FROM employee_info, employee_sales WHERE employee_info.employeeid = employee_sales.employeeid; This statement will select the employeeid, lastname (from the employee_info table), and the comission value (from the employee_sales table) for all of the rows where the employeeid in the employee_info table matches the employeeid in the employee_sales table.