SlideShare a Scribd company logo
2
Most read
4
Most read
6
Most read
POSTGRESQL TUTORIAL
PostgreSQL is an advanced relational database system.
PostgreSQL supports both relational (SQL) and non-relational (JSON)
queries.
PostgreSQL is free and open-source.
PostgreSQL, also known as Postgres, is a free and open-source
relational database management system emphasizing extensibility
and SQL compliance. PostgreSQL supports both relational (SQL) and
non-relational (JSON) queries.
PostgreSQL supports the most important programming languages:
• Python
• Java
• C/C++
• C#
• Node.js
• Go
• Ruby
• Perl
• Tcl
PostgreSQL supports basically all features that other database
management systems support.
PostgreSQL History
PostgreSQL was invented at the Berkeley Computer
Science Department, University of California.
It started as a project in 1986 with the goal of
creating a database system with the minimal features
needed to support multiple data types.
In the beginning, PostgreSQL ran on UNIX platforms,
but now it can run on various platforms, including
Windows and MacOS.
Connect to the Database
If you have followed the steps from the Install
PostgreSQL page, you now have a PostgreSQL database
on you computer.
There are several ways to connect to the database, we
will look at two ways in this tutorial:
• SQL Shell (psql)
• pgAdmin 4
Both of them comes with the installation of PostgreSQL
Note: Always end SQL statements with a
semicolon ;
Once you are connected through pgAdmin4, you
are ready to write SQL statements!
The ALTER TABLE Statement
To add a column to an existing table, we have to use the ALTER TABLE statement.
To change the data type, or the size of a table column we have to use the ALTER TABLE
statement.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER COLUMN
We want to change the data type of the year
column of the cars table from INT to
VARCHAR(4).
To modify a column, use the ALTER COLUMN
statement and the TYPE keyword followed by
the new data type:
Example
Change the year column from INT to
VARCHAR(4):
ALTER TABLE cars
ALTER COLUMN year TYPE VARCHAR(4);
Note: Some data types cannot be converted if the column
has value. E.g. numbers can always be converted to text,
but text cannot always be converted to numbers.
DROP COLUMN
We want to remove the column named color from the
cars table.
To remove a column, use the DROP COLUMN statement:
Example
Remove the color column:
ALTER TABLE cars DROP COLUMN color;
The DELETE Statement
The DELETE statement is used to delete existing records in a table.
Note: Be careful when deleting records in a table! Notice the WHERE
clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted.
If you omit the WHERE clause, all records in the table will be deleted!.
The TRUNCATE TABLE Statement
The TRUNCATE TABLE statement is used to delete ALL records in a
table.
The DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a
database.
Note: Be careful before dropping a table. Deleting a table will result in
loss of all information stored in the table!
= Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
<> Not equal to
!= Not equal to
LIKE Check if a value matches a pattern (case sensitive)
ILIKE Check if a value matches a pattern (case insensitive)
AND Logical AND
OR Logical OR
IN Check if a value is between a range of values
BETWEE
N
Check if a value is between a range of values
IS NULL Check if a value is NULL
NOT
Makes a negative result e.g. NOT LIKE, NOT IN, NOT
BETWEEN
Operators in the WHERE clause
We can operate with different operators in the WHERE clause:
LIKE
The LIKE operator is used when you want to return all records where a
column is equal to a specified pattern.
The pattern can be an absolute value like 'Volvo', or with a wildcard that
has a special meaning.
There are two wildcards often used in conjunction with the LIKE operator:
• The percent sign % , represents zero, one, or multiple characters.
• The underscore sign _ , represents one single character.
ILIKE
Same as the LIKE operator, but ILIKE is case insensitive.
IN
The IN operator is used when a column's value matches any of the values in a list:
Example
Return all records where the brand is present in this list: ('Volvo', 'Mercedes', 'Ford'):
SELECT * FROM cars
WHERE brand IN ('Volvo', 'Mercedes', 'Ford’);
NOT
The NOT operator can be used together with LIKE, ILIKE, IN, BETWEEN, and NULL
operators to reverse the truth of the operator.
Example: NOT LIKE : Return all records where the brand does NOT start with a
capital 'B' (case sensitive):
SELECT * FROM cars WHERE brand NOT LIKE 'B%';
THE OFFSET CLAUSE
The OFFSET clause is used to specify where to
start selecting the records to return.
If you want to return 20 records, but start at
number 40, you can use both LIMIT and OFFSET.
Note: The first record is number 0, so when you
specify OFFSET 40 it means starting at record
number 41.
Example
Return 20 records, starting from the 41th record:
SELECT * FROM customers LIMIT 20 OFFSET 40;
IN (SELECT)
You can also us a SELECT statement inside the parenthesis
to return all records that are in the result of the SELECT
statement.
Example: Return all customers that have an order in the
orders table:
SELECT * FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);
NOT IN (SELECT)
The result in the example above returned 89 records, that
means that there are 2 customers that haven't placed any
orders.
Let us check if that is correct, by using the NOT IN operator.
Example
Return all customers that have NOT placed any orders in
the orders table:
SELECT * FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM
orders);
BETWEEN
The BETWEEN operator selects values within a given range. The
values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are
included.
Example
Select all products with a price between 10 and 15:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 15;
BETWEEN Text Values
The BETWEEN operator can also be used on text values.
The result returns all records that are alphabetically between the
specified values.
SELECT * FROM Products
WHERE product_name BETWEEN 'Pavlova' AND 'Tofu'
ORDER BY product_name;
BETWEEN Date Values
The BETWEEN operator can also be used on date values.
Example : Select all orders between 12. of April 2023 and 5. of
May 2023:
SELECT * FROM orders
Concatenate Columns
The AS keyword is often used when two or more fields are
concatenated into one.
To concatenate two fields use ||.
Example
Concatenate two fields and call them product:
SELECT product_name || unit AS product FROM products;
Note: In the result of the example above we are missing a
space between product_name and unit. To add a space
when concatenating, use || ' ' ||.
Using Aliases With a Space Character
If you want your alias to contain one or more spaces, like
"My Great Products", surround your alias with double
quotes.
Example
Surround your alias with double quotes:
SELECT product_name AS “My Great Products” FROM
products;
JOIN OPERATIONS IN POSTGRESQL
In PostgreSQL, the JOIN clause is used to combine rows from two or
more tables based on a related column or condition. It specifies how
the tables should be joined and on which columns the join should be
performed.
There are several types of joins available in PostgreSQL:
1: INNER JOIN
2: LEFT JOIN
3: RIGHT JOIN
4: FULL JOIN
5: CROSS JOIN / CARTESIAN JOIN
6: NATURAL JOIN
7: SELF JOIN
Note: JOIN and INNER JOIN will give the same result.
INNER is the default join type for JOIN, so when you write JOIN the
parser actually writes INNER JOIN.
Note: LEFT JOIN and LEFT OUTER JOIN will give the same result.
OUTER is the default join type for LEFT JOIN, so when you write LEFT
JOIN the parser actually writes LEFT OUTER JOIN.
Note: RIGHT JOIN and RIGHT OUTER JOIN will give the same result.
OUTER is the default join type for RIGHT JOIN, so when you write
RIGHT JOIN the parser actually writes RIGHT OUTER JOIN.
Note: FULL JOIN and FULL OUTER JOIN will give the same result.
OUTER is the default join type for FULL JOIN, so when you write FULL
JOIN the parser actually writes FULL OUTER JOIN.
CROSS JOIN
The CROSS JOIN keyword matches ALL records from the "left" table
with EACH record from the "right" table.
That means that all records from the "right" table will be returned for
each record in the "left" table.
This way of joining can potentially return very large table, and you
should not use it if you do not have to.
UNION
The UNION operator is used to combine the result-set of two or more
queries.
The queries in the union must follow these rules:
1. They must have the same number of columns
2. The columns must have the same data types
3. The columns must be in the same order
UNION vs UNION ALL
With the UNION operator, if some rows in the two queries returns the
exact same result, only one row will be listed, because UNION selects
only distinct values.
Use UNION ALL to return duplicate values.
GROUP BY
The GROUP BY clause groups rows that have the
same values into summary rows, like "find the
number of customers in each country".
The GROUP BY clause is often used with aggregate
functions like COUNT(), MAX(), MIN(), SUM(), AVG()
to group the result-set by one or more columns.
HAVING
The HAVING clause was added to SQL because the
WHERE clause cannot be used with aggregate
functions.
Aggregate functions are often used with GROUP BY
clauses, and by adding HAVING we can write condition
like we do with WHERE clauses.
SELECT customers.customer_name, SUM(products.price)
FROM order_details
LEFT JOIN products ON order_details.product_id =
products.product_id
LEFT JOIN orders ON order_details.order_id = orders.order_id
LEFT JOIN customers ON orders.customer_id =
customers.customer_id
GROUP BY customer_name
HAVING SUM(products.price) > 1000.00;
Lists customers that have ordered for 1000$ or
more:
EXISTS
The EXISTS operator is used to test for the existence of any record in a sub
query.
The EXISTS operator returns TRUE if the sub query returns one or more
records.
Example
Return all customers that is represented in the orders table:
SELECT customers.customer_name
FROM customers
WHERE EXISTS (
SELECT order_id FROM orders WHERE customer_id =
customers.customer_id
);
The result in example above showed that 89 customers had at least one
order in the orders table.
NOT EXISTS
To check which customers that do not have any orders, we can use the
NOT operator together with the EXISTS operator :
Example
Return all customers that is NOT represented in the orders table:
SELECT customers.customer_name
FROM customers
WHERE NOT EXISTS (
SELECT order_id FROM orders WHERE customer_id =
customers.customer_id
ANY
The ANY operator allows you to perform a
comparison between a single column value and
a range of other values.
The ANY operator:
Returns a Boolean value as a result returns
TRUE if ANY of the sub query values meet the
condition
ANY means that the condition will be true if the
operation is true for any of the values in the
range.
Example
List products that have ANY records in the
order_details table with a quantity larger than
120:
SELECT product_name
FROM products
WHERE product_id = ANY (
SELECT product_id
FROM order_details
WHERE quantity > 120
);
ALL
The ALL operator:
• returns a Boolean value as a result
• returns TRUE if ALL of the sub query values meet the condition
• is used with SELECT, WHERE and HAVING statements
ALL means that the condition will be true only if the operation is true
for all values in the range.
Example
List the products if ALL the records in the order_details with quantity
larger than 10.
Note: This will of course return FALSE because the quantity column has
many different values (not only the value of 10):
SELECT product_name
FROM products
WHERE product_id = ALL (
SELECT product_id
FROM order_details
WHERE quantity > 10
);
CASE
The CASE expression goes through conditions and returns a value
when the first condition is met (like an if-then-else statement).
Once a condition is true, it will stop reading and return the result. If no
conditions are true, it returns the value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
Example
Return specific values if the price meets a specific condition:
SELECT product_name,
CASE
WHEN price < 10 THEN 'Low price product'
WHEN price > 50 THEN 'High price product'
ELSE
'Normal product'
END
FROM products;
Las 10 mejores herramientas para monitorear bases de datos PostgreSQL
1. pgAdmin
•Descripción: Herramienta oficial para administración de PostgreSQL.
•Características: Visualización de estadísticas, monitoreo básico y
consultas en tiempo real.
2. pg_stat_statements
•Descripción: Extensión nativa para analizar y optimizar consultas
SQL.
•Características: Métricas de rendimiento por consulta, identificación
de consultas lentas.
3. Prometheus + Grafana
•Descripción: Herramientas de monitoreo y visualización en tiempo
real.
•Características: Dashboards personalizados y alertas; usa
postgres_exporter para métricas de PostgreSQL.
4. pganalyze
•Descripción: Plataforma avanzada de análisis y monitoreo.
•Características: Optimización de consultas, métricas avanzadas,
recomendaciones automatizadas.
5. Zabbix
•Descripción: Herramienta de monitoreo general con soporte para
PostgreSQL.
•Características: Monitoreo de conexiones, bloqueos, rendimiento y
alertas personalizables.
6. Datadog
•Descripción: Plataforma de monitoreo en la nube que incluye
soporte para PostgreSQL.
•Características: Visualización avanzada, integración con múltiples
servicios y alertas automatizadas.
7. Nagios
•Descripción: Sistema de monitoreo de infraestructura con módulos
para bases de datos.
•Características: Monitoreo de rendimiento, conexiones,
disponibilidad y alertas.
8. Percona Monitoring and Management (PMM)
•Descripción: Herramienta enfocada en bases de datos, incluyendo
PostgreSQL.
•Características: Análisis de consultas, métricas de rendimiento y
optimización.
9. New Relic
•Descripción: Plataforma de monitoreo para aplicaciones y bases de
datos.
•Características: Análisis de rendimiento en tiempo real, optimización
y visualización de datos históricos.
10. pgCluu
•Descripción: Herramienta de monitoreo y auditoría específica para
PostgreSQL.
•Características: Informes detallados sobre uso de recursos,
consultas y rendimiento.

More Related Content

PPT
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
PPTX
SQL Server Learning Drive
PDF
full detailled SQL notesquestion bank (1).pdf
PDF
Learning SQL
PDF
Learning SQL
PPTX
PPTX
DDL,DML,SQL Functions and Joins
PPTX
Database Overview
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
SQL Server Learning Drive
full detailled SQL notesquestion bank (1).pdf
Learning SQL
Learning SQL
DDL,DML,SQL Functions and Joins
Database Overview

Similar to Practical Tutorial about the PostgreSQL Database (20)

DOC
Learn sql queries
PPTX
Introduction to SQL
PPTX
Sql slid
DOCX
SQL report
PDF
SQL Beginners anishurrehman.cloud.pdf
PPTX
SQL Query
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
PDF
SQL Overview
PPT
MY SQL
PPTX
Oracle: Basic SQL
PPTX
Oracle: Basic SQL
PDF
Bt0075 rdbms with mysql 2
PPT
Mysql 120831075600-phpapp01
PPTX
Sql powerpoint
PDF
SQL command for daily use ddl dml dcl dql
PPTX
Structure Query Language Advance Training
PPT
PPT
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
Learn sql queries
Introduction to SQL
Sql slid
SQL report
SQL Beginners anishurrehman.cloud.pdf
SQL Query
INTRODUCTION TO SQL QUERIES REALTED BRIEF
SQL Overview
MY SQL
Oracle: Basic SQL
Oracle: Basic SQL
Bt0075 rdbms with mysql 2
Mysql 120831075600-phpapp01
Sql powerpoint
SQL command for daily use ddl dml dcl dql
Structure Query Language Advance Training
SQL command practical power point slides, which help you in learning sql.pptx
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
cuic standard and advanced reporting.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Cloud computing and distributed systems.
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced IT Governance
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
cuic standard and advanced reporting.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Cloud computing and distributed systems.
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Chapter 2 Digital Image Fundamentals.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced IT Governance
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Diabetes mellitus diagnosis method based random forest with bat algorithm
GamePlan Trading System Review: Professional Trader's Honest Take
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
“AI and Expert System Decision Support & Business Intelligence Systems”
Ad

Practical Tutorial about the PostgreSQL Database

  • 1. POSTGRESQL TUTORIAL PostgreSQL is an advanced relational database system. PostgreSQL supports both relational (SQL) and non-relational (JSON) queries. PostgreSQL is free and open-source. PostgreSQL, also known as Postgres, is a free and open-source relational database management system emphasizing extensibility and SQL compliance. PostgreSQL supports both relational (SQL) and non-relational (JSON) queries. PostgreSQL supports the most important programming languages: • Python • Java • C/C++ • C# • Node.js • Go • Ruby • Perl • Tcl PostgreSQL supports basically all features that other database management systems support. PostgreSQL History PostgreSQL was invented at the Berkeley Computer Science Department, University of California. It started as a project in 1986 with the goal of creating a database system with the minimal features needed to support multiple data types. In the beginning, PostgreSQL ran on UNIX platforms, but now it can run on various platforms, including Windows and MacOS. Connect to the Database If you have followed the steps from the Install PostgreSQL page, you now have a PostgreSQL database on you computer. There are several ways to connect to the database, we will look at two ways in this tutorial: • SQL Shell (psql) • pgAdmin 4 Both of them comes with the installation of PostgreSQL
  • 2. Note: Always end SQL statements with a semicolon ; Once you are connected through pgAdmin4, you are ready to write SQL statements! The ALTER TABLE Statement To add a column to an existing table, we have to use the ALTER TABLE statement. To change the data type, or the size of a table column we have to use the ALTER TABLE statement. The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table. ALTER COLUMN We want to change the data type of the year column of the cars table from INT to VARCHAR(4). To modify a column, use the ALTER COLUMN statement and the TYPE keyword followed by the new data type: Example Change the year column from INT to VARCHAR(4): ALTER TABLE cars ALTER COLUMN year TYPE VARCHAR(4); Note: Some data types cannot be converted if the column has value. E.g. numbers can always be converted to text, but text cannot always be converted to numbers. DROP COLUMN We want to remove the column named color from the cars table. To remove a column, use the DROP COLUMN statement: Example Remove the color column: ALTER TABLE cars DROP COLUMN color;
  • 3. The DELETE Statement The DELETE statement is used to delete existing records in a table. Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!. The TRUNCATE TABLE Statement The TRUNCATE TABLE statement is used to delete ALL records in a table. The DROP TABLE Statement The DROP TABLE statement is used to drop an existing table in a database. Note: Be careful before dropping a table. Deleting a table will result in loss of all information stored in the table!
  • 4. = Equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to <> Not equal to != Not equal to LIKE Check if a value matches a pattern (case sensitive) ILIKE Check if a value matches a pattern (case insensitive) AND Logical AND OR Logical OR IN Check if a value is between a range of values BETWEE N Check if a value is between a range of values IS NULL Check if a value is NULL NOT Makes a negative result e.g. NOT LIKE, NOT IN, NOT BETWEEN Operators in the WHERE clause We can operate with different operators in the WHERE clause: LIKE The LIKE operator is used when you want to return all records where a column is equal to a specified pattern. The pattern can be an absolute value like 'Volvo', or with a wildcard that has a special meaning. There are two wildcards often used in conjunction with the LIKE operator: • The percent sign % , represents zero, one, or multiple characters. • The underscore sign _ , represents one single character. ILIKE Same as the LIKE operator, but ILIKE is case insensitive. IN The IN operator is used when a column's value matches any of the values in a list: Example Return all records where the brand is present in this list: ('Volvo', 'Mercedes', 'Ford'): SELECT * FROM cars WHERE brand IN ('Volvo', 'Mercedes', 'Ford’); NOT The NOT operator can be used together with LIKE, ILIKE, IN, BETWEEN, and NULL operators to reverse the truth of the operator. Example: NOT LIKE : Return all records where the brand does NOT start with a capital 'B' (case sensitive): SELECT * FROM cars WHERE brand NOT LIKE 'B%';
  • 5. THE OFFSET CLAUSE The OFFSET clause is used to specify where to start selecting the records to return. If you want to return 20 records, but start at number 40, you can use both LIMIT and OFFSET. Note: The first record is number 0, so when you specify OFFSET 40 it means starting at record number 41. Example Return 20 records, starting from the 41th record: SELECT * FROM customers LIMIT 20 OFFSET 40; IN (SELECT) You can also us a SELECT statement inside the parenthesis to return all records that are in the result of the SELECT statement. Example: Return all customers that have an order in the orders table: SELECT * FROM customers WHERE customer_id IN (SELECT customer_id FROM orders); NOT IN (SELECT) The result in the example above returned 89 records, that means that there are 2 customers that haven't placed any orders. Let us check if that is correct, by using the NOT IN operator. Example Return all customers that have NOT placed any orders in the orders table: SELECT * FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM orders);
  • 6. BETWEEN The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included. Example Select all products with a price between 10 and 15: SELECT * FROM Products WHERE Price BETWEEN 10 AND 15; BETWEEN Text Values The BETWEEN operator can also be used on text values. The result returns all records that are alphabetically between the specified values. SELECT * FROM Products WHERE product_name BETWEEN 'Pavlova' AND 'Tofu' ORDER BY product_name; BETWEEN Date Values The BETWEEN operator can also be used on date values. Example : Select all orders between 12. of April 2023 and 5. of May 2023: SELECT * FROM orders Concatenate Columns The AS keyword is often used when two or more fields are concatenated into one. To concatenate two fields use ||. Example Concatenate two fields and call them product: SELECT product_name || unit AS product FROM products; Note: In the result of the example above we are missing a space between product_name and unit. To add a space when concatenating, use || ' ' ||. Using Aliases With a Space Character If you want your alias to contain one or more spaces, like "My Great Products", surround your alias with double quotes. Example Surround your alias with double quotes: SELECT product_name AS “My Great Products” FROM products;
  • 7. JOIN OPERATIONS IN POSTGRESQL In PostgreSQL, the JOIN clause is used to combine rows from two or more tables based on a related column or condition. It specifies how the tables should be joined and on which columns the join should be performed. There are several types of joins available in PostgreSQL: 1: INNER JOIN 2: LEFT JOIN 3: RIGHT JOIN 4: FULL JOIN 5: CROSS JOIN / CARTESIAN JOIN 6: NATURAL JOIN 7: SELF JOIN Note: JOIN and INNER JOIN will give the same result. INNER is the default join type for JOIN, so when you write JOIN the parser actually writes INNER JOIN. Note: LEFT JOIN and LEFT OUTER JOIN will give the same result. OUTER is the default join type for LEFT JOIN, so when you write LEFT JOIN the parser actually writes LEFT OUTER JOIN. Note: RIGHT JOIN and RIGHT OUTER JOIN will give the same result. OUTER is the default join type for RIGHT JOIN, so when you write RIGHT JOIN the parser actually writes RIGHT OUTER JOIN. Note: FULL JOIN and FULL OUTER JOIN will give the same result. OUTER is the default join type for FULL JOIN, so when you write FULL JOIN the parser actually writes FULL OUTER JOIN.
  • 8. CROSS JOIN The CROSS JOIN keyword matches ALL records from the "left" table with EACH record from the "right" table. That means that all records from the "right" table will be returned for each record in the "left" table. This way of joining can potentially return very large table, and you should not use it if you do not have to. UNION The UNION operator is used to combine the result-set of two or more queries. The queries in the union must follow these rules: 1. They must have the same number of columns 2. The columns must have the same data types 3. The columns must be in the same order UNION vs UNION ALL With the UNION operator, if some rows in the two queries returns the exact same result, only one row will be listed, because UNION selects only distinct values. Use UNION ALL to return duplicate values. GROUP BY The GROUP BY clause groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY clause is often used with aggregate functions like COUNT(), MAX(), MIN(), SUM(), AVG() to group the result-set by one or more columns. HAVING The HAVING clause was added to SQL because the WHERE clause cannot be used with aggregate functions. Aggregate functions are often used with GROUP BY clauses, and by adding HAVING we can write condition like we do with WHERE clauses. SELECT customers.customer_name, SUM(products.price) FROM order_details LEFT JOIN products ON order_details.product_id = products.product_id LEFT JOIN orders ON order_details.order_id = orders.order_id LEFT JOIN customers ON orders.customer_id = customers.customer_id GROUP BY customer_name HAVING SUM(products.price) > 1000.00; Lists customers that have ordered for 1000$ or more:
  • 9. EXISTS The EXISTS operator is used to test for the existence of any record in a sub query. The EXISTS operator returns TRUE if the sub query returns one or more records. Example Return all customers that is represented in the orders table: SELECT customers.customer_name FROM customers WHERE EXISTS ( SELECT order_id FROM orders WHERE customer_id = customers.customer_id ); The result in example above showed that 89 customers had at least one order in the orders table. NOT EXISTS To check which customers that do not have any orders, we can use the NOT operator together with the EXISTS operator : Example Return all customers that is NOT represented in the orders table: SELECT customers.customer_name FROM customers WHERE NOT EXISTS ( SELECT order_id FROM orders WHERE customer_id = customers.customer_id
  • 10. ANY The ANY operator allows you to perform a comparison between a single column value and a range of other values. The ANY operator: Returns a Boolean value as a result returns TRUE if ANY of the sub query values meet the condition ANY means that the condition will be true if the operation is true for any of the values in the range. Example List products that have ANY records in the order_details table with a quantity larger than 120: SELECT product_name FROM products WHERE product_id = ANY ( SELECT product_id FROM order_details WHERE quantity > 120 ); ALL The ALL operator: • returns a Boolean value as a result • returns TRUE if ALL of the sub query values meet the condition • is used with SELECT, WHERE and HAVING statements ALL means that the condition will be true only if the operation is true for all values in the range. Example List the products if ALL the records in the order_details with quantity larger than 10. Note: This will of course return FALSE because the quantity column has many different values (not only the value of 10): SELECT product_name FROM products WHERE product_id = ALL ( SELECT product_id FROM order_details WHERE quantity > 10 );
  • 11. CASE The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). Once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL. Example Return specific values if the price meets a specific condition: SELECT product_name, CASE WHEN price < 10 THEN 'Low price product' WHEN price > 50 THEN 'High price product' ELSE 'Normal product' END FROM products;
  • 12. Las 10 mejores herramientas para monitorear bases de datos PostgreSQL 1. pgAdmin •Descripción: Herramienta oficial para administración de PostgreSQL. •Características: Visualización de estadísticas, monitoreo básico y consultas en tiempo real. 2. pg_stat_statements •Descripción: Extensión nativa para analizar y optimizar consultas SQL. •Características: Métricas de rendimiento por consulta, identificación de consultas lentas. 3. Prometheus + Grafana •Descripción: Herramientas de monitoreo y visualización en tiempo real. •Características: Dashboards personalizados y alertas; usa postgres_exporter para métricas de PostgreSQL. 4. pganalyze •Descripción: Plataforma avanzada de análisis y monitoreo. •Características: Optimización de consultas, métricas avanzadas, recomendaciones automatizadas. 5. Zabbix •Descripción: Herramienta de monitoreo general con soporte para PostgreSQL. •Características: Monitoreo de conexiones, bloqueos, rendimiento y alertas personalizables. 6. Datadog •Descripción: Plataforma de monitoreo en la nube que incluye soporte para PostgreSQL. •Características: Visualización avanzada, integración con múltiples servicios y alertas automatizadas. 7. Nagios •Descripción: Sistema de monitoreo de infraestructura con módulos para bases de datos. •Características: Monitoreo de rendimiento, conexiones, disponibilidad y alertas. 8. Percona Monitoring and Management (PMM) •Descripción: Herramienta enfocada en bases de datos, incluyendo PostgreSQL. •Características: Análisis de consultas, métricas de rendimiento y optimización. 9. New Relic •Descripción: Plataforma de monitoreo para aplicaciones y bases de datos. •Características: Análisis de rendimiento en tiempo real, optimización y visualización de datos históricos. 10. pgCluu •Descripción: Herramienta de monitoreo y auditoría específica para PostgreSQL. •Características: Informes detallados sobre uso de recursos, consultas y rendimiento.