SlideShare uma empresa Scribd logo
1 de 26
4. Grants, filters, groups and Sort.
• Grants –Accessing someone else’s objects
• Filters – Getting only the necessary rows
• Groups – Aggregating rows to see totals,
counts and other metrics.
• Sort – Order your results as you need.
http://adata.guru
Grants (privileges)
• Accessing data that you don’t own.
http://adata.guru
User/Schema : SCOTT
DEPT
EMP
SAL_GRADE
User/Schema : OE
CUSTOMERS
WAREHOUSES
ORDERS
Select * from oe.customers
Error : No privileges
Select * from oe.customers
Grant select on oe.customers to scott
Grants (contd).
By the end of this section..
1. Each of our 5 users should be able to see each
other’s objects.
2. You should understand what (user) prefixes
mean and why they are important.
3. You should understand what object name
resolution is and how oracle figures out the
name
http://adata.guru
How to check grants
Oracle (data dictionary tables)
select *
From all_tab_privs
Where table_name = 'CUSTOMERS'; --- case matters!
http://adata.guru
SQL Developer:
Shift + F4
Grants Tab
Filters – The where clause
Select [* | column_list ]
From <table_name>
Where <filter_conditions>
Group by <group columns>
Having <filters on groups>
Order by <sort on columns or aggregates>
http://adata.guru
Filters – The where clause
Select [* | column_list ]
From <table_name>
Where ( condition_1 or
condition_2 or
condition_3 …
)
Group by <group columns>
Having <filters on groups>
Order by <sort on columns or aggregates>
http://adata.guru
Where clause : Just the rows you need
Example : Big ticket items
Items priced more than 200 or have a profit (list_price-min_price) of at least 50.
http://adata.guru
Only a few
columns Specific rows
Parts of a filter
<expression> <operator> <expression>
• Sal > 500 (salary > 500)
• Last_name like ‘%Cooper%’
• List_price > 1.2 * min_price
• Cust_last_name in (‘Lemmon’,’Collins’)
http://adata.guru
List of operators
Operator Description example
= Equal to Name = ‘King’
<>, != Not equal to Deptno <> 20
<, <=
>, >=
Less than, less than or equal to
Greater than, greater than or equal to
Sal < 2000
Sal >= 2000
IN One in a list of values Deptno in (10,20)
Like Matches a pattern Name like ‘Scott%’
! Not (of any operator or condition) !(name = ‘King’)
between Between two values Sal between 1000 and 2000
IS NULL A given expression is null Comm is null
IS NOT NULL Given value is not null Comm is not null
http://adata.guru
Groups & Aggregates
Select [* | column_list ]
From <table_name>
Where <filter_conditions>
Group by <group columns>
Having <filters on groups>
Order by <sort on columns or aggregates>
http://adata.guru
Grouping data
http://adata.guru
One row per department instead of one row per employee
Group functions
Aggregate functions return a single result row based on groups of
rows, rather than on single rows. Commonly used in-built functions.
AVG
SUM
COUNT
MIN
MAX
Complete list of aggregate functions for 11g R2:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions003.htm#SQLRF20035
http://adata.guru
When to group data?
• The problem statement or data being requested is at a summary level
– Total sales in a given month for a given product
– Average mileage for a car after 50,000 miles
– Least time for any participant to finish the marathon
• Data returned should be one record per a common attribute
– Product and the first sale date (one record per product)
– Department and number of employees in that dept (one record per
department)
– Running time world record for each race (100m, 200m, 400m) : ( One
record per race type)
http://adata.guru
Examples : Extreme cases
Grouping by no column : one value for all records in the table
Grouping by a unique column like the primary key – almost never useful.
Returns one row per employee as before
http://adata.guru
Common example
One record per grouped column(s):
Number of employees in each country/territory.
http://adata.guru
Grouping column
Aggregate function
Grouping and distinct
Usually used for count, to see the distinct number.
http://adata.guru
Aggregate functions and nulls
Oracle aggregate functions ignore nulls.
Max(sal) => max(sal) where sal is not null
** Important when you look at averages
http://adata.guru
Total / 14
Group by : Common error
http://adata.guru
Each column should be in either
in the group by list or should be
aggregated. In this case, it looks
like we need one row per
(country+marital_status), so we
need to add marital_status to
the group by column to avoid
this error.
Having clause : Filtering on groups
Select [* | column_list ]
From <table_name>
Where <filter_conditions>
Group by <group columns>
Having <filters on groups>
Order by <sort on columns or aggregates>
http://adata.guru
Common scenarios
Requirement usually indicates a grouping column in the requirement.
For example:
1. List of all departments where the average salary in that
deparment is more than 5000
2. products and total sales of items where total sales is more than
5000.
3. Recipes where the total calorie content is less than 1000.
4. Jobs where the average age of the employee is more less than 30.
http://adata.guru
Example
Get the product id and the total sales of all products where the total
sales exceeds 5000. Rename the total sales heading appropriately.
http://adata.guru
Grouped column
Same column/expression as above
Aggregation (can be on an expression)
Good Practices
Use “having” only for aggregate columns
http://adata.guru
This is fine as you only have
access to max(salary) after the
aggregation and your condition is
on the aggregation
Sorting data – Order by Clause.
Select [* | column_list ]
From <table_name>
Where <filter_conditions>
Group by <group columns>
Having <filters on groups>
Order by <sort on columns or aggregates>
http://adata.guru
Sorting data – Syntax.
http://adata.guru
Sorting data – Nulls.
• Nulls have the “highest” value when sorting. You can change this
behavior by specifying “nulls first” or “nulls last”
http://adata.guru
Override
“NULL”
behavior
Default
“NULL”
behavior
Sorting data – Best practises.
1. Sort the data only if you need it. It is an resource-intensive
operation for large data sets.
2. Sort only on the last outer query. The sort in the inner query
usually does not matter.
3. If your application logic needs data to be ordered in a certain
way, sort explicitly. Do not assume the default order that data will
be returned in. Oracle makes no guarantees about the order in
which data is returned unless you specify it explicitly.
4. You can sort when you see the data as part of your analysis. If
your logic doesn’t need it, comment it before deploying the code.
http://adata.guru

Mais conteúdo relacionado

Mais procurados (19)

SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
Sql
SqlSql
Sql
 
Intro to t sql – 3rd session
Intro to t sql – 3rd sessionIntro to t sql – 3rd session
Intro to t sql – 3rd session
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statement
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 
Les05
Les05Les05
Les05
 
Sql select
Sql select Sql select
Sql select
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
intro for sql
intro for sql intro for sql
intro for sql
 
Xslt
XsltXslt
Xslt
 
Introduction to XSLT
Introduction to XSLTIntroduction to XSLT
Introduction to XSLT
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Sql basic things
Sql basic thingsSql basic things
Sql basic things
 

Semelhante a Oracle SQL - Grants, filters, groups and more

Consultas con agrupaci¾n de datos
Consultas con agrupaci¾n de datosConsultas con agrupaci¾n de datos
Consultas con agrupaci¾n de datosCaleb Gutiérrez
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseDBrow Adm
 
e computer notes - Aggregating data using group functions
e computer notes -  Aggregating data using group functionse computer notes -  Aggregating data using group functions
e computer notes - Aggregating data using group functionsecomputernotes
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronEmiel Paasschens
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlnishantdavid9
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11Syed Asrarali
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sqlN.Jagadish Kumar
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimizationVivek Singh
 
Group by clause mod
Group by clause modGroup by clause mod
Group by clause modNitesh Singh
 
Managing user Online Training in IBM Netezza DBA Development by www.etraining...
Managing user Online Training in IBM Netezza DBA Development by www.etraining...Managing user Online Training in IBM Netezza DBA Development by www.etraining...
Managing user Online Training in IBM Netezza DBA Development by www.etraining...Ravikumar Nandigam
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 

Semelhante a Oracle SQL - Grants, filters, groups and more (20)

Module03
Module03Module03
Module03
 
Consultas con agrupaci¾n de datos
Consultas con agrupaci¾n de datosConsultas con agrupaci¾n de datos
Consultas con agrupaci¾n de datos
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Les04
Les04Les04
Les04
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
 
e computer notes - Aggregating data using group functions
e computer notes -  Aggregating data using group functionse computer notes -  Aggregating data using group functions
e computer notes - Aggregating data using group functions
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with Schematron
 
OOW 2012 XML Business Rules Validation Schematron - Emiel Paasschens
OOW 2012  XML Business Rules Validation Schematron - Emiel PaasschensOOW 2012  XML Business Rules Validation Schematron - Emiel Paasschens
OOW 2012 XML Business Rules Validation Schematron - Emiel Paasschens
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
Les18
Les18Les18
Les18
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
Group by clause mod
Group by clause modGroup by clause mod
Group by clause mod
 
Managing user Online Training in IBM Netezza DBA Development by www.etraining...
Managing user Online Training in IBM Netezza DBA Development by www.etraining...Managing user Online Training in IBM Netezza DBA Development by www.etraining...
Managing user Online Training in IBM Netezza DBA Development by www.etraining...
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 

Último

Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsJoseMangaJr1
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...amitlee9823
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...amitlee9823
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfadriantubila
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
ELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptxELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptxolyaivanovalion
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 

Último (20)

Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Anomaly detection and data imputation within time series
Anomaly detection and data imputation within time seriesAnomaly detection and data imputation within time series
Anomaly detection and data imputation within time series
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptx
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
ELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptxELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptx
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Predicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science ProjectPredicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science Project
 

Oracle SQL - Grants, filters, groups and more

  • 1. 4. Grants, filters, groups and Sort. • Grants –Accessing someone else’s objects • Filters – Getting only the necessary rows • Groups – Aggregating rows to see totals, counts and other metrics. • Sort – Order your results as you need. http://adata.guru
  • 2. Grants (privileges) • Accessing data that you don’t own. http://adata.guru User/Schema : SCOTT DEPT EMP SAL_GRADE User/Schema : OE CUSTOMERS WAREHOUSES ORDERS Select * from oe.customers Error : No privileges Select * from oe.customers Grant select on oe.customers to scott
  • 3. Grants (contd). By the end of this section.. 1. Each of our 5 users should be able to see each other’s objects. 2. You should understand what (user) prefixes mean and why they are important. 3. You should understand what object name resolution is and how oracle figures out the name http://adata.guru
  • 4. How to check grants Oracle (data dictionary tables) select * From all_tab_privs Where table_name = 'CUSTOMERS'; --- case matters! http://adata.guru SQL Developer: Shift + F4 Grants Tab
  • 5. Filters – The where clause Select [* | column_list ] From <table_name> Where <filter_conditions> Group by <group columns> Having <filters on groups> Order by <sort on columns or aggregates> http://adata.guru
  • 6. Filters – The where clause Select [* | column_list ] From <table_name> Where ( condition_1 or condition_2 or condition_3 … ) Group by <group columns> Having <filters on groups> Order by <sort on columns or aggregates> http://adata.guru
  • 7. Where clause : Just the rows you need Example : Big ticket items Items priced more than 200 or have a profit (list_price-min_price) of at least 50. http://adata.guru Only a few columns Specific rows
  • 8. Parts of a filter <expression> <operator> <expression> • Sal > 500 (salary > 500) • Last_name like ‘%Cooper%’ • List_price > 1.2 * min_price • Cust_last_name in (‘Lemmon’,’Collins’) http://adata.guru
  • 9. List of operators Operator Description example = Equal to Name = ‘King’ <>, != Not equal to Deptno <> 20 <, <= >, >= Less than, less than or equal to Greater than, greater than or equal to Sal < 2000 Sal >= 2000 IN One in a list of values Deptno in (10,20) Like Matches a pattern Name like ‘Scott%’ ! Not (of any operator or condition) !(name = ‘King’) between Between two values Sal between 1000 and 2000 IS NULL A given expression is null Comm is null IS NOT NULL Given value is not null Comm is not null http://adata.guru
  • 10. Groups & Aggregates Select [* | column_list ] From <table_name> Where <filter_conditions> Group by <group columns> Having <filters on groups> Order by <sort on columns or aggregates> http://adata.guru
  • 11. Grouping data http://adata.guru One row per department instead of one row per employee
  • 12. Group functions Aggregate functions return a single result row based on groups of rows, rather than on single rows. Commonly used in-built functions. AVG SUM COUNT MIN MAX Complete list of aggregate functions for 11g R2: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions003.htm#SQLRF20035 http://adata.guru
  • 13. When to group data? • The problem statement or data being requested is at a summary level – Total sales in a given month for a given product – Average mileage for a car after 50,000 miles – Least time for any participant to finish the marathon • Data returned should be one record per a common attribute – Product and the first sale date (one record per product) – Department and number of employees in that dept (one record per department) – Running time world record for each race (100m, 200m, 400m) : ( One record per race type) http://adata.guru
  • 14. Examples : Extreme cases Grouping by no column : one value for all records in the table Grouping by a unique column like the primary key – almost never useful. Returns one row per employee as before http://adata.guru
  • 15. Common example One record per grouped column(s): Number of employees in each country/territory. http://adata.guru Grouping column Aggregate function
  • 16. Grouping and distinct Usually used for count, to see the distinct number. http://adata.guru
  • 17. Aggregate functions and nulls Oracle aggregate functions ignore nulls. Max(sal) => max(sal) where sal is not null ** Important when you look at averages http://adata.guru Total / 14
  • 18. Group by : Common error http://adata.guru Each column should be in either in the group by list or should be aggregated. In this case, it looks like we need one row per (country+marital_status), so we need to add marital_status to the group by column to avoid this error.
  • 19. Having clause : Filtering on groups Select [* | column_list ] From <table_name> Where <filter_conditions> Group by <group columns> Having <filters on groups> Order by <sort on columns or aggregates> http://adata.guru
  • 20. Common scenarios Requirement usually indicates a grouping column in the requirement. For example: 1. List of all departments where the average salary in that deparment is more than 5000 2. products and total sales of items where total sales is more than 5000. 3. Recipes where the total calorie content is less than 1000. 4. Jobs where the average age of the employee is more less than 30. http://adata.guru
  • 21. Example Get the product id and the total sales of all products where the total sales exceeds 5000. Rename the total sales heading appropriately. http://adata.guru Grouped column Same column/expression as above Aggregation (can be on an expression)
  • 22. Good Practices Use “having” only for aggregate columns http://adata.guru This is fine as you only have access to max(salary) after the aggregation and your condition is on the aggregation
  • 23. Sorting data – Order by Clause. Select [* | column_list ] From <table_name> Where <filter_conditions> Group by <group columns> Having <filters on groups> Order by <sort on columns or aggregates> http://adata.guru
  • 24. Sorting data – Syntax. http://adata.guru
  • 25. Sorting data – Nulls. • Nulls have the “highest” value when sorting. You can change this behavior by specifying “nulls first” or “nulls last” http://adata.guru Override “NULL” behavior Default “NULL” behavior
  • 26. Sorting data – Best practises. 1. Sort the data only if you need it. It is an resource-intensive operation for large data sets. 2. Sort only on the last outer query. The sort in the inner query usually does not matter. 3. If your application logic needs data to be ordered in a certain way, sort explicitly. Do not assume the default order that data will be returned in. Oracle makes no guarantees about the order in which data is returned unless you specify it explicitly. 4. You can sort when you see the data as part of your analysis. If your logic doesn’t need it, comment it before deploying the code. http://adata.guru