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

MariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialMariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialColin Charles
 
Oracle dba 12c training syllabus
Oracle dba 12c training syllabusOracle dba 12c training syllabus
Oracle dba 12c training syllabusMonster Courses
 
Optimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversOptimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversScyllaDB
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsCarlos Sierra
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaEdureka!
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joinsredro
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Aaron Shilo
 
MySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsMySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsOSSCube
 
SQL Server Database Migration
SQL Server Database MigrationSQL Server Database Migration
SQL Server Database MigrationZeba Ansari
 
How a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBHow a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBCarlos Sierra
 
Dd and atomic ddl pl17 dublin
Dd and atomic ddl pl17 dublinDd and atomic ddl pl17 dublin
Dd and atomic ddl pl17 dublinStåle Deraas
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVERDarwin Durand
 
DB1 Unidad 2: Modelo ER y modelo relacional
DB1 Unidad 2: Modelo ER y modelo relacionalDB1 Unidad 2: Modelo ER y modelo relacional
DB1 Unidad 2: Modelo ER y modelo relacionalFranklin Parrales Bravo
 

La actualidad más candente (20)

Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
MariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialMariaDB 10: The Complete Tutorial
MariaDB 10: The Complete Tutorial
 
Oracle dba 12c training syllabus
Oracle dba 12c training syllabusOracle dba 12c training syllabus
Oracle dba 12c training syllabus
 
Optimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database DriversOptimizing Performance in Rust for Low-Latency Database Drivers
Optimizing Performance in Rust for Low-Latency Database Drivers
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | Edureka
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joins
 
Oracle Tablespace - Basic
Oracle Tablespace - BasicOracle Tablespace - Basic
Oracle Tablespace - Basic
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
MySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsMySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 Tips
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
SQL Server Database Migration
SQL Server Database MigrationSQL Server Database Migration
SQL Server Database Migration
 
Postgresql
PostgresqlPostgresql
Postgresql
 
How a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBHow a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DB
 
Dd and atomic ddl pl17 dublin
Dd and atomic ddl pl17 dublinDd and atomic ddl pl17 dublin
Dd and atomic ddl pl17 dublin
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVER
 
DB1 Unidad 2: Modelo ER y modelo relacional
DB1 Unidad 2: Modelo ER y modelo relacionalDB1 Unidad 2: Modelo ER y modelo relacional
DB1 Unidad 2: Modelo ER y modelo relacional
 

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

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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.