SQL – Lesson II Grade 12.

Slides:



Advertisements
Similar presentations
SQL IS 240 – Database Management Lecture #15 – Prof. M. E. Kabay, PhD, CISSP Norwich University
Advertisements

© Abdou Illia MIS Spring 2014
Sometimes you need to use data from more than one table. In example1, the report displays data from two separate tables. Employee IDs exist in the EMPLOYEES.
Join Queries CS 146. Introduction: Join Queries So far, our SELECT queries have retrieved data from a single table Usually queries combine data from multiple.
ZEIT2301 Design of Information Systems Multi-Table Queries in SQL School of Engineering and Information Technology Dr Kathryn Merrick.
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Restricting and Sorting Data. Consider the table employee(employee_id,last_name,job_id, department_id ) assume that you want to display all the employees.
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.
--The SQL Query Language DML--1 LIKE  LIKE allows to select character strings which have some element in common by using wild cards:  Wild cards:  “%”
Structured Query Language Part I Chapter Three CIS 218.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
SQL Intermediate Workshop Authored by Jay Mussan-Levy.
Interpreting SQL Code. SQL (The language used to query a database) S is used to specify the you want to include. F is used to specify the the selected.
Computer Science 101 Web Access to Databases SQL – Extended Form.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
15 Structured Query Language (SQL). 2 Objectives After completing this section, you should be able to: Understand Structured Query Language (SQL) and.
Chapter 3 Single-Table Queries
Labs for SQL Training Ashish Raghute, Manager of Applications Development, Fleetwood Enterprises.
Restricting and Sorting Data. ◦ Limiting rows with:  The WHERE clause  The comparison conditions using =,
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
LECTURE 8.  Consider the table employee(employee_id,last_name,job_id, department_id )  assume that you want to display all the employees in department.
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,
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
CIS 375—Web App Dev II SQL. 2 Introduction SQL (Structured _______ Language) is an ANSI standard language for accessing databases.ANSI SQL can execute.
CIS 375—Web App Dev II SQL. 2 Introduction SQL (Structured _______ Language) is an ANSI standard language for accessing databases.ANSI SQL can execute.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
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.
Information Technology Structured Query Language Grade11.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
ORDER BY clause in SELECT command: Normally, the result of the query will not be in ordered format. If we want to get the result of the query in specific.
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.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
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.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Select Statement IT 350. Select Statement SELECT statement is what we use to choose, or select, the data that we want returned from the database to our.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Restricting and Sorting Data
How to: SQL By: Sam Loch.
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Writing Basic SQL SELECT Statements
Basic select statement
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
The Database Exercises Fall, 2009.
Aggregating Data Using Group Functions
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Restricting and Sorting Data
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Access: SQL Participation Project
M1G Introduction to Database Development
Reporting Aggregated Data Using the Group Functions
Section 4 - Sorting/Functions
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Restricting and Sorting Data
Aggregating Data Using Group Functions
Lab 2: Retrieving Data from the Database
Presentation transcript:

SQL – Lesson II Grade 12

The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you specify The SELECT statement has five main clauses to choose from… SELECT statement format: SELECT [ALL | DISTINCT] column1[,column2] FROM table1[,table2] [WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ]

Lets’ break it down… Example: SELECT name, age, salary FROM employee WHERE age > 50; The above statement will select all of the values in the name, age, and salary columns from the employee table whose age is greater than 50. Comparison Operators = Equal > Greater than < Less than >= Greater than or equal to <= Less than or equal to <> or != Not equal to LIKE String comparison test

Like what? So what about : The LIKE “matching” operator can also be used in the conditional selection of the where clause… Example: SELECT name, title, dept FROM employee WHERE title LIKE 'Pro%'; So what about : ALL and DISTINCT? …are keywords used to select either ALL (default) or the “DISTINCT" / unique records in your query results. Let’s try a few…

items_ordered Exercises From the “itemsOrdered” table, select a list of all items purchased for “customerId” 10449. Display the customerid, item, and price for this customer. Select all columns from the itemsOrdered table for whoever purchased a Tent. Select the customerId, orderDate, and item values from the itemsOrdered table for any items in the item column that start with the letter "S". Select the distinct items in the itemsOrdered table. In other words, display a listing of each of the unique items from the itemsOrdered table. Answers : #1 SELECT customerId, item, price FROM itemsOrdered WHERE customerId=10449; #2 SELECT * FROM items_ordered WHERE item = 'Tent'; #3 SELECT customerId, orderDate, item FROM itemsOrdered WHERE item LIKE 's%'; #4 SELECT DISTINCT item FROM itemsOrdered;

Aggregate Functions Aggregate functions are used to “compare To” a returned column of numeric data". 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 We need to understand these functions before we can cover the "GROUP BY“clause. For example:

Exercises SELECT AVG(salary) FROM employee; SELECT AVG(salary) FROM employee WHERE title = 'Programmer'; SELECT Count(*) FROM employees; This statement will return the number of rows in the employees table. Exercises Select the maximum price of any item ordered in the “itemsOrdered” table. Hint: Select the maximum price only.> 2. Select the average price of all of the items ordered that were purchased in the month of Dec. 3. What are the total number of rows in the itemsOrdered table? 4. For all of the tents that were ordered in the itemsOrdered table, what is the price of the lowest tent? Hint: Your query should return the price only.

Answers #1 SELECT max(price) FROM itemsOrdered; #2 SELECT avg(price) FROM itemsOrdered WHERE orderDate LIKE '%Dec%'; #3 SELECT count(*) FROM itemsOrdered; #4 SELECT min(price) FROM itemsOrdered WHERE item = 'Tent';

The GROUP BY clause… ..will gather all of the rows together that contain data in the specified column(s). It will also allow aggregate functions to be performed on the one or more columns. For example: Let's say you want to retrieve a list of the highest paid salaries in each dept: SELECT max(salary), dept FROM employee GROUP BY dept; The above statement selects the maximum salary for the people in each unique department. Let’s look at the syntax: SELECT column1, SUM(column2) FROM "list-of-tables“ GROUP BY "column-list";

GROUP BY - Multiple Grouping Columns - What if? What if you ALSO want to display their last name for the query below: SELECT max(salary), dept FROM employee GROUP BY dept; What you'll need to do is: SELECT surname, max(salary), dept FROM employee GROUP BY dept, surname; This is a called "multiple grouping columns". Another example? Show them items table. Let's say you want to group everything of quantity 1 together, everything of quantity 2 together, everything of quantity 3 together, etc. If you would like to determine what the largest cost item is for each grouped quantity (all quantity 1's, all quantity 2's, all quantity 3's, etc.), you would enter: SELECT quantity, max(price) FROM items GROUP BY quantity;

Exercises How many people are in the various provinces in the customers table? Select the province and display the number of people in each. Hint: count is used to count rows in a column, sum works on numeric data only. From the itemsOrdered table, select the item, maximum price, and minimum price for each specific item in the table. Hint: The items will need to be broken up into separate groups. 3. How many orders did each customer make? Use the itemsOrdered table. Select the customerId, number of orders they made, and the sum of their orders. Answers #1 SELECT province, count(province) FROM customers GROUP BY province; #2 SELECT item, max(price), min(price) FROM itemsOrdered GROUP BY item; #3 SELECT customerId, count(customerId), sum(price) FROM itemsOrdered GROUP BY customerId;

The HAVING clause… …allows you to specify conditions on the rows for each group. In other words, which rows should be selected will be based on the conditions you specify. Let’s look at the syntax: SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list" HAVING "condition"; HAVING can best be described by example. SELECT dept, avg(salary) FROM employee GROUP BY dept; But, let's say that you want to ONLY calculate & display the average if their salary is over 20000: SELECT dept, avg(salary) FROM employee GROUP BY dept HAVING avg(salary) > 20000;

Exercises  1. How many people are in each province in the customers.tbl that have more than one person in the province? Select province and display the number of how many people are in each if it's greater than 1. 2. From the itemsOrdered.tbl, select the item, maximum price, and minimum price for each specific item in the table. Only display the results if the maximum price for one of the items is greater than 190.00. 3. How many orders did each customer make? Use the itemsOrdered table. Select customerId, number of orders they made, and the sum of their orders if they purchased more than 1 item.

Answers #1 SELECT province, count(province) FROM customers GROUP BY province HAVING count(province) > 1; #2 SELECT item, max(price), min(price) FROM itemsOrdered GROUP BY item HAVING max(price) > 190.00; #3 SELECT customerId, count(customerId), sum(price) FROM itemsOrdered GROUP BY customerId HAVING count(customerId) > 1;

The ORDER BY clause… For example: is an optional clause which allows you to display the results of your query in a sorted order…  Let’s look at the syntax: SELECT column1, SUM(column2) FROM "list-of-tables" ORDER BY "column-list" [ASC | DESC]; For example: SELECT employeeId, dept, name, age, salary FROM employeeInfo WHERE dept = 'Sales' ORDER BY salary; Or, if you would like to order based on 2 or more columns… SELECT employee_id, dept, name, age, salary FROM employee_info WHERE dept = 'Sales' ORDER BY salary, age DESC;

Exercises Select the surname, firstname, and city for all customers in the customers table. Display the results in Ascending Order according to the lastname. Same thing as above, but display the results in Descending order. Select the item and price for all of the items in the itemsOrdered table that the price is greater than 10.00. Display the results in Ascending order based on the price. Answers #1 SELECT lastname, firstname, city FROM customers ORDER BY lastname; #2 SELECT lastname, firstname, city FROM customers ORDER BY lastname DESC; #3 SELECT item, price FROM itemsOrdered WHERE price > 10.00 ORDER BY price ASC;

Combining conditions and Boolean Operators The AND operator can be used to join two or more conditions in the WHERE clause. Both sides of the AND condition must be true in order for the condition to be met SELECT column1, SUM(column2) FROM "list-of-tables" WHERE "condition1" AND "condition2"; Similarly… The OR operator can be used to join two or more conditions in the WHERE clause also. For example SELECT employeeId, firstname, surname, title, salary FROM employeeInfo WHERE salary >= 50000.00 AND title = 'Programmer'; Please feel free to use brackets to separate your conditions…it makes it easier to read… SELECT employeeId, firstname, surname, title, salary FROM employeeInfo WHERE salary >= 50000.00 AND title = 'Programmer';

And/ OR continued… Another Example: Some few Exercises … SELECT firstname, surname, title, salary FROM employeeInfo WHERE (title = 'Sales') OR (title = 'Programmer'); Some few Exercises … Select the customerId, orderDate, and item from itemsOrdered.tbl for all items unless they are 'Shoes‘ or ‘Shot-Guns'. Display the rows as long as they are not either of these two items. 2. Select the item and price of all items that start with the letters 'S', 'P', or 'F'.

Answers #1 SELECT customerId, orderDate, item FROM itemsOrdered WHERE (item <> 'shoes') AND (item <> ‘shot-guns'); NB: You do want to use an AND here. If you were to use an OR here, then either side of the OR will be true, and EVERY row will be displayed. For example, when it encounters ' shot-guns ', it will evaluate to True since ' shot-guns ' are not equal to 'shoes'. #2 SELECT item, price FROM itemsOrdered WHERE (item LIKE 'S%') OR (item LIKE 'P%') OR (item LIKE 'F%');

IN and BETWEEN Conditional Operators… You can also use NOT IN to exclude the rows in your list. …are used to test whether or not a value is "in" the list of values provided after the keyword IN SELECT col1, SUM (col2) FROM "list-of-tables" WHERE col3 IN (list-of-values); SELECT col1, SUM(col2) FROM "list-of-tables" WHERE col3 BETWEEN value1 AND value2; An example: SELECT employeeId, surname, salary FROM employeeInfo WHERE surname IN (Naidoo', ‘Naidu', ‘Moodley', ‘Pompilio'); Alternatively… SELECT employeeId, surname, salaryFROM employee_info WHERE surname = Naidoo' OR surname = ‘Naidu' OR surname = ‘Moodley' OR lastname = ‘Pompilio';

The BETWEEN operator For example: Alternatively… …is used to test to see whether or not a value is “between” a value!? For example: SELECT employeeId, age, surname, salary FROM employeeInfo WHERE age BETWEEN 30 AND 40; Alternatively… SELECT employeeId, age, surname, salary FROM employeeInfo WHERE age >= 30 AND age <= 40; NB.: You can also use NOT BETWEEN to exclude the values between your range. Let’s try a few…

Exercises… Select the date, item, and price from the itemsOrdered table for all of the rows that have a price value ranging from 10.00 to 80.00. Select the firstName, city, and province from the customers table for all of the rows where the state value is either: KZN, WC, EC, Gauteng, or Northern Cape . Answers #1 SELECT orderDate, item, price FROM itemsOrdered WHERE price BETWEEN 10.00 AND 80.00; #2 SELECT firstName, city, province FROM customers  WHERE province IN (KZN', ‘WC', ‘EC', ‘Gauteng', ‘Northern Cape');

Mathematical Operators The basics… + addition - subtraction * multiplication / division % modulo Some few others… ABS(x) returns the absolute value of x SIGN(x) returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively) MOD(x,y) modulo - returns the integer remainder of x divided by y (same as x%y) FLOOR(x) returns the largest integer value that is less than or equal to x CEILING(x) or CEIL(x) returns the smallest integer value that is greater than or equal to x POWER(x,y) returns the value of x raised to the power of y ROUND(x) returns the value of x rounded to the nearest whole integer ROUND(x,d) returns the value of x rounded to the number of decimal places specified by the value d SQRT(x) returns the square-root value of x Example: SELECT round(salary), firstname FROM employee_info

Now you try… The answer: Select the item and per unit price for each item in the items_ordered table. Hint: Divide the price by the quantity. The answer: Exercise #1 select item, sum(price)/sum(quantity) from items_ordered group by item;

Table Joins, a must To put it simply, the "Join" makes relational database systems "relational". A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the FROM keyword. NB.:Joins can be explained easier by demonstrating what would happen if you worked with one table only NB>: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: id first last address city state zip date item price unnecessary "redundant data" id first last address             city state zip date item price 10982 Wolfgang Schultz 300 N. 1st Ave Yuma AZ 85002 032299 snowboard 45.00 082899 snow shovel 35.00 091199 gloves 15.00 100999 lantern 022900 tent 85.00 An ideal database would have two tables: One for keeping track of your customers And the other to keep track of what they purchase: Normalistation…

This column, which contains the unique customer number will be used to JOIN the two tables. "Customer_info" table: customer_number firstname lastname address city state zip Notice  "Purchases" table: customer_number date item price SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info, purchases WHERE customer_info.customer_number = purchases.customer_number; his particular "Join" is known as an "Inner Join The correct syntax though would be.. SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info INNER JOIN purchases ON customer_info.customer_number = purchases.customer_number;

Another example and an exercise… SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comission FROM employee_info, employee_sales WHERE employee_info.employeeid = employee_sales.employeeid; employee_sales employee_info employeeid employeeid Exercises Write a query using a join to determine which items were ordered by each of the customers in the customers table. Select the customerid, firstname, lastname, order_date, item, and price for everything each customer purchased in the items_ordered table. 2. Repeat exercise #1, however display the results sorted by state in descending order.

Answers So, what about OUTER JOINS? Exercise #1 SELECT customers.customerid, customers.firstname, customers.lastname,  items_ordered.order_date, items_ordered.item, items_ordered.price  FROM customers, items_ordered  WHERE customers.customerid = items_ordered.customerid; Exercise #2 SELECT customers.customerid, customers.firstname, customers.state, items_ordered.item  FROM customers, items_ordered  WHERE customers.customerid = items_ordered.customerid  ORDER BY customers.state DESC; So, what about OUTER JOINS?

NEXT YEAR LOSERS!!!