Chapter 16: Advanced MySQL- Grouping Records and Joining Tables. Informatics Practices Class XII. By- Rajesh Kumar Mishra

Similar documents
Visit for more.

Objectives. After completing this lesson, you should be able to do the following:

Visit for more.

Chapter 17: Table & Integrity Contraints. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh

Visit for more.

GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Subquery: There are basically three types of subqueries are:

Chapter 14: MySQL Revision Tour. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh (Raj.)

Chapter 9: Working with MySQL

SQL. Char (30) can store ram, ramji007 or 80- b

CS2 Current Technologies Lecture 2: SQL Programming Basics

Databases - 5. Problems with the relational model Functions and sub-queries

Real-World Performance Training SQL Introduction

Database implementation Further SQL

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

Relational Database Management Systems for Epidemiologists: SQL Part II

Objectives. After completing this lesson, you should be able to do the following:

Slicing and Dicing Data in CF and SQL: Part 1

Chapter 12 DBMS Concepts

Database 2: Slicing and Dicing Data in CF and SQL

Table Joins and Indexes in SQL

KORA. RDBMS Concepts II

Deepak Bhinde PGT Comp. Sc.

Databases - 3. Null, Cartesian Product and Join. Null Null is a value that we use when. Something will never have a value

Databases - 3. Null, Cartesian Product and Join. Null Null is a value that we use when. Something will never have a value

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

1 SQL Structured Query Language

Databases - 4. Other relational operations and DDL. How to write RA expressions for dummies

1 SQL Structured Query Language

Introduction to Views

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

5 Integrity Constraints and Triggers

Intermediate SQL: Aggregated Data, Joins and Set Operators

CS2 Current Technologies Note 1 CS2Bh

NULLs & Outer Joins. Objectives of the Lecture :

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

CSIT5300: Advanced Database Systems

SQL Data Query Language

Types. Inner join ( Equi Joins ) Outer(left, right, full) Cross. Prepared By : - Chintan Shah & Pankti Dharwa 2

Creating Other Schema Objects

Pivot Tables Motivation (1)

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

RDBMS- Day 4. Grouped results Relational algebra Joins Sub queries. In today s session we will discuss about the concept of sub queries.

Creating and Managing Tables Schedule: Timing Topic

CSE 530A SQL. Washington University Fall 2013

Suppose we need to get/retrieve the data from multiple columns which exists in multiple tables...then we use joins..

Handout 9 CS-605 Spring 18 Page 1 of 8. Handout 9. SQL Select -- Multi Table Queries. Joins and Nested Subqueries.

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Oracle Syllabus Course code-r10605 SQL

Sql Server Syllabus. Overview

Chapter 10: Web Application Development. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh

CS 2451 Database Systems: More SQL

Downloaded from

Visit for more.

MySQL DML Commands - Joins and subqueries

DRAFT SOLUTION. Query 1(a) DATABASE MANAGEMENT SYSTEMS PRACTICE 1

T-SQL Training: T-SQL for SQL Server for Developers

Data Manipulation Language (DML)

@vmahawar. Agenda Topics Quiz Useful Links

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

CMP-3440 Database Systems

CIS 363 MySQL. Chapter 12 Joins Chapter 13 Subqueries

ORACLE VIEWS ORACLE VIEWS. Techgoeasy.com

FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017

Key Points. COSC 122 Computer Fluency. Databases. What is a database? Databases in the Real-World DBMS. Database System Approach

Database Management Systems,

Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired.

Chapter 3. Introducation to Relational Database 9/2/2014 CSC4341 1

Database Technology. Topic 3: SQL. Olaf Hartig.

Tables and Volatile Tables

Slicing and Dicing Data in CF and SQL: Part 2

Join (SQL) - Wikipedia, the free encyclopedia

QUERY OPTIMIZATION [CH 15]

THE INDIAN COMMUNITY SCHOOL, KUWAIT

More SQL: Complex Queries, Triggers, Views, and Schema Modification

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Oracle DB-Tuning Essentials

SQL STRUCTURED QUERY LANGUAGE

In This Lecture. More SQL Select. SQL SELECT Overview. Aliases. Example. Example. More SQL Select. Database Systems Lecture 8 Natasha Alechina

Database design process

Database Foundations. 6-9 Joining Tables Using JOIN. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Structure Query Language (SQL)

1. Data Definition Language.

RDBMS Using Oracle. Use of IN OUT

Cartesian Product and the Join Operations. Copyright 2008, Oracle. All rights reserved.

SQL Structured Query Language Introduction

Semantic Errors in Database Queries

MariaDB Crash Course. A Addison-Wesley. Ben Forta. Upper Saddle River, NJ Boston. Indianapolis. Singapore Mexico City. Cape Town Sydney.

Physical Design. Elena Baralis, Silvia Chiusano Politecnico di Torino. Phases of database design D B M G. Database Management Systems. Pag.

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

CSC Web Programming. Introduction to SQL

Oracle Hints. Using Optimizer Hints

Transcription:

Chapter 16: Advanced MySQL- Grouping Records and Joining Tables Informatics Practices Class XII By- Rajesh Kumar Mishra PGT (Comp.Sc.) KV No.1, AFS, Suratgarh (Raj.) e-mail : rkmalld@gmail.com

Grouping Records in a Query Some time it is required to apply a query in a group of records instead of whole table. You can group records by using GROUP BY <Column Name> clause with Select command. A group column is chosen which have non-distinct values like City, Job etc. Generally, Aggregate Functions [MIN(), MAX(), SUM(), AVG(), COUNT()] etc. are applied on groups.

Aggregate or Group Functions Name Purpose Example SUM() MIN() MAX() AVG() COUNT() Returns the sum of given column. Returns the minimum value in the given column. Returns the maximum value in the given column. Returns the Average value of the given column. Returns the total number of values/ records as per given column. Select SUM(Pay) from Emp; Select Sum(Pay), Sum(Net) from Emp; Select MIN(Pay) from Emp; Select MAX(Pay) from Emp; Select AVG(Pay) from Emp; Select COUNT(Name) from Emp; Select COUNT(*) from Emp; A query using Aggregate Function with GROUP BY clause works on the group instead of whole records in the table.

Aggregate or Group Functions An Aggregate function may applied on a column with DISTINCT or ALL keyword. If nothing is given ALL is assumed. SUM ( [DISTINCT ALL] <Column>) This function returns the sum of values in given column or expression. mysql> Select Sum(Sal) from EMP; mysql> Select Sum(DISTINCT Sal) from EMP; mysql> Select Sum (Sal) from EMP where City= Kanpur ; mysql> Select Sum (Sal) from EMP Group By City; mysql> Select Job, Sum(Sal) from EMP Group By Job; MIN ( [DISTINCT ALL] <column>) This functions returns the Minimum value in the given column. mysql> Select Min(Sal) from EMP; mysql> Select Min(Sal) from EMP Group By City; mysql> Select Job, Min(Sal) from EMP Group By Job;

Aggregate or Group Functions MAX ( [DISTINCT ALL] <Column>) This function returns the Maximum value in given column. mysql> Select Max(Sal) from EMP; mysql> Select Max(Sal) from EMP where City= Kanpur ; mysql> Select Max(Sal) from EMP Group By City; AVG ( [DISTINCT ALL] <column>) This functions returns the Average value in the given column. mysql> Select AVG(Sal) from EMP; mysql> Select AVG(Sal) from EMP Group By City; COUNT ( [DISTINCT ALL] <* column>) This functions returns the number of rows in the given column. mysql> Select Count (*) from EMP; mysql> Select Count(Sal) from EMP Group By City; mysql> Select Count(*), Sum(Sal) from EMP Group By Job;

Using Group By clause in Select Query Grouping Results The Group By clause along with Aggregate functions may cause of grouping. mysql> Select Max(Sal) from EMP Group By City; Grouping on Multiple columns- Nested Groups You may define multiple columns with GROUP BY to make a nested groups. mysql> Select City, Job, Count (*) from EMP Group By City, Job; Condition with Group You may use any condition on group, if required. HAVING <condition> clause is used to apply a condition. mysql> Select Job, Count (*) from EMP Group By Job HAVING Count(*)<=3; Where clause is not used with aggregate functions. HAVING can t be used without GROUP By clause.

Joining tables - Join Query Some times it is required to access information from two or more tables, which requires the Joining of two or more tables. Such query is called Join Query. MySQL facilitates you to handle Join Queries. The major types of Join is as follows- Cross Join (Cartesian Product) Equi Join Non-Equi Join Natural Join Outer Join Left Outer Join Right Outer Join Full Outer Join

Cross Join Mathematical Principle Consider the two set A= {a,b} and B={1,2} The Cartesian Product i.e. AxB = {(a,1) (a,2) (b,1) (b,2)} Similarly, we may compute Cross Join of two tables by joining each Record of first table to each record of second table. R A B C p q s m n t l m u X S C X Y s q r t n m R x S A B C C X Y p q s s q r p q s t n m p q s m n t s q r m n t t n m The table will contain (4x3=12) rows and 6 columns. m n t.... l m u

Equvi Join Mathematical Principle In Equvi Join, records are joined on the equality condition of Joining Column. Generally, the Join column is column which is common in both tables. Consider the following table R and S having C as Join column. R S T (Equi Join) A B C p q s m n t l m u C X Y s q r t n m A B C C X Y p q s s q r m n t t n m s p r The result table will contain 6 columns but records are selected those are having Equal value for C column in both table.

Non-Equvi Join Mathematical Principle In Non-Equvi Join, records are joined on the condition other than Equal operator (>,<,<>,>=,<=) for Joining Column (common column). Consider the following table R and S having C as Join column and <> (not equal) operator is applied in join condition. R S T (Non-Equi Join) A B C C X Y A B C C X Y <> p q s s q r p q s t n m m n t l m u t n m The result table will contain 6 columns but records are selected those are having not- equal value for C column in both table. p q s m n t s p r m n t t n m l m u s q R l m u t n M l m u

Natural Join Mathematical Principle The Natural Join is much similar to Equi Join i.e. records are joined on the equality condition of Joining Column except that the common column appears one time. Consider the following table R and S having C as Join column. R S T (Natural Join) A B C p q s m n t l m u C X Y s q r t n m A B C X Y p q s q r m n t n m p r The result table will contain 5 columns (common column is eliminated ) but records are selected those are having Equal value for C column in both table.

Outer Join (Left, Right and Full) The Outer join is much similar to Natural Join but it also contains left (ignored) record during Join. Left outer Join= Natural Join + Record ignored from Left Table. Right outer Join= Natural Join + Record ignored from Right Table. Full outer Join= Natural Join + Record ignored from Left & Right Table. R S T (Full Outer Join) A B C p q s m n t l m u C X Y s q r t n m A B C X Y p q s q r m n t n m p R l m u - - - - Left outer Join result contains ignored record from Left table only. Right Outer Join contains ignored record from Right table only. The Full outer Join result contains ignored records from both table.

Implementing Join Operation in MySQL Suppose two table EMP and DEPT are given - EmpID EName City Job Pay DeptNo EMP DEPT E1 Amitabh Mumbai Manager 50000 D1 E2 Sharukh Delhi Manager 40000 D2 E3 Amir Mumbai Engineer 30000 D1 E4 Kimmi Kanpur Operator 10000 D2 E4 Puneet Chennai Executive 18000 D3 E5 Anupam Kolkatta Manager 35000 D3 E6 Syna Banglore Secretary 15000 D1... DeptNo DName Location D1 Production Mumbai D2 Sales Delhi D3 Admn Mumbai D4 Research Chennai Suppose we want complete details of employees with their Deptt. Name and Location this query requires the join of both tables

How to Join? MySQL offers different ways by which you may join two or more tables. Method 1 : Using Multiple table with FROM clause The simplest way to implement JOIN operation, is the use of multiple table with FROM clause followed with Joining condition in WHERE clause. To avoid ambiguity Select * From EMP, DEPT you should use Where Emp.DeptNo=Dept.DeptNo ; Qualified name i.e. <Table>.<column> Select E.*, D.* From EMP E, DEPT D Where E.DeptNo=D.DeptNo Method 2: Using JOIN keyword You may Alias the tables for easy referencing MySQL offers JOIN keyword, which can be used to implement all type of Join operation. Select * From EMP JOIN DEPT ON Emp.DeptNo=Dept.DeptNo ;

Using Multiple Table with FROM clause The General Syntax of Joining table is- SELECT < List of Columns> FROM <Table1, Table 2, > WHERE <Joining Condition> [Order By..] [Group By..] You may add more condition with Joining Condition using AND/OR NOT operators, if required. All types of Join (Equi, No-Equi, Natural etc. are implemented by changing the Operators in Joining Condition and selection of columns with SELECT clause. Ex. Find out the name of Employees working in Production Deptt. Select Ename From EMP, DEPT Where Emp.DeptNo=Dept.DeptNo AND Dname= Production ; Ex. Find out the name of Employees working in same city from where they belongs (hometown). Select Ename From EMP, DEPT Where Emp.DeptNo=Dept.DeptNo And City=Location;

Using JOIN keyword with FROM clause MySQL s JOIN Keyword may be used with From clause. SELECT < List of Columns> FROM <Table1> [CROSS][NATURAL][LEFT][RIGHT] JOIN <Table2> [ON <Joining Condition>] [USING <column>] [WHERE <Condition>] [Order By..] [Group By..] Ex. Find out the name of Employees working in Production Deptt. Select Ename From EMP JOIN DEPT ON Emp.DeptNo=Dept.DeptNo Where Dname= Production ; Or Select Ename From EMP JOIN DEPT USING DeptNo Where Dname= Production ; Ex. Find out the name of Employees working in same city from where they belongs (hometown). Select Ename From EMP NATURAL JOIN DEPT ON Emp.DeptNo=Dept.DeptNo WHERE City=Location;

Nested Query (A query within another query) Sometimes it is required to join two sub-queries to solve a problem related to the single or multiple table. Nested query contains multiple query in which inner query evaluated first. The general form to write Nested query is- Select. From <Table> Where <Column1> <Operator> (Select Column1 From <Table> [Where <Condition>]) Ex. Find out the name of Employees working in Production Deptt. Select Ename From EMP Where DeptNo = (Select DeptNo From DEPT Where DName= Production ); Ex. Find out the name of Employees who are getting more pay than Ankit. Select Ename From EMP Where Pay >= (Select Pay From EMP WHERE Ename= Ankit );