SlideShare una empresa de Scribd logo
1 de 17
Technical Skills Enhancement – PL/SQL Best
practices
Objectives
At the end of this training, you will be able to:
• Understand best practices in SQL and PL/SQL
Agenda
– Indexes
– Logical tuning
– Benefits of using exists
– Avoid distinct
– Know your data, know your query
– Check code behind views
PL/SQL Tuning for performance- Indexes
• Indexes help Oracle find rows easily as rowid references are stored in
Indexes.
• Similar to reading from a book
Guidelines for creating indexes
• Do create indexes on
– Columns frequently used in WHERE clause
– Columns used in joins
• Avoid creating indexes on
– Columns whose data is updated frequently
Indexes – not too many, not too few
Create indexes only when it is absolutely necessary. While indexes aid in improving the
performance of queries, too many indexes on a table could drastically slow down the
inserts and updates to the table.
PL/SQL Tuning for performance- Indexes
Note: Although it is not a standard practice to create indexes on platform tables (starting
with SI_), sometimes when performance issues are seen it might require an index to be
created. In this case, ensure that care is taken to recreate the indexes after each
platform upgrade.
Guidelines for indexes
• When creating composite indexes, the order of columns is important. The
column that is more frequently queried must be put first. If the columns have a
parent-child relation, then the parent column should come first.
Script : IndexBestPractices.sql
– Missing leading index column in join  Can’t use index
• Eg: Composite index on STATE, CITY
where state = 'TX' [Index used]
where city = 'DALLAS' [Index Not Used]
where state = 'TX' and city = 'DALLAS' [Index Used]
PL/SQL Tuning for performance- Indexes
– NOT, != and <> disable index use
where state not in ('TX', 'FL','OH')[Index Not used]
where state != 'TX' [Index Not used]
  Instead try to use IN or = whenever possible
– NULL value references can never use indexes
where state IS NULL [Index Not used]
where state IS NOT NULL [Index Not used]
– Expression references can never use indexes
  where substr(city,1,3) = 'DAL' [Index Not used]
where city like 'DAL%' [Index Used]
where city || state = 'DALLASTX' [Index Not used]
where salary * 12 >= 24000 [Index Not used]
where salary >= 2000 [Index Used]
PL/SQL Tuning for performance- Indexes
• Avoid using functions on table columns in WHERE clause, instead use 
local variables. 
• Functions on indexed columns prevent Index scans, unless there is a 
function based index on the column.
• DO NOT: “where trunc(created_date) > …”
• BETTER: “where created_date > “
• DO NOT: select * from accounts where account_status
= get_system_constants(‘SUSPENDED STATUS’);
• BETTER: l_suspended_status :=
get_system_constants(‘SUSPENDED STATUS’);
select * from accounts where account_status =
l_suspended_status;
PL/SQL Tuning for performance – The benefits of using EXISTS
Lesson Learned
In a query joining multiple tables if some tables are not represented in the SELECT clause 
(ie : columns from those tables are not in SELECT clause) those tables can be moved from 
JOIN to EXISTS.
EXISTS is always better than using JOIN(in some cases) or IN. This is because once 
Oracle finds the first record that fulfills the subquery in the EXISTS clause, it does not 
bother to check the remaining records.
Consider the below query- 
SELECT user_name
FROM users
WHERE user_id IN (SELECT user_id
FROM user_org_roles)
FOR EACH user_id IN USERS
FOR EACH user_id IN USER_ORG_ROLES
IF USERS.user_id = USER_ORG_ROLES.user_id THEN
TRUE;
END IF;
END LOOP;
END LOOP;
100 users x 1000 org roles = 100,000
comparisons!
PL/SQL Tuning for performance – The benefits of using EXISTS
Rewriting using EXISTS
SELECT a.user_name
FROM users a
WHERE EXISTS (SELECT b.user_id
FROM user_org_roles b
WHERE b.user_id = a.user_id)
FOR EACH user_id IN USERS
IF user_id EXISTS in USER_ORG_ROLES THEN
RETURN row;
END IF;
END LOOP;
100 users = 100 comparisons!
PL/SQL Tuning for performance – Avoid DISTINCT
Reqmt : Users in organization 100000
SELECT u.user_id
, u.user_name
FROM users u
, user_org_roles r
WHERE u.user_id = r.user_id
AND r.org_id = 100000;
USER_ID USER_NAME
------------ -------------------------------
100001 JOHN DOE
100001 JOHN DOE
Lazy developer approach
SELECT DISTINCT
u.user_id
, u.user_name
FROM users u
, user_org_roles r
WHERE u.user_id = r.user_id
AND r.org_id = 100000;
USER_ID USER_NAME
------------ -------------------------------
100001 JOHN DOE
PL/SQL Tuning for performance –Avoid DISTINCT
• DISTINCT
– Fetch All Rows satisfying the join
– Sort and Filter duplicate values
– Uses TEMP tablespace if resultset is large
• Better way to fetch unique values using EXISTS
SELECT u.user_id
, u.user_name
FROM users u
WHERE EXISTS ( SELECT 1
FROM user_org_roles r
WHERE u.user_id = r.user_id
AND r.org_id = 100000
)
SQL Tuning – HAVING vs WHERE
• Use HAVING only to filter on aggregate functions (count, sum, avg etc)
• Use WHERE to filter on table columns
Script : SQLBestPractices.sql
Least Efficient:
The statement below is a syntactically correct statement. It will produce
the expected result. However filter is done after all the sorting and
counting is complete.
SELECT job, city, state, COUNT(empno) FROM city_data
GROUP BY job, city, state
HAVING job='CLERK';
Correct Usage
SELECT job, city, state, COUNT(empno) FROM city_data
WHERE job='CLERK'
GROUP BY job, city, state;
SQL Tuning – UNION vs UNION ALL
• The UNION operation sorts the result set to eliminate duplicate rows
• UNION ALL includes duplicate rows and does not require a sort.
• Unless you require that the duplicate rows be eliminated, or you are certain
that the member queries do not produce duplicate data, use UNION ALL
SELECT empno, ename, deptno FROM emp_10
UNION
SELECT empno, ename, deptno FROM emp_20;
--Better performance
SELECT empno, ename, deptno FROM emp_10
UNION ALL
SELECT empno, ename, deptno FROM emp_20;
PL/SQL coding guidelines - General
– Use equality first.
– Use range operators only where equality does not apply.
– Avoid use of negatives in the form of “ != ” or ” NOT”.
– Avoid LIKE pattern matching.
– Try to retrieve specific rows and in small numbers.
– Filter from large tables first to reduce rows joined. Retrieve tables
in order from the most highly filtered table downwards; preferably
the largest table has the most filtering applied.
– The most highly filtered table is the table having the smallest
percentage of its rows retrieved, preferably the largest table.
– Use indexes wherever possible except for very small tables.
– Let the Optimizer do its job.
PL/SQL coding guidelines - General
• Modularize with top-down design; keep executable sections small and
easy to read
• Modularize to reduce complexity, make your tasks manageable, and
make your resulting code maintainable
• Avoid multiple RETURN statements in executable section, instead
save values in variables & return the variable
• Avoid lengthy sections of code, and spaghetti code
• Code sections should be self documenting
• Avoid any code redundancies
PL/SQL Tuning for performance
• There will always be many ways to write a query or PL/SQL program
to fulfill a requirement.
• By applying the above concepts and using iterative methods you can
figure out which method yields THE BEST performance.
Thank You
Feedback, Questions, Discussion

Más contenido relacionado

La actualidad más candente

Non relational databases-no sql
Non relational databases-no sqlNon relational databases-no sql
Non relational databases-no sqlRam kumar
 
Architecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres ClusterArchitecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres ClusterAshnikbiz
 
MariaDB ColumnStore
MariaDB ColumnStoreMariaDB ColumnStore
MariaDB ColumnStoreMariaDB plc
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptChien Chung Shen
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introductionPooyan Mehrparvar
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresqlbotsplash.com
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to CassandraGokhan Atil
 
Scaling paypal workloads with oracle rac ss
Scaling paypal workloads with oracle rac ssScaling paypal workloads with oracle rac ss
Scaling paypal workloads with oracle rac ssAnil Nair
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQLVikash Sharma
 
Lect 08 materialized view
Lect 08 materialized viewLect 08 materialized view
Lect 08 materialized viewBilal khan
 

La actualidad más candente (20)

Non relational databases-no sql
Non relational databases-no sqlNon relational databases-no sql
Non relational databases-no sql
 
Architecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres ClusterArchitecture for building scalable and highly available Postgres Cluster
Architecture for building scalable and highly available Postgres Cluster
 
MariaDB ColumnStore
MariaDB ColumnStoreMariaDB ColumnStore
MariaDB ColumnStore
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning Concept
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introduction
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
NoSQL databases
NoSQL databasesNoSQL databases
NoSQL databases
 
Introduction to NoSQL
Introduction to NoSQLIntroduction to NoSQL
Introduction to NoSQL
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresql
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to Cassandra
 
Sql fundamentals
Sql fundamentalsSql fundamentals
Sql fundamentals
 
Scaling paypal workloads with oracle rac ss
Scaling paypal workloads with oracle rac ssScaling paypal workloads with oracle rac ss
Scaling paypal workloads with oracle rac ss
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Lect 08 materialized view
Lect 08 materialized viewLect 08 materialized view
Lect 08 materialized view
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 

Destacado

PL/SQL Code for Sample Projects
PL/SQL Code for Sample ProjectsPL/SQL Code for Sample Projects
PL/SQL Code for Sample Projectsjwjablonski
 
A green solution to solve a race condition problem
A green solution to solve a race condition problemA green solution to solve a race condition problem
A green solution to solve a race condition problemKai Zhou
 
PLSQL Standards and Best Practices
PLSQL Standards and Best PracticesPLSQL Standards and Best Practices
PLSQL Standards and Best PracticesAlwyn D'Souza
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answersvijaybusu
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handlingSmitha Padmanabhan
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questionsPyadav010186
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 
RESTful web services using java and spring
RESTful web services using java and springRESTful web services using java and spring
RESTful web services using java and springMuhammad Junaid Ansari
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingJohn Beresniewicz
 
Oracle SQL Interview Questions for Freshers
Oracle SQL Interview Questions for FreshersOracle SQL Interview Questions for Freshers
Oracle SQL Interview Questions for FreshersDTecH It Education
 
Anchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typeAnchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typedhruv patel
 
Animation: The Basic Skills
Animation:  The Basic SkillsAnimation:  The Basic Skills
Animation: The Basic Skillswalkers
 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practicesAnkita Mahajan
 
Oracl DBA lab manual
Oracl DBA lab manualOracl DBA lab manual
Oracl DBA lab manualAbdulla Shaik
 
APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !Roel Hartman
 

Destacado (20)

PL/SQL Code for Sample Projects
PL/SQL Code for Sample ProjectsPL/SQL Code for Sample Projects
PL/SQL Code for Sample Projects
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
A green solution to solve a race condition problem
A green solution to solve a race condition problemA green solution to solve a race condition problem
A green solution to solve a race condition problem
 
PLSQL Standards and Best Practices
PLSQL Standards and Best PracticesPLSQL Standards and Best Practices
PLSQL Standards and Best Practices
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handling
 
Oracle Complete Interview Questions
Oracle Complete Interview QuestionsOracle Complete Interview Questions
Oracle Complete Interview Questions
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questions
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
RESTful web services using java and spring
RESTful web services using java and springRESTful web services using java and spring
RESTful web services using java and spring
 
Plsql programs
Plsql programsPlsql programs
Plsql programs
 
Plsql Ref
Plsql RefPlsql Ref
Plsql Ref
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL Programming
 
Oracle SQL Interview Questions for Freshers
Oracle SQL Interview Questions for FreshersOracle SQL Interview Questions for Freshers
Oracle SQL Interview Questions for Freshers
 
Anchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data typeAnchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data type
 
Animation: The Basic Skills
Animation:  The Basic SkillsAnimation:  The Basic Skills
Animation: The Basic Skills
 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practices
 
AMIS - Can collections speed up your PL/SQL?
AMIS - Can collections speed up your PL/SQL?AMIS - Can collections speed up your PL/SQL?
AMIS - Can collections speed up your PL/SQL?
 
Oracl DBA lab manual
Oracl DBA lab manualOracl DBA lab manual
Oracl DBA lab manual
 
APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !
 

Similar a Oracle SQL, PL/SQL best practices

Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsNirav Shah
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ICarlos Oliveira
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sqlN.Jagadish Kumar
 
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
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorialbunny0143
 
Pl sql best practices document
Pl sql best practices documentPl sql best practices document
Pl sql best practices documentAshwani Pandey
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserverlochaaaa
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Alex Zaballa
 
Performance tuning
Performance tuningPerformance tuning
Performance tuningami111
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
Sql performance vesl technologies
Sql performance vesl technologiesSql performance vesl technologies
Sql performance vesl technologiesSuresh Mishra
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Krishan Singh
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
Sydney Oracle Meetup - indexes
Sydney Oracle Meetup - indexesSydney Oracle Meetup - indexes
Sydney Oracle Meetup - indexespaulguerin
 

Similar a Oracle SQL, PL/SQL best practices (20)

Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorial
 
Pl sql best practices document
Pl sql best practices documentPl sql best practices document
Pl sql best practices document
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Sql performance vesl technologies
Sql performance vesl technologiesSql performance vesl technologies
Sql performance vesl technologies
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager Db2 sql tuning and bmc catalog manager
Db2 sql tuning and bmc catalog manager
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
Sydney Oracle Meetup - indexes
Sydney Oracle Meetup - indexesSydney Oracle Meetup - indexes
Sydney Oracle Meetup - indexes
 

Último

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 

Último (20)

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 

Oracle SQL, PL/SQL best practices

  • 1. Technical Skills Enhancement – PL/SQL Best practices
  • 2. Objectives At the end of this training, you will be able to: • Understand best practices in SQL and PL/SQL
  • 3. Agenda – Indexes – Logical tuning – Benefits of using exists – Avoid distinct – Know your data, know your query – Check code behind views
  • 4. PL/SQL Tuning for performance- Indexes • Indexes help Oracle find rows easily as rowid references are stored in Indexes. • Similar to reading from a book Guidelines for creating indexes • Do create indexes on – Columns frequently used in WHERE clause – Columns used in joins • Avoid creating indexes on – Columns whose data is updated frequently Indexes – not too many, not too few Create indexes only when it is absolutely necessary. While indexes aid in improving the performance of queries, too many indexes on a table could drastically slow down the inserts and updates to the table.
  • 5. PL/SQL Tuning for performance- Indexes Note: Although it is not a standard practice to create indexes on platform tables (starting with SI_), sometimes when performance issues are seen it might require an index to be created. In this case, ensure that care is taken to recreate the indexes after each platform upgrade. Guidelines for indexes • When creating composite indexes, the order of columns is important. The column that is more frequently queried must be put first. If the columns have a parent-child relation, then the parent column should come first. Script : IndexBestPractices.sql – Missing leading index column in join  Can’t use index • Eg: Composite index on STATE, CITY where state = 'TX' [Index used] where city = 'DALLAS' [Index Not Used] where state = 'TX' and city = 'DALLAS' [Index Used]
  • 6. PL/SQL Tuning for performance- Indexes – NOT, != and <> disable index use where state not in ('TX', 'FL','OH')[Index Not used] where state != 'TX' [Index Not used]   Instead try to use IN or = whenever possible – NULL value references can never use indexes where state IS NULL [Index Not used] where state IS NOT NULL [Index Not used] – Expression references can never use indexes   where substr(city,1,3) = 'DAL' [Index Not used] where city like 'DAL%' [Index Used] where city || state = 'DALLASTX' [Index Not used] where salary * 12 >= 24000 [Index Not used] where salary >= 2000 [Index Used]
  • 7. PL/SQL Tuning for performance- Indexes • Avoid using functions on table columns in WHERE clause, instead use  local variables.  • Functions on indexed columns prevent Index scans, unless there is a  function based index on the column. • DO NOT: “where trunc(created_date) > …” • BETTER: “where created_date > “ • DO NOT: select * from accounts where account_status = get_system_constants(‘SUSPENDED STATUS’); • BETTER: l_suspended_status := get_system_constants(‘SUSPENDED STATUS’); select * from accounts where account_status = l_suspended_status;
  • 8. PL/SQL Tuning for performance – The benefits of using EXISTS Lesson Learned In a query joining multiple tables if some tables are not represented in the SELECT clause  (ie : columns from those tables are not in SELECT clause) those tables can be moved from  JOIN to EXISTS. EXISTS is always better than using JOIN(in some cases) or IN. This is because once  Oracle finds the first record that fulfills the subquery in the EXISTS clause, it does not  bother to check the remaining records. Consider the below query-  SELECT user_name FROM users WHERE user_id IN (SELECT user_id FROM user_org_roles) FOR EACH user_id IN USERS FOR EACH user_id IN USER_ORG_ROLES IF USERS.user_id = USER_ORG_ROLES.user_id THEN TRUE; END IF; END LOOP; END LOOP; 100 users x 1000 org roles = 100,000 comparisons!
  • 9. PL/SQL Tuning for performance – The benefits of using EXISTS Rewriting using EXISTS SELECT a.user_name FROM users a WHERE EXISTS (SELECT b.user_id FROM user_org_roles b WHERE b.user_id = a.user_id) FOR EACH user_id IN USERS IF user_id EXISTS in USER_ORG_ROLES THEN RETURN row; END IF; END LOOP; 100 users = 100 comparisons!
  • 10. PL/SQL Tuning for performance – Avoid DISTINCT Reqmt : Users in organization 100000 SELECT u.user_id , u.user_name FROM users u , user_org_roles r WHERE u.user_id = r.user_id AND r.org_id = 100000; USER_ID USER_NAME ------------ ------------------------------- 100001 JOHN DOE 100001 JOHN DOE Lazy developer approach SELECT DISTINCT u.user_id , u.user_name FROM users u , user_org_roles r WHERE u.user_id = r.user_id AND r.org_id = 100000; USER_ID USER_NAME ------------ ------------------------------- 100001 JOHN DOE
  • 11. PL/SQL Tuning for performance –Avoid DISTINCT • DISTINCT – Fetch All Rows satisfying the join – Sort and Filter duplicate values – Uses TEMP tablespace if resultset is large • Better way to fetch unique values using EXISTS SELECT u.user_id , u.user_name FROM users u WHERE EXISTS ( SELECT 1 FROM user_org_roles r WHERE u.user_id = r.user_id AND r.org_id = 100000 )
  • 12. SQL Tuning – HAVING vs WHERE • Use HAVING only to filter on aggregate functions (count, sum, avg etc) • Use WHERE to filter on table columns Script : SQLBestPractices.sql Least Efficient: The statement below is a syntactically correct statement. It will produce the expected result. However filter is done after all the sorting and counting is complete. SELECT job, city, state, COUNT(empno) FROM city_data GROUP BY job, city, state HAVING job='CLERK'; Correct Usage SELECT job, city, state, COUNT(empno) FROM city_data WHERE job='CLERK' GROUP BY job, city, state;
  • 13. SQL Tuning – UNION vs UNION ALL • The UNION operation sorts the result set to eliminate duplicate rows • UNION ALL includes duplicate rows and does not require a sort. • Unless you require that the duplicate rows be eliminated, or you are certain that the member queries do not produce duplicate data, use UNION ALL SELECT empno, ename, deptno FROM emp_10 UNION SELECT empno, ename, deptno FROM emp_20; --Better performance SELECT empno, ename, deptno FROM emp_10 UNION ALL SELECT empno, ename, deptno FROM emp_20;
  • 14. PL/SQL coding guidelines - General – Use equality first. – Use range operators only where equality does not apply. – Avoid use of negatives in the form of “ != ” or ” NOT”. – Avoid LIKE pattern matching. – Try to retrieve specific rows and in small numbers. – Filter from large tables first to reduce rows joined. Retrieve tables in order from the most highly filtered table downwards; preferably the largest table has the most filtering applied. – The most highly filtered table is the table having the smallest percentage of its rows retrieved, preferably the largest table. – Use indexes wherever possible except for very small tables. – Let the Optimizer do its job.
  • 15. PL/SQL coding guidelines - General • Modularize with top-down design; keep executable sections small and easy to read • Modularize to reduce complexity, make your tasks manageable, and make your resulting code maintainable • Avoid multiple RETURN statements in executable section, instead save values in variables & return the variable • Avoid lengthy sections of code, and spaghetti code • Code sections should be self documenting • Avoid any code redundancies
  • 16. PL/SQL Tuning for performance • There will always be many ways to write a query or PL/SQL program to fulfill a requirement. • By applying the above concepts and using iterative methods you can figure out which method yields THE BEST performance.