More sql Session 4 – subselects, union, aggregate functions.

Slides:



Advertisements
Similar presentations
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Advertisements

N.G.Acharya & D.K.Marathe college Chembur-E, Mumbai-71
CSC271 Database Systems Lecture # 11.
CSC443 Integrity Set operations List operations. Review Commands: Create Drop Alter Insert Select.
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
 CS 405G: Introduction to Database Systems Lecture 7: Relational Algebra II Instructor: Chen Qian Spring 2014.
Lists, Views, Describing tables Kris Pepper. Where are we Finishing up integrity, sets and lists, and now adding in views and describe. Finishing homework.
Introduction to Oracle9i: SQL1 SQL Group Functions.
Relational Operators, SQL, and Access Query ISYS 562.
Chapter 11.1 and 11.2 Data Manipulation: Relational Algebra and SQL Brian Cobarrubia Introduction to Database Management Systems October 4, 2007.
Lecture 6 29/1/15. Number functions Number functions take numbers as input, change them, and output the results as numbers. 2.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 3 Single-Table Queries
CSc-340 2b1 Introduction to SQL Chapter 3 [2 of 2] Null Values Aggregate Functions Nested Subqueries Modification of the Database.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
Chapter 11 Functions and Groups Part C. SQL Copyright 2005 Radian Publishing Co.
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
SQL Functions. SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. These functions are use full.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
1/18/00CSE 711 data mining1 What is SQL? Query language for structural databases (esp. RDB) Structured Query Language Originated from Sequel 2 by Chamberlin.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
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.
1 SY306 Web and Databases for Cyber Operations Set #13: SQL SELECT Grouping and sub-queries.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
SQL constrains and keys. SORTED RESULTS Sort the results by a specified criterion SELECT columns FROM tables WHERE predicates ORDER BY column ASC/DESC;
Oracle Developer. Create Table SQL> create table catalog ( 2 cno varchar2(7), 3 ctitle varchar2(50), 4 primary key (cno)); Table created. SQL> describe.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
COMP 430 Intro. to Database Systems Grouping & Aggregation Slides use ideas from Chris Ré and Chris Jermaine. Get clickers today!
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Chapter 3 Introduction to SQL
CS 480: Database Systems Lecture 12 February 11, 2013.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Introduction to SQL.
Chapter 3 Introduction to SQL(3)
Lecture#7: Fun with SQL (Part 2)
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
CS 405G: Introduction to Database Systems
Chapter 11 Functions and Groups
SQL – Entire Select.
Built in Functions Massaging the data.
Chapter 4 Summary Query.
CS122 Using Relational Databases and SQL
Reporting Aggregated Data Using the Group Functions
Query Functions.
CSC 453 Database Systems Lecture
Set Operations Union Intersect Minus.
Trainer: Bach Ngoc Toan– TEDU Website:
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

More sql Session 4 – subselects, union, aggregate functions

Catalog cno varchar(7) ctitle varchar(50) Students sid varchar(5) fname varchar(20) lname varchar(20) minit char Courses term varchar(10) lineno int(4) cno varchar(7) a int(2) b int(2) c int(2) d int(2) Components term varchar(10) lineno int(4) compname varchar(15) maxpoints int(4) weight int(2) Enrolls sid varchar(5) term varchar(10) lineno varchar(4) Scores sid varchar(5) term varchar(10) lineno varchar(4) compname varchar(15) points int(4)

Sub-selects The search criteria in the where clause may itself contain a select statement. Such a select statement is referred a a sub- select.

sub-select operators in and not in Get the sid values of students who have enrolled in csc226. select fname,lname from students where sid in (select sid from enrolls, courses where enrolls.term = courses.term and enrolls.lineno = courses.lineno and cno = 'csc226'); Ex: Get the names of students who have enrolled in csc226 or csc227.

sub-select operators(cont) any – the comparison succeeds if it matches any one value in the subselect all - the comparison succeeds if it matches all the values in the subselect Get the students name with the lowest student id: select fname,lname from students where sid <= all (select sid from students); Get the names of students who took at least one course in the fall semester of 1996 select distinct fname, lname from students, enrolls where students.sid=enrolls.sid and students.sid = any ( select distinct sid from enrolls where term=‘f96’);

sub-select operators(cont) exists and not exists –exists predicate is true if the sub-select result is a non-empty set of values and is false otherwise Get the ids of student who did not enroll in any course in the fall 1996 semester. select sid from students where not exists ( select ’a’ from enrolls where term=“f96” and students.sid=enrolls.sid);

Union Computes the union of two sub-queries Get the student ids enrolled in f96 or sp97 select sid from enrolls where term=“f96” union select sid from enrolls where term=“sp97” Union all does not remove duplicates select sid from enrolls where term=“f96” Union all select sid from enrolls where term=“sp97”

Aggregate functions NameArgument typeResult TypeDescription countany( can be *)numericcount of occurrences sumnumeric sum of arguments avgnumeric Average of arguments maxchar or numericsame as argument maximum value minchar or numericsame as argument minimum value

Aggregate functions examples Get the total number of students select count(*) sid from students; Get the un-weighted average of the number of points for all tests in section 1031, fall select avg(maxpoints) from components where lineno=“1031” and term=“f96”;

Group by and having The group by clause is used to form groups of rows of a resulting table based on column values When the group by clause is used all aggregate operations are computed on the individual groups, not on the entire table The having clause is used to eliminate certain groups

Group and having example Get the average number of points for all the tests in each term/section select term,lineno,avg(maxpoints) from components group by term,lineno; Get the average number of points for all the tests in each term/section, but only if the average is higher then select term,lineno,avg(maxpoints) AVG from components group by term,lineno having AVG >=100

Sql functions String functions : –lower(string) –upper(string) –char_lenth(string) –substring(string,start [,n]) –trim(string) – removes spaces from the string (ltrim, rtrim)

Sql functions (cont) Numeric functions –+,-,*, / –abs – absolute value –ceil, floor –mod –power –sqrt

Sql functions (cont) Date functions –current_date() –+, - ' :59:59' + INTERVAL 1 SECOND = ' :00:00‘ SELECT ' ' - INTERVAL 1 DAYS = ' ' –PERIOD_DIFF(P1,P2) – months between P1 and P2 (YYMM) –> < = –trunc(d) returns the same day but with the time truncated to 12:00AM –More information : and-time-functions.html

More information of MySql functions : nctions.html

In class exercises Get the sid values of students who did not enroll in any class during the f96 term. Get the names of students who have enrolled in the highest number of courses.