CREATE TABLE ItaiTable ( ItaiID INT4, Name VARCHAR(32) );
The copy-pastes and explanations blog for SQL code, errors and daily cases! This blog is a 'list' of actions that always good to have available. The copy-paste concept here is short and clear explanations and descriptions (no long stories!) and - of course - the code to take (copy) and use (paste). The blog deals in the database (mostly) and software issues.
Labels
PostgreSQL - Tuples Demo
PostgreSQL Tuples and MVCC
- Actually tuple is a row in the table.
- Row is what will be back in a SELECT query.
- Tuple is how it managed.
- MVCC enables operations to occur concurrently by utilizing snapshots of the database.
- In MVCC, When you update or delete any row, Internally It creates the new row and mark old row as unused.
- The tradeoff is that it creates dead rows / dead tuples.
- MVCC is a little bit similar to READ_COMMITTED_SNAPSHOT in SQL Server.
- Vacuuming is needed to get rid of old (dead) tuples which are created when you change/delete rows.
- In PostgreSQL, tuples that are deleted or obsoleted by an update are not physically removed from their table; they remain present until a VACUUM is done.
- It doesn’t reduce the size of the files.
- except for the case when several pages at the end of the file are completely free.
- Space is freed up inside the data pages, which can later be used to insert new tuples.
- Vacuuming runs:
- Manually with the VACUUM command
- Autovacuum background process
- VACUUM update statistics when the configuration parameter “track_counts” is set to “on”.
- Running it too often will create unnecessary load on the system. But running vacuum too rare, with a large volume of changes, the files may grow significantly in size.
- VACUUM update statistics when the configuration parameter “track_counts” is set to “on”.
- This parameter is under “Runtime Statistics” section in postgresql.conf configuration file.
- To check what is the current value run: SELECT name, setting FROM pg_settings WHERE name='track_counts';
PostgreSQL Architecture
The physical structure of PostgreSQL consists of
- Processes.
- Shared memory.
- Data files.
- Postmaster (Daemon) Process
- The first process started when you start PostgreSQL.
- At startup it starts all other processes; performs recovery, initialize shared memory, and run background processes.
- It creates a backend process when there is a connection request from the client process.
- Postmaster process is the parent process of all processes.
- Background Processes
List of Background processes:
logger
Write the error message to the log file.
checkpointer
When a checkpoint occurs, the dirty buffer is written to the file.
writer
Periodically writes the dirty buffer to a file.
wal writer
Write the WAL buffer to the WAL file.
Autovacuum launcher
Fork autovacuum worker when autovacuum is enabled.It is the responsibility of the autovacuum daemon to carry vacuum operations on bloated tables on demand
archiver
When in Archive.log mode, copy the WAL file to the specified directory.
stats collector
DBMS usage statistics such as session execution information ( pg_stat_activity ) and table usage statistical information ( pg_stat_all_tables ) are colle
- Backend Process
- Performs the query request of the user process and then transmits the result.
- Client Process
- Refers to the background process that is assigned for every backend user connection.
- Usually the postmaster process will fork a child process that is dedicated to serve a user connection.
- Database caching
- Transaction log caching.
The important elements in shared memory are
- Shared Buffer
- The purpose of Shared Buffer is to minimize DISK IO.
- WAL buffers
- A buffer that temporarily stores changes to the database (to the WAL files).
- Temp buffers
- Stores temporary tables
The data is cached both in the operating system level and in the PostgreSQL level:
- PostgreSQL buffer cache in shared memory.
- OS data cache is the Write-Ahead Log (WAL).
In the case of a failure the contents of the RAM disappear and some data may be lost, which is unacceptable as it violates the durability property.
Therefore, during its operation PostgreSQL constantly writes the so-called Write-Ahead Log (WAL) to the disk.
This allows to re-perform lost operations and restore data in a consistent state.
Transaction logging - WAL
WAL = Write-Ahead Log.
Each transaction is written to the WAL File before it written to the data files on the disk (as described above).
WAL files stored in \data\pg_wal.
A single information unit within a WAL file is called a log record.
“Segment” is sometimes used as synonym for WAL file.
SQL Server LDF files ~ Oracle REDO files ~ PostgreSQL WAL files
PostgreSQL main terms
A tuple is a synonym for a row.
A relation is a synonym for a table.
A filenode is an id which represent a reference to a table or an index.
PostgreSQL database Cluster
- It is not a collection of servers,
- It is a collection of databases managed by a single server
PostgreSQL Data Types
- numeric, floating-point
- string
- Boolean
- date/time
- UUID
- Universally Unique Identifies.
- 16 bytes of storage.
- Example: d5f28c97-b962-43be-9cf8-ca1632182e8e
- XML
- XML type is just a text data type.
- The advantage is that it checks that the XML is well-formed.
- json, jsonB
- Text Search Type:
- Two data types which are designed to support full-text search.
- Money
- Network Address
- Network information like IP address.
- Using Network Address Types has following advantages
- Storage Space Saving
- Input error checking
- Functions like searching data by subnet
- Geometric
- Represent two-dimensional spatial objects.
- They help perform operations like rotations, scaling, translation, etc.
- Enumerated
- A set of values.
- While inserting, it checks that the value is from the declared set.
- The ordering of the values in an enum type is the order in which the values were listed when the type was created.
- Example:
- ('sad', 'ok', 'happy’);
- In this example: ‘ok’ > ‘sad’ and < ‘happy’.
- Range
- Data in ranges.
- Can be a range of numeric and dates.
- Pseudo-Types
- special-purpose entries.
- Any, An array, Any element, Any enum, Nonarray, Cstring, Internal, Language_handler, Record, Trigger.
PostgreSQL Databases
- Two Template Databases:
- Template0
- Template1
- postgres:
- The default database created using the template1 database.
- If you do not specify a database at connection time, you will be connected to the postgres database.
- DVD Rental sample database.
- Two ‘default’ Template Databases: Template0, Template1.
- Template1 is the default template.
- The 2 templates contains the same data.
- Template0 is more empty/"virgin" DB.
- New encoding and locale settings can be specified when copying template0, whereas a copy of template1 must use the same settings it does.
- More templates can be created.
- pg_default: stores all user data (the default tablespace).
- pg_global: stores all global data.
PostgreSQL Configurations
Edit postgresql.conf file itself.
- Via postgres command in the command-line.
- Some parameters can be changed in individual SQL sessions with the SET command.
- Some parameters can be changed with “ALTER SYSTEM” command.
- ALTER SYSTEM SET configuration_parameter { TO | = } { value | 'value' | DEFAULT }
- ALTER SYSTEM RESET configuration_parameter
- ALTER SYSTEM RESET ALL
- select * from pg_settings
- At pgAdmin.
PostgreSQL as Object-Relational Database Management System (ORDBMS)
PostgreSQL Overview

PostgreSQL uses and extends the SQL language combined with other features.
- Database superuser (postgres) password.
- Port (default: 5432).
- PostgreSQL site: https://www.postgresql.org/
- postgresql.git: https://git.postgresql.org/gitweb/?p=postgresql.git
- PostgreSQL ODBC driver: https://www.progress.com/campaigns/datadirect/ppc/postgresql-odbc
- Configuration calculator: https://pgtune.leopard.in.ua/#/
- What is PostgreSQL? https://www.guru99.com/introduction-postgresql.html
IS DISTINCT FROM
select * from itaitable
select * from itaitable where "Job" <> 'DBA’
select * from itaitable where "Job" = 'DBA’
select * from itaitable where "Job" is distinct from 'DBA'
PostgreSQL - translate encoding char to numbers and vice versa
--Result: UTF8
select pg_char_to_encoding('UTF8');
--Result: 6
PostgreSQL - EXPLAIN - Show execution plan
Display the execution plan which PostgreSQL generates.
EXPLAIN ANALYZE
Display more statistics. Display actual run-time statistics.
CTE - SQL Server vs PostgreSQL
In SQL Server CTEs are processed with the main query.
In PostgreSQL CTEs are processed separately from the main query
- A query that should touch a small amount of data instead reads a whole table and possibly spills it to a tempfile.
- You cannot UPDATE or DELETE FROM a CTE term, because it’s more like a read-only temp table rather than a dynamic view.
- In PostgreSQL, in this query:
PostgreSQL - relation "pg_stat_statements" does not exist
select * from pg_stat_statements;
-- and pg_stat_statements is enabled (if not - check here)
Error message:
ERROR: pg_stat_statements must be loaded via shared_preload_libraries
Cause:
pg_stat_statements is not set in postgresql.conf.
It probably looks like:
#shared_preload_libraries = '' # (change requires restart)
or with other libraries.
Solution:
1. Set pg_stat_statements in postgresql.conf; adding:
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 10000
pg_stat_statements.track = all
2. Restart PostgreSQL service
Check it:
SHOW shared_preload_libraries;
PostgreSQL - relation "pg_stat_statements" does not exist
select * from pg_stat_statements;
Error message:
ERROR: relation "pg_stat_statements" does not exist
LINE 1: select * from pg_stat_statements
^
Cause:
pg_stat_statements is not available globally but can be enabled for a specific database with CREATE EXTENSION.
Solution:
Enable pg_stat_statements:
CREATE EXTENSION pg_stat_statements;
Check it:
SELECT * FROM pg_available_extensions WHERE name = 'pg_stat_statements';
SELECT * FROM pg_available_extension_versions WHERE name = 'pg_stat_statements';










