SlideShare a Scribd company logo
PostgreSQL
Advanced Queries
COMELABS - MARGONDA DEPOK
14 NOPEMBER 2015
About Me
• Editor PojokProgrammer.net
• Writers welcome!
• CEO BiruniLabs
• Trainers welcome!
• CEO Cronos Studio
• Developers welcome!
WhatYou Need
• Laptop or Computer
• PostgreSQL Installed
• SQL Interface
• HeidiSQL
• SQLyog
• phpMyAdmin
• Whatever.....
• Your Brain 
SQL Basics
History of PostgreSQL
• INGRES, Berkeley 1982
• POSTGRES, Berkeley 1985
• POSTGRES v1, 1989
• PostQUEL, 1990
•PostgreSQL 6.0 (1995)
• Initial release
•PostgreSQL 7.0 (2000)
• SQL92 compliance
•PostgreSQL 8.0 (2005)
• Multi-Platform support
• Analytical Function
support
•PostgreSQL 9.0 (2010)
• Built-in Replication
• JSON datatype support
Rule of Thumb
From Tom Kyte (Oracle Evangelist)
1. Use single SQL statement whenever
possible
2. Use PL/SQL or Stored Procedure
3. Use Java (or other programming
language)
4. Rethink why you want to do it
(refine your approach)
SQL Anatomy
• Statements
• Queries
• Clauses
• Predicates
• Expressions
ChangeYour Mindset!
• Apa yang akan kalian lakukan jika mendapatkan tugas seperti di
bawah ini
• Tampilkan angka 1 sampai dengan 100, namun
setiap kelipatan 3 ubah angkanya menjadi kata
Rumah, setiap kelipatan 5 ubah angkanya menjadi
kata Sakit, dan setiap kelipatan 15 ubah angkanya
menjadi kata Rumah Sakit.
SELECT
SELECT b,d,e,h
FROM some_table ;
SELECT *
FROM some_table
WHERE x IN (3,5,6,8) ;
SELECT b,d,e,h
FROM some_table
WHERE x IN (3,5,6,8) ;
JOIN vs UNION
JOIN
======
SELECT *
FROM A JOIN B ON 1=1
UNION (UNION ALL)
======
SELECT * FROM A
UNION ALL
SELECT * FROM B
JOIN
• INNER JOIN (JOIN)
• LEFT OUTER JOIN (LEFT JOIN)
• RIGHT OUTER JOIN (RIGHT JOIN)
• FULL OUTER JOIN (FULLJOIN)
• LEFT JOIN EXCLUDING INNER JOIN (LEFT EXCLUDING
JOIN)
• RIGHT JOIN EXCLUDING INNER JOIN (RIGHT EXCLUDING
JOIN)
• OUTER JOIN EXCLUDING INNER JOIN (OUTER
EXCLUDINGJOIN)
Visual Representation
ChangeYour Mindset!
• Apa yang akan kalian lakukan jika diminta membuat output
seperti di bawah ini
Tabel A
ID Description
1 SUV
2 Sedan
3 Truk
4 Bus
5 MPV
Tabel B
A_ID Description
1 Toyota Fortuner
1 BMW X5
2 ToyotaVios
2 Honda City
5 Dahihatsu GranMax
ID Description Jumlah
1 SUV 2
2 Sedan 2
3 Truk 0
4 Bus 0
5 MPV 1
Ready for Advanced Queries?
Common Table Expression
• Standard SQL feature
• Allows you to split a query statement into distinct
parts
• Results of each part will appear as a table
• More maintainable than subqueries
Hierarchical Queries
• Fixed depth hierarchical data can be solved using
simple JOINs
• CTE allows recursive query
• CTE can process data as hierarchical
• CTE can process arbitrarily deep hierarchies with
just one query
Hierarchical Query using CTE
Aggregates and Window Functions
• GROUP BY lets you calculate aggregates of data over a single or
multiple columns in a result set.
• GROUP BY can only aggregate over a single grouping
• GROUP BY only return aggregated data, detail data is not
preserved
• Window functions make it possible
• Indicated by OVER Clause
• ROW_NUMBER() OVER()
• SUM() OVER()
• COUNT() OVER()
• MAX() OVER()
• MIN() OVER()
• AVG() OVER()
Windowing Function
Pivoting data
• Sometimes it’s nice to be able to pivot data in a
properly normalized data model, so that repeating
groups of related entities are folded into parent
entity as columns.
• Pivoting is very useful reporting purposes and ad-
hoc queries.
• PostgreSQL can handle pivoting data using
• Subqueries and Arrays
• UsingCASE clause
Pivot Sample
Other Advanced PostgreSQL
• JSON built-in support
• Pattern matching. Regular expression matching is
supported
• Geolocation queries. PostGIS extension adds
comprehensive support for managing and querying
geospatial data
• Partitioning
• Replication
ThankYou
QUESTIONS AND ANSWERS

More Related Content

PDF
The Parquet Format and Performance Optimization Opportunities
PDF
Deep dive to PostgreSQL Indexes
PDF
Linux tuning to improve PostgreSQL performance
PDF
PostgreSQL: Advanced indexing
PDF
InnoDB Performance Optimisation
PDF
PostgreSQL Extensions: A deeper look
PDF
Introduction VAUUM, Freezing, XID wraparound
PDF
PostgreSQL WAL for DBAs
The Parquet Format and Performance Optimization Opportunities
Deep dive to PostgreSQL Indexes
Linux tuning to improve PostgreSQL performance
PostgreSQL: Advanced indexing
InnoDB Performance Optimisation
PostgreSQL Extensions: A deeper look
Introduction VAUUM, Freezing, XID wraparound
PostgreSQL WAL for DBAs

What's hot (20)

PDF
Apache Arrow Flight: A New Gold Standard for Data Transport
PDF
Solving PostgreSQL wicked problems
PDF
Tricks every ClickHouse designer should know, by Robert Hodges, Altinity CEO
PDF
Postgres Vision 2018: WAL: Everything You Want to Know
 
PDF
Introduction to MongoDB
PDF
Distributed Databases Deconstructed: CockroachDB, TiDB and YugaByte DB
PDF
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...
PPTX
Optimizing queries MySQL
PDF
MyRocks Deep Dive
KEY
PostgreSQL
PDF
MySQL 상태 메시지 분석 및 활용
PPTX
Getting started with postgresql
PDF
PostgreSQL: XID周回問題に潜む別の問題
PPTX
がっつりMongoDB事例紹介
PDF
Análise de performance usando as estatísticas do PostgreSQL
PPTX
Facebook's TAO & Unicorn data storage and search platforms
PPTX
BigQuery walk through.pptx
PDF
PostgreSql query planning and tuning
PDF
Apache Iceberg - A Table Format for Hige Analytic Datasets
PDF
PostgreSQL Performance Tuning
Apache Arrow Flight: A New Gold Standard for Data Transport
Solving PostgreSQL wicked problems
Tricks every ClickHouse designer should know, by Robert Hodges, Altinity CEO
Postgres Vision 2018: WAL: Everything You Want to Know
 
Introduction to MongoDB
Distributed Databases Deconstructed: CockroachDB, TiDB and YugaByte DB
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...
Optimizing queries MySQL
MyRocks Deep Dive
PostgreSQL
MySQL 상태 메시지 분석 및 활용
Getting started with postgresql
PostgreSQL: XID周回問題に潜む別の問題
がっつりMongoDB事例紹介
Análise de performance usando as estatísticas do PostgreSQL
Facebook's TAO & Unicorn data storage and search platforms
BigQuery walk through.pptx
PostgreSql query planning and tuning
Apache Iceberg - A Table Format for Hige Analytic Datasets
PostgreSQL Performance Tuning
Ad

Viewers also liked (11)

PDF
PostgreSQL: Advanced features in practice
PPTX
Do IT with SQL
PPTX
Formation LPIC-1_SysArch
PDF
LPI Academy Presents Linux Essentials - A Deep Dive
PDF
Deep dive into PostgreSQL statistics.
PDF
GPGPU Accelerates PostgreSQL (English)
PDF
12-Step Program for Scaling Web Applications on PostgreSQL
PDF
Lessons PostgreSQL learned from commercial databases, and didn’t
PDF
PostgreSQL + ZFS best practices
PDF
Full Text Search In PostgreSQL
PDF
5 Steps to PostgreSQL Performance
PostgreSQL: Advanced features in practice
Do IT with SQL
Formation LPIC-1_SysArch
LPI Academy Presents Linux Essentials - A Deep Dive
Deep dive into PostgreSQL statistics.
GPGPU Accelerates PostgreSQL (English)
12-Step Program for Scaling Web Applications on PostgreSQL
Lessons PostgreSQL learned from commercial databases, and didn’t
PostgreSQL + ZFS best practices
Full Text Search In PostgreSQL
5 Steps to PostgreSQL Performance
Ad

Similar to PostgreSQL Advanced Queries (20)

PPTX
Modern sql
ODP
Meet the-other-elephant
PPTX
Sql analytic queries tips
PDF
JDD 2016 - Tomasz Borek - DB for next project? Why, Postgres, of course
PDF
PostgreSQL (2) by Aswin
PDF
Techday2010 Postgresql9
PDF
Why PostgreSQL for Analytics Infrastructure (DW)?
PPTX
How to Implement Distributed Data Store
PDF
dbms.pdf
PDF
Do It With SQL - Journey to the Center of Database Worlds
PDF
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
PPT
Object Relational Database Management System
PDF
Modern sql
PDF
Really Big Elephants: PostgreSQL DW
PDF
Pg 95 new capabilities
PPTX
Introduction to PostgreSQL
PDF
20080424 Cdb2008 Postgresql News Bartunov
PDF
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
PDF
PostgreSQL: Data analysis and analytics
PDF
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Modern sql
Meet the-other-elephant
Sql analytic queries tips
JDD 2016 - Tomasz Borek - DB for next project? Why, Postgres, of course
PostgreSQL (2) by Aswin
Techday2010 Postgresql9
Why PostgreSQL for Analytics Infrastructure (DW)?
How to Implement Distributed Data Store
dbms.pdf
Do It With SQL - Journey to the Center of Database Worlds
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Object Relational Database Management System
Modern sql
Really Big Elephants: PostgreSQL DW
Pg 95 new capabilities
Introduction to PostgreSQL
20080424 Cdb2008 Postgresql News Bartunov
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
PostgreSQL: Data analysis and analytics
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies

More from Nur Hidayat (7)

PDF
Develop a Software, Where to Start?
PPTX
How to Design a Good Database
PDF
How to Design a Good Database for Your Application
PPTX
Seminar Android - Pengenalan PhoneGap
PPTX
How to Become Great Programmer
PPTX
PHP Oracle
PPTX
MRI Presentation
Develop a Software, Where to Start?
How to Design a Good Database
How to Design a Good Database for Your Application
Seminar Android - Pengenalan PhoneGap
How to Become Great Programmer
PHP Oracle
MRI Presentation

Recently uploaded (20)

PDF
top salesforce developer skills in 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Nekopoi APK 2025 free lastest update
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPT
Introduction Database Management System for Course Database
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Transform Your Business with a Software ERP System
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
history of c programming in notes for students .pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
top salesforce developer skills in 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Nekopoi APK 2025 free lastest update
Internet Downloader Manager (IDM) Crack 6.42 Build 41
2025 Textile ERP Trends: SAP, Odoo & Oracle
Computer Software and OS of computer science of grade 11.pptx
Introduction Database Management System for Course Database
Design an Analysis of Algorithms I-SECS-1021-03
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
CHAPTER 2 - PM Management and IT Context
Navsoft: AI-Powered Business Solutions & Custom Software Development
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Transform Your Business with a Software ERP System
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
history of c programming in notes for students .pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

PostgreSQL Advanced Queries

  • 1. PostgreSQL Advanced Queries COMELABS - MARGONDA DEPOK 14 NOPEMBER 2015
  • 2. About Me • Editor PojokProgrammer.net • Writers welcome! • CEO BiruniLabs • Trainers welcome! • CEO Cronos Studio • Developers welcome!
  • 3. WhatYou Need • Laptop or Computer • PostgreSQL Installed • SQL Interface • HeidiSQL • SQLyog • phpMyAdmin • Whatever..... • Your Brain 
  • 5. History of PostgreSQL • INGRES, Berkeley 1982 • POSTGRES, Berkeley 1985 • POSTGRES v1, 1989 • PostQUEL, 1990 •PostgreSQL 6.0 (1995) • Initial release •PostgreSQL 7.0 (2000) • SQL92 compliance •PostgreSQL 8.0 (2005) • Multi-Platform support • Analytical Function support •PostgreSQL 9.0 (2010) • Built-in Replication • JSON datatype support
  • 6. Rule of Thumb From Tom Kyte (Oracle Evangelist) 1. Use single SQL statement whenever possible 2. Use PL/SQL or Stored Procedure 3. Use Java (or other programming language) 4. Rethink why you want to do it (refine your approach)
  • 7. SQL Anatomy • Statements • Queries • Clauses • Predicates • Expressions
  • 8. ChangeYour Mindset! • Apa yang akan kalian lakukan jika mendapatkan tugas seperti di bawah ini • Tampilkan angka 1 sampai dengan 100, namun setiap kelipatan 3 ubah angkanya menjadi kata Rumah, setiap kelipatan 5 ubah angkanya menjadi kata Sakit, dan setiap kelipatan 15 ubah angkanya menjadi kata Rumah Sakit.
  • 9. SELECT SELECT b,d,e,h FROM some_table ; SELECT * FROM some_table WHERE x IN (3,5,6,8) ; SELECT b,d,e,h FROM some_table WHERE x IN (3,5,6,8) ;
  • 10. JOIN vs UNION JOIN ====== SELECT * FROM A JOIN B ON 1=1 UNION (UNION ALL) ====== SELECT * FROM A UNION ALL SELECT * FROM B
  • 11. JOIN • INNER JOIN (JOIN) • LEFT OUTER JOIN (LEFT JOIN) • RIGHT OUTER JOIN (RIGHT JOIN) • FULL OUTER JOIN (FULLJOIN) • LEFT JOIN EXCLUDING INNER JOIN (LEFT EXCLUDING JOIN) • RIGHT JOIN EXCLUDING INNER JOIN (RIGHT EXCLUDING JOIN) • OUTER JOIN EXCLUDING INNER JOIN (OUTER EXCLUDINGJOIN)
  • 13. ChangeYour Mindset! • Apa yang akan kalian lakukan jika diminta membuat output seperti di bawah ini Tabel A ID Description 1 SUV 2 Sedan 3 Truk 4 Bus 5 MPV Tabel B A_ID Description 1 Toyota Fortuner 1 BMW X5 2 ToyotaVios 2 Honda City 5 Dahihatsu GranMax ID Description Jumlah 1 SUV 2 2 Sedan 2 3 Truk 0 4 Bus 0 5 MPV 1
  • 14. Ready for Advanced Queries?
  • 15. Common Table Expression • Standard SQL feature • Allows you to split a query statement into distinct parts • Results of each part will appear as a table • More maintainable than subqueries
  • 16. Hierarchical Queries • Fixed depth hierarchical data can be solved using simple JOINs • CTE allows recursive query • CTE can process data as hierarchical • CTE can process arbitrarily deep hierarchies with just one query
  • 18. Aggregates and Window Functions • GROUP BY lets you calculate aggregates of data over a single or multiple columns in a result set. • GROUP BY can only aggregate over a single grouping • GROUP BY only return aggregated data, detail data is not preserved • Window functions make it possible • Indicated by OVER Clause • ROW_NUMBER() OVER() • SUM() OVER() • COUNT() OVER() • MAX() OVER() • MIN() OVER() • AVG() OVER()
  • 20. Pivoting data • Sometimes it’s nice to be able to pivot data in a properly normalized data model, so that repeating groups of related entities are folded into parent entity as columns. • Pivoting is very useful reporting purposes and ad- hoc queries. • PostgreSQL can handle pivoting data using • Subqueries and Arrays • UsingCASE clause
  • 22. Other Advanced PostgreSQL • JSON built-in support • Pattern matching. Regular expression matching is supported • Geolocation queries. PostGIS extension adds comprehensive support for managing and querying geospatial data • Partitioning • Replication