INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;

Slides:



Advertisements
Similar presentations
Chapter 11 Group Functions
Advertisements

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Oracle9i: SQL1 SQL Group Functions.
Structured Query Language Part I Chapter Three CIS 218.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
Chapter 6 Group Functions. Chapter Objectives  Differentiate between single-row and multiple-row functions  Use the SUM and AVG functions for numeric.
Chapter 3 Single-Table Queries
A CCESSING D ATABASES WITH JDBC CH 24 C S 442: A DVANCED J AVA P ROGRAMMING.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
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,
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
I NTRODUCTION TO SQL II. T ABLE JOINS A simple SQL select statement is one that selects one or more columns from any single table There are two types.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
1 Querying a Single Table Structured Query Language (SQL) - Part II.
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.
Structured Query Language SQL Unit 2 An Introduction to Organizing and Retrieving Data with SQL.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
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.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I 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.
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.
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.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
Fundamental of Database Systems
CHAPTER 7 DATABASE ACCESS THROUGH WEB
SQL Query Getting to the data ……..
Rob Gleasure robgleasure.com
MySQL DML Commands By Prof. B.A.Khivsara
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Aggregating Data Using Group Functions
The Database Exercises Fall, 2009.
Structured Query Language – The Basics
Aggregating Data Using Group Functions
(SQL) Aggregating Data Using Group Functions
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Rob Gleasure robgleasure.com
SQL LANGUAGE and Relational Data Model TUTORIAL
SQL – Entire Select.
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Introduction To Structured Query Language (SQL)
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Access: SQL Participation Project
Structured Query Language
Structured Query Language – The Fundamentals
Introduction To Structured Query Language (SQL)
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
Aggregating Data Using Group Functions
Presentation transcript:

INLS 623– S QL Instructor: Jason Carter

SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;

Duplicate rows A column may contain many duplicate values; and sometimes you only want to list the distinct values

R EMOVING D UPLICATE S ALARIES select distinct salary from employees

S ORTING R ESULTS SELECT column_name, column_name FROM table_name ORDER BY column_name, column_name ASC; SELECT column_name, column_name FROM table_name ORDER BY column_name, column_name DESC; ASC means ascending order 1,2,3,4,5,6 DESC means descending order 6,5,4,3,2,1 ASC is default

S ORTING R ESULTS IN A SCENDING O RDER select distinct salary from employees order by salary

S ORTING R ESULTS IN D ESCENDING O RDER select distinct salary from employees order by salary

R ETURN A C ERTAIN NUMBER OF R ESULTS SELECT column_name, column_name FROM table_name ORDER BY column_name, column_name LIMIT value ; Value is an actual number SELECT column_name, column_name FROM table_name ORDER BY column_name, column_name LIMIT 10;

L IMIT E XAMPLE select distinct salary from employees limit 5

F ILTERING R ECORDS Use the where clause SELECT column_name, column_name FROM table_name WHERE column_name operator value ; operator

O PERATORS

W HERE C LAUSE E XAMPLE select distinct salary from employees where salary =

W HERE O PERATORS > < >= <= <> or != These operators are straightforward

LIKE O PERATOR The LIKE operator is used in a WHERE clause to search for a specified pattern in a column SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern ; How do we specify a pattern?

W ILDCARDS

L IKE AND W ILDCARDS E XAMPLE % wildcard select ename from employees where ename LIKE 'J%'

L IKE AND W ILDCARDS E XAMPLE select ename from employees where ename LIKE 'John William_'

I N O PERATOR The IN operator allows you to specify multiple values in a WHERE clause It is like an or SELECT column_name(s) FROM table_name WHERE column_name IN ( value1, value2,...);

I N O PERATOR E XAMPLE SELECT * FROM flights WHERE origin IN ('Los Angeles','Madison');

B ETWEEN O PERATOR The BETWEEN operator is used to select values within a range. SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND val ue2; The values can be numbers, text, or dates.

B ETWEEN E XAMPLE SELECT * FROM flights WHERE distance between 100 and 500 order by distance

N OT B ETWEEN The BETWEEN operator is used to select values outside of a range. SELECT column_name(s) FROM table_name WHERE column_name NOT BETWEEN value1 AND value2;

N OT B ETWEEN E XAMPLE SELECT * FROM flights WHERE distance not between 100 and 500 order by distance

T EMPORARILY R ENAME T ABLE OR C OLUMN SQL aliases are used to give a database table, or a column in a table, a temporary name. Columns SELECT column_name AS alias_name FROM table_name; Tables SELECT column_name(s) FROM table_name AS alias_name;

A LIAS E XAMPLE Select ename as "Employee Name" from employees

J OINS Used to combine rows from two or more tables, based on a common field between them. The most common type of join is the inner join You can type inner join or join

I NNER J OIN Returns all rows when there is at least one match in BOTH tables Two tables Faculty and class Want to know the class name and who is teaching the course (faculty name) How would you write this without using joins? select faculty.fname, class.class_name from faculty, class where faculty.fid = class.fid

I NNER J OIN FacultyClass A set of records which match in both the faculty and class table, i.e. all faculty who teach a course.

INNER JOIN EXAMPLE select faculty.fname, class.class_name from faculty inner join class on faculty.fid = class.fid;

L EFT J OIN The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. A set of records which match all of the rows in the faculty table with matching rows in the class table, i.e. all faculty and their courses regardless of whether they teach a course

L EFT J OIN E XAMPLE select faculty.fname, class.class_name from faculty left join class on faculty.fid = class.fid; Faculty who don’t teach a course

R IGHT J OIN The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. A set of records which match all of the rows in the class table with matching rows in the faculty table, i.e. all classes and faculty regardless of whether there is a faculty member teaching the course

R IGHT J OIN E XAMPLE select faculty.fname, class.class_name, faculty.fid from faculty right join class on faculty.fid = class.fid; Class with no faculty

SQL A GGREGATE F UNCTIONS SQL aggregate functions return a single value, calculated from values in a column avg() count() max() min() sum()

AVG OR A VERAGE The AVG() function returns the average value of a numeric column SELECT AVG(column_name) FROM table_name

AVG E XAMPLE Get the average cruising range of aircraft select avg(cruisingrange) as "Average Cruising Range" from aircraft

C OUNT The COUNT() function returns the number of rows that matches a specified criteria Column name SELECT COUNT(column_name) FROM table_name; Count the number of records in the table SELECT COUNT(*) FROM table_name; Count number of distinct columns SELECT COUNT(DISTINCT column_name) FROM table_name;

M AX The MAX() function returns the largest value of the selected column. SELECT MAX(column_name) FROM table_name;

M AX E XAMPLE select max(salary) as "highest salary" from employees;

M IN The MIN() function returns the smallest value of the selected column SELECT MIN(column_name) FROM table_name;

M IN E XAMPLE select min(salary) as "lowest salary" from employees;

G ROUP B Y Used in conjunction with the aggregate functions to group the result-set by one or more columns. Used to group rows into subgroups by the one or more values of columns. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;

G ROUP B Y E XAMPLE How many items each supplier sells? select sid, count(sid) from catalog group by sid What if we want to know the supplier’s name?

G ROUP B Y E XAMPLE How many items each supplier (the name of the supplier) sells? We need the suppliers and catalog table select suppliers.sname, count(catalog.sid) as "number of items" from catalog join suppliers on catalog.sid = suppliers.sid group by catalog.sid

H AVING Used to to specify a filter condition for groups of rows or aggregates. Often used with GROUP BY SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value;

H AVING E XAMPLE The suppliers (name) that sell 3 or more items. select suppliers.sname, count(catalog.sid) as "number of items" from catalog join suppliers on catalog.sid = suppliers.sid group by catalog.sid having count(catalog.sid) >= 3

S UB Q UERY A query that is nested inside another query SELECT * FROM table_name WHERE column_name = (SELECT column_name FROM table_name)

S UB Q UERY E XAMPLE select max(salary) as "highest salary" from employees; We also want to know the employee’s name with the highest salary. select ename, max(salary) as "highest salary" from employees where salary = (select max(salary) from employees);

V IEWS A database view is a virtual table or logical table

V IEWS You can query against a view When the data of the tables changes, the view reflects that changes as well A database view allows you to simplify complex queries A database view helps limit data access to specific users A database view provides extra security layer. (read only)

V IEWS CREATE VIEW [view_name] AS [SELECT statement] The view name cannot be the same name as tables

V IEW E XAMPLES CREATE VIEW customerProductSales AS SELECT orderDetails.orderNumber, customerName, SUM(quantityOrdered * priceEach) as total FROM orderDetails INNER JOIN orders ON orders.orderNumber = orderdetails.orderNumber INNER JOIN customers ON orders.customerNumber = customers.customerNumber GROUP BY orderDetails.orderNumber AS

I NSTALL THE NEW D ATABASE Customers: stores customer’s data. Products: stores a list of scale model cars. ProductLines: stores a list of product line categories. Orders: stores sales orders placed by customers. OrderDetails: stores sales order line items for each sales order. Payments: stores payments made by customers based on their accounts. Employees: stores all employee information as well as the organization structure such as who reports to whom. Offices: stores sales office data.

P RACTICE Get the last name of all employees

P RACTICE Get the last name of all employees (NO DUPLICATES)

P RACTICE Get the last name of all employees sorted in alphabetical order (no duplicates). Get the last name of all employees sorted in reverse alphabetical order (no duplicates).

P RACTICE Select the first 10 customers.

P RACTICE Find all offices in the US and France.

P RACTICE Find all offices that are not in the US and France.

P RACTICE Find product whose buy price within the range of $90 and $100.

P RACTICE Find the product whose buy price is out of the range of $20 and $100

P RACTICE Find employees where their first name starts with character ‘a’. Find employees where their last name ends with ‘on’. Find employee whose first name starts with T, ends with m and contains any single character between.

P RACTICE Show all line items for each order Show all line items for each order only show each orderNumber once

P RACTICE Find all orders that belong to each customer (even if that customer does not have an order)

P RACTICE Want to know the number of orders for each status.

P RACTICE Find which order has total sales greater than $1000. Clue…there is a SUM() function that adds up the numeric value of each column Find all orders that has shipped and has total sales greater than $1500