Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-30 12:25 pm

Dave Stokes: PostgreSQL 18 Old & New

 Learning Structured Query Language can be frustrating when double-checking that what you wanted to have done is actually what was done. PostgreSQL 18 has 'OLD and NEW support for RETURNING clauses in INSERT, UPDATE, DELETE, and MERGE commands'. Now you can get instant feedback. 

The addition of the RETURNING clause in the previous version made MERGE much easier to use. Now it makes other commands easier.

To demonstrate, let's create a table with one column that is designated as a unique, primary key integer and insert a value.

create table foo (a int unique primary key);


insert into foo (a) values (1);

Now is the point where many of us would run a SELECT a FROM foo, just to double check that indeed there is a 1 in column a.

There is now an option in PG 18 to use RETURNING, and it provides the previous 'old' value of a column along with the 'new' value.

insert into foo (a) values (2) returning old.a, new.a;

a|a|
-+-+
 |2|

The 'old' value was a NULL, and the new value is 2.

I suggest adding an alias to make things more explicit.

insert into foo (a) values (3) returning old.a as "Old", new.a as "New";
Old|New|
---+---+
   |  3|

Upserts

As I mentioned earlier, sometimes doubt creeps into your mind when you enter or update data.
RETURNING also works with UPSERTS (Thanks to the brilliant Magnus Hagander, who pointed this out out in
his presentation at the PG NYC 2025 show and his slides are available here).

In the following example, we have a conflict because there is already a '2' in the table, so the
ON CONFLICT path is taken. Using RETURNING in this case takes away any doubt of what happened when
this query was executed.

insert into foo(a) values (2)

on conflict(a) do update

set a = 99

returning old.a as old, new.a as update


old|update|
--
[...]
Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-29 12:00 am

Cédric Villemain: Cumulative Statistics in PostgreSQL 18

In PostgreSQL 18, the statistics & monitoring subsystem receives a
significant overhaul - extended cumulative statistics, new per-backend I/O
visibility, the ability for extensions to export / import / adjust statistics,
and improvements to GUC controls and snapshot / caching behavior. These changes
open new doors for performance analysis, cross‑environment simulation, and
tighter integration with extensions. In this article I explore what’s new, what
to watch out for, Grand Unified Configuration (GUC) knobs, and how extension
authors can leverage the new C API surface.

Introduction & motivation

Statistics (in the broad sense: monitoring counters, I/O metrics, and planner /
optimizer estimates) lie at the heart of both performance tuning and internal
decision making in PostgreSQL. Transparent, reliable, and manipulable
statistics, among other things, allow DBAs to address the efficiency of
PostgreSQL directly, as well as enable “extensions” to improve the user
experience.

That said, the historic statistics system of PostgreSQL has not been without
points of friction. These include limited ability to clear (relations)
statistics, metrics with units that don’t always align with user goals, and no C
API for using the PostgreSQL Cumulative Stats engine. PostgreSQL 18 addresses
these concerns head on.

Below is a summary of the key enhancements.

A warning on stats

While statistics offer incredible value, their collection can take up
significant time and resources. PostgreSQL 18 introduces an important
consideration: with the expanded range of collectible metrics, the hash table
maximum size has been increased. Do keep in mind, especially if you’re designing
large-scale systems with table-per-customer architectures, that 1GB ceilings
have been shown to be hit with some millions of tables.

What’s new with PostgreSQL 18 and “stats”

Here are the major new or improved features relating to statistics and
monitoring. Each item links to the relevant

[...]
Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-30 06:08 am

Вода из крана

Posted by temalebedev

Самая большая проблема в России - это качество воды в кранах у населения на селе и в малых городах.

В Москве и Питере вода из крана почти идеальная. А в частных загородных резиденциях и в какой-нибудь Тотьме из крана льется полный пиздец.

Вода тут пахнет сероводородом или яичным белком, то есть, пердежом дохлых микробов. И народ это терпит!

А за границей вода обычно нормальная (кроме льда в США, который пахнет прокисшими пселыми тряпками), но зато проблема с полотенцами - в каждой второй гостинице полотенца пахнут хлором до невозможности ими вытираться.

Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-30 06:00 am

Laurenz Albe: How to do UPDATE ... LIMIT in PostgreSQL

Dolphin to elephant: "MySQL has got UPDATE ... LIMIT, and PostgreSQL doesn't." - Elephant to dolphin: "But on the other hand, there is no limit to what you can do with an UPDATE in PostgreSQL."
© Laurenz Albe 2025

If you are reading this hoping that PostgreSQL finally got UPDATE ... LIMIT like MySQL, I have to disappoint you. The LIMIT clause is not yet supported for DML statements in PostgreSQL. If you want to UPDATE only a limited number of rows, you have to use workarounds. This article will describe how to do this and how to avoid the pitfalls and race condition you may encounter. Note that most of the following also applies to DELETE ... LIMIT!

An example for how we would like to do UPDATE ... LIMIT

The following table contains 100 categories of 100 entries each. Since we don't discuss persistence, an UNLOGGED table will do:

CREATE UNLOGGED TABLE upd (
   id bigint GENERATED ALWAYS AS IDENTITY,
   category integer NOT NULL,
   flag boolean DEFAULT FALSE NOT NULL
);

INSERT INTO upd (category)
SELECT (i - 1) / 100
FROM generate_series(1, 100000) AS i;

/* set hint bits, gather optimizer statistics */
VACUUM (ANALYZE) upd;

/* created after INSERT for performance */
ALTER TABLE upd ADD PRIMARY KEY (id);

CREATE INDEX ON upd (category);

Now we would like to set the flag on a single row with category 42:

UPDATE upd
SET flag = TRUE
WHERE category = 42
LIMIT 1;

But alas, we cannot do that. We'll have to look for other ways to achieve our goal.

Attempt to solve UPDATE ... LIMIT with a simple subquery

Since there is a LIMIT clause for SELECT, we can use a subquery as follows:

UPDATE upd AS u
SET flag = TRUE
WHERE u.category = 42
  AND u.id IN (SELECT id FROM upd AS u2
               WHERE u2.category = u.category
               LIMIT 1);

This query works as intended if nobody else is using the table. But it can fail to work as expected in the face of concurrent data modifications:

BEGIN;

DELETE FROM upd WHERE id = 4201;

Now run our proposed update statement in a concurrent session, and it will hang. Now, if you COMMIT the DELETE, our UPDATE statement will delete nothing:

UPDATE 0

How did this happen? It is true that the entire query sees the same state

[...]
Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-29 07:00 am

Tudor Golubenco: Going down the rabbit hole of Postgres 18 features

A comprehensive list of PostgreSQL 18 new features, performance optimizations, operational and observability improvements, and new tools for devs.
Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-29 03:37 am

Ian Barwick: PgPedia Week, 2025-09-28

PostgreSQL 18 was released on schedule this week!

PostgreSQL 18 articles Exploring PostgreSQL 18 – Part 1: The COPY Command Gets More User-Friendly (2025-09-28) - Deepak Mahto Postgres 18: OLD and NEW Rows in the RETURNING Clause (2025-09-26) - Brandur Leach / Crunchy Data PostgreSQL: "UPDATE … RETURNING" made even better (2025-09-25) - Hans-Jürgen Schönig / CYBERTEC PostgreSQL 18: part 5 or CommitFest 2025-03 (2025-09-25) - Pavel Luzanov / PostgresPro Parallel Apply of Large Transactions (2025-09-24) - Amit Kapila Celebrating the PostgreSQL 18 Release (2025-09-24) - EnterpriseDB Tuning AIO in PostgreSQL 18 (2025-09-24) - Tomas Vondra Changes to NOT NULL in Postgres 18 (2025-09-23) - Álvaro Herrera / EnterpriseDB PostgreSQL 19 changes this week

Development continues apace, but no user-visible features were committed this week. See the Commits of Interest list below for more details on changes.

more...

egorius: (Default)
egorius ([personal profile] egorius) wrote2025-09-29 10:30 pm

Навеяло

Тот случай, когда музыка в лифте гостиницы нравится больше, чем потуги специально приглашенной кавер-группы®.

Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-28 06:12 pm

Безнадежность

Posted by temalebedev

Я безнадежен для человечества. Я ничего не умею. Я ничего не знаю. Я ни на что не способен.

Я никогда бы не изобрел способ получения металла из руды. Никогда бы не придумал как делать хлеб из муки, а тем более как сделать муку из пшеницы. Никогда бы не обнаружил нихуя в космосе, я даже смутно представляю, где встает и садится солнце, что уж говорить про луну.

Я бы не изобрел понятие "нуля" в математике, не открыл бы принципов химии и биологии, не придумал бы микроскоп, даже очки бы не создал. Не смог бы додуматься до книгопечатания, полупроводников, вакцинирования, сварки, ныряния с аквалангом.

Если бы все человечество было как я, мы бы до сих пор жили бы бы в докембрии, потому что даже высекание огня трением для меня - недостижимая интеллектуальная высота.

Я бы никогда не догадался расщепить булыжник для получения топора, потому что этот текст я набираю десятипальцевым слепым методом на клавиатуре макбука.

Для эволюции человечества я максимально бесполезен.

Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-28 06:10 pm

Поддержка суеверий

Posted by temalebedev

Я очень хорошо отношусь к суевериям и повериям.

Если нужно потереть часть статуи, приложиться к камню плодородия, произнести мантру, выпить на удачу, посидеть на дорожку, плюнуть через плечо, покормить духа огня, перекреститься, то я с радостью все это сделаю.

Мне не жалко, а материалистический мир не может обидеться по определению.

House of the Scrambling Sign ([syndicated profile] hardsign_lj_feed) wrote2025-09-29 07:40 am

О китайцах

Прочитал книгу Алексея Рязанцева «Китайцы. Руководство по применению».

Категорически рекомендую всем, кто ратует за китайский путь развития или просто кивает на Китай, мол, они смогли, а наши не могут. Отдельно отмечу вот это вот «наши» вместо «мы», как будто автору высказываний кто-то обязан обеспечить в России китайское экономическое чудо.

Тезисно:

  • У нас есть шутки типа «вам как — по закону или по справедливости?», и мы свысока смотрим на Запад, где закон выше справедливости, а обойти справедливость, исполнив букву закона, считается доблестью. У китайцев эта ручка выкручена до упора в обратную сторону: понятия и дружеские связи гораздо важнее любых ТЗ и договоров, ну а если друга понял как-то не так, то друг ведь простит, да?
  • Мы говорим «работать надо не 12 часов в сутки, а головой». Китайцы могут работать не 12 часов в сутки, а 16, а если аврал, то и 26. Стремление к оптимизации — это не про них.
  • Анекдот про мышей, которые едят кактус, — это не анекдот. Автор пытался сделать бизнес на посредничестве между европейцами и китайцами, но не преуспел: никому в Европе не нужно чёткое выполнение ТЗ и выдерживание сроков, всем нужна только низкая цена. Автор пытался продавать китайцам оригинальный дизайн и качественное ПО, но тоже не преуспел: никому в Китае не нужно делать что-то оригинальное и качественное, всех устраивает роль сборочного цеха, где думать уже не надо. Cactus quo сохраняется.

Ну и да, как обычно призываю всех читать первоисточник, а не верить перепеву в ЖЖ.

Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-28 06:09 pm

Кура и греча

Posted by temalebedev

В разных городах есть свои языковые особенности.

Скажем, в Питере говорят и пишут кура вместо курица и греча вместо гречка. Московские консультанты-снобы обычно советуют не выебываться и писать по-московски.

А я считаю, что нужно максимально втапливать за свои региональные особенности. Ну говоришь ты "булка" вместо "белый хлеб" - так и заяви, что это гражданская позиция. И тогда в разных местах страны мультифора победит файлик, а шуфлядка - выдвижной ящик стола.

Мое отношение к разным языковым нормам - каждый дрочит, как он хочет.

Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-29 06:33 am

Jeremy Schneider: Losing Data is Harder Than I Expected

This is a follow‑up to the last article: Run Jepsen against CloudNativePG to see sync replication prevent data loss. In that post, we set up a Jepsen lab to make data loss visible when synchronous replication was disabled — and to show that enabling synchronous replication prevents it under crash‑induced failovers.

Since then, I’ve been trying to make data loss happen more reliably in the “async” configuration so students can observe it on their own hardware and in the cloud. Along the way, I learned that losing data on purpose is trickier than I expected.


Methodology and a Kubernetes caveat

To simulate an abrupt primary crash, the lab uses a forced pod deletion, which is effectively a kill -9 for Postgres:

kubectl delete pod -l role=primary --grace-period=0 --force --wait=false

This mirrors the very first sanity check I used to run on Oracle RAC clusters about 15 years ago: “unplug the server.” It isn’t a perfect simulation, but it’s a simple, repeatable crash model that’s easy to reason about.

I should note that the label role is deprecated by CNPG and will be removed. I originally used it for brevity, but I will update the labs and scripts to use the label cnpg.io/instanceRole instead.

After publishing my original blog post, someone pointed out an important Kubernetes caveat with forced deletions:

Irrespective of whether a force deletion is successful in killing a Pod, it will immediately free up the name from the apiserver. This would let the StatefulSet controller create a replacement Pod with that same identity; this can lead to the duplication of a still-running Pod

https://kubernetes.io/docs/tasks/run-application/force-delete-stateful-set-pod/

This caveat would apply to the CNPG controller just like a StatefulSet controller. In practice, for my tests, this caveat did not undermine the goal of demonstrating that synchronous replication prevents data loss. The lab includes an automation script (Exercise 3) to run the 5‑minute Jepsen test in a loop for ma

[...]
Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-29 06:00 am

Hans-Juergen Schoenig: PostgreSQL 18 and beyond: From AIO to Direct IO?

PostgreSQL 18 is such an exceptional piece of software - it is hard to imagine anything better, right? I remember a similar thought when PostgreSQL 7 was released (“wow, how cool is that - this is it”). Well, let me put it mildly: I was wrong, and things are a lot better than they used to be. So, obviously the idea that PostgreSQL 18 is as far as humanity can go is also wrong. But what might be next?

Synchronous IO, Asynchronous I/O, Direct I/O?

The question is: While a major step forward has been made in PostgreSQL 18, and an important milestone has been achieved … is there anything out there that is even cooler? Something we might see in a couple of years? Well, maybe: I am of course talking about “Direct I/O”.

What is Direct I/O?

Under normal circumstances, a read works like this:

  • Application requests some data
    • Kernel accepts the read 

      • does sanity checks

      • cache lookup happens

        • if needed data is read from disk

        • otherwise the filesystem cache serves the data
    • Application receives an OK

Sounds good? Well it is, and in most cases this is exactly what we want. However, there is an additional method: Direct IO. What it does can be summed up in one sentence:  DirectIO bypasses the OS page cache layer. 

But let us take a look at more detail: The good part is that it skips the overhead and scalability limitations. The bad part is that it skips the services that layer provi

[...]
Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-28 09:01 pm

Ian Barwick: PgPedia Week, 2025-09-21

PostgreSQL 19 changes this week encode() / decode() : support for base64url format added extension_control_path : only the first extension name found in the path will be shown by extension availability views logical_replication : conflict-relevant data retention will now be automatically resumed pg_replication_origin_session_setup() : parameter pid added function lookup failures will now have more specific error details/hints provided PostgreSQL 19 articles Waiting for PostgreSQL 19 – Add date and timestamp variants of random(min, max). (2025-09-17) - Hubert 'depesz' Lubaczewski PostgreSQL 18 articles PostgreSQL 18: Better I/O performance with AIO (2025-09-19) - Hans-Jürgen Schönig / CYBERTEC Preview PostgreSQL 18's OAuth2 Authentication (3) - Enhancing a PostgreSQL Client Library to Speak OAUTHBEARER (2025-09-19) - Guang Yi Xu / EnterpriseDB Preview PostgreSQL 18’s OAuth2 Authentication (2) - Building a Custom OAuth2 Validator by Rust (2025-09-17) - Guang Yi Xu / EnterpriseDB Preview PostgreSQL 18’s OAuth2 Authentication (1) - Explore How it Works (2025-09-15) - Guang Yi Xu / EnterpriseDB

more...

Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-28 06:24 am

Жесть

Posted by temalebedev

Пиздец, больше всего на свете я ненавижу запах жестяных консервных банок с персиками и ананасами.

Если открыть компот и быстро перелить содержимое в стекло, то еще терпимо. А в жестяной банке если похранить, получается просто блевота.

Поэтому для простоты я всегда покупаю ананасы и персики в стекле, там никаких посторонних запахов нет.

Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-28 12:58 pm

Dave Stokes: PostgreSQL 18 Release Notes

 The PostgreSQL 18 Release Notes are like a great noir novel, full of surprises and intrigue. But we know who did it - the amazing PostgreSQL community.

If you have not perused the Notes, I advise you to do so now. They contain many of what I call 'Wow!' level items, such as the redesigned I/O subsystem, skip scan lookups, virtual generated columns, and more.  The new Uuidv7 function and temporal constraints would be a significant leap forward. The OLD and NEW support for RETURNING will help lessen the learning curve for many who are new to SQL.

But go down to the seemingly more mundane items. Removing redundant self-joins, merge-joins can now use incremental sorts, and internally reordering the keys of SELECT DISTINCT to avoid sorting are the types of improvements that are not as attention-getting as the items in the preceding paragraph, but will make life much nicer for us. 

Each release of PostgreSQL is faster than the previous one, and early reports report that this has happened again. This is an astounding delivery for those of us with backgrounds in other databases. All too often, new features came with a trade-off in performance that relegated upgrades to the back burner.

Please read the Acknowledgments. This is a list of the good folks who have worked very hard on our behalf to deliver an improved version of PostgreSQL. And they are already working on 19! If you run into any of them, please give them a big 'thank you'.  

жежешечка ([syndicated profile] taurus_ek_lj_feed) wrote2025-09-28 08:11 am

Демофонт и Мастусий с точки зрения ИИ

Очередной эксперимент с генерацией картинок Sora от Гугла.

История такая. В херсонесском городе Элеунт началась эпидемия, и правитель города Демофонт получил оракул, что остановить мор можно, принося в жертву дев знатного рода. Он начал это делать по жребию, однако своих дочерей не включал в жеребьевку. Некий Мастусий возмутился; тогда Демофонт принес его дочь во внеочередную жертву и мор прекратился. Мастусий сделал вид, что не ропщет на случившееся, и даже позвал Демофонта с дочерьми на пир. Там клевреты Матусия заманили и убили приглашенных дочерей, и хозяин напоил неведающего гостя вином, смешанным с их кровью. (В скобках: по Гигину, чаша с кровью - созвездие Чаша.)


20250928_1054_Реалистичная картина_remix_01k67mza98fwcbwb5m5qfntqhs.png


Пришлось поколдовать, чтобы получить такое нормонарушающее.

P.S. Хотя, конечно, левая рука Демофонта... да... длинновато получилось )
Артемий Лебедев ([syndicated profile] temalebedev_feed) wrote2025-09-28 06:23 am

Вечные фильмы

Posted by temalebedev

Какие фильмы вы можете смотреть вечно?

Я вот могу каждый год пересматривать "Белое солнце пустыни" и "Место встречи изменить нельзя" (по две любые серии из четырех).

А вы?

Planet PostgreSQL ([syndicated profile] planet_pgsql_short_feed) wrote2025-09-28 06:39 am

Deepak Mahto: Exploring PostgreSQL 18: A Developer’s Guide to New Features – Part 1: The COPY Comman

PostgreSQL 18 was released on September 25, 2024, introducing a host of exciting new features across all major areas. In this blog series, we’ll delve into these features and explore how they can benefit database developers and migration engineers transitioning to PostgreSQL.

Part 1 of the series focuses on enhancements to the COPY command, particularly for use cases involving loading external files into the database.

PostgreSQL 18 – Enhancements with the COPY Command

The COPY command is the default native option for loading flat files, primarily in text or CSV format, into PostgreSQL. If you are a data engineer or database developer looking for ways to load flat files into PostgreSQL, you must take care of quality checks and encapsulate a mechanism to report or discard failed records.

Until PostgreSQL 16, if quality checks were planned to be done on the database side, one option was to load flat files into staging tables with all columns as text or a generic data type and later move legitimate and discarded data to the concerned tables.With PostgreSQL 17 onward, the COPY command provides options for handling data type incompatibilities and logging failed rows or records using on_error options.

In PostgreSQL 18 these features is further enhances with REJECT_LIMIT options. If overall discarded or error row data is beyond the reject limit the copy command is discarded as whole.

PostgreSQL 18 – New REJECT_LIMIT option.

Let’s start by creating sample target tables and a CSV file with intentional data type mismatch issues. The sample table also has check and NOT NULL constraints defined on it.

CREATE TABLE copy18(
    col1 integer,
    col2 text DEFAULT 'x'::text,
    col3 text NOT NULL,
    col4 text,
    col5 boolean,
    col6 date,
    col7 timestamp without time zone
    CONSTRAINT copy18_col4_check CHECK (length(col4) > 2)
);

The CSV file contains data type incompatibilities in the following lines:

  • Timestamp (4th line)
  • Integer (5th line)
  • Boolean type (7t
[...]
House of the Scrambling Sign ([syndicated profile] hardsign_lj_feed) wrote2025-09-28 07:15 am

О пофиге

Прочитал очередное заклинание на тему, как нейросети всех нас заменят. Ну и разумеется, источник паники и комментарии. И похоже, я понял, к чему идёт дело.

Но для начала цитата из «Атланта», который «расправил плечи»:

– Мы хотим, чтобы ты взял это на себя!.. Мы хотим, чтобы ты управлял!.. Мы приказываем тебе приказывать!.. Требуем, чтобы ты стал диктатором!.. Приказываем тебе спасти нас!.. Приказываем тебе думать!..
Ответом им был лишь стук сердца, от жизни которого зависели и их жизни.

Так вот, роман Айн Рэнд — не про живительную силу капитализма, а про людей, которым не всё равно. По мнению автора, которое я разделяю (или которое приписываю автору), именно воля и есть та движущая сила, благодаря которой самолёты летают, компьютеры считают, а вода иногда течёт не только вниз, но и вверх. Насосы, процессоры, и прочее оборудование, пусть даже самое высокотехнологичное, — это всего лишь инструменты.

Есть класс задач настолько сложных, что с ним пока не справляется механизм, и приходится нанимать человека, который «делает, что сказали». Вот таких людей, которым пофиг, нейросеть действительно может заменить, и особенной трагедии в этом я не вижу.

А вот именно волю тех людей, которым не пофиг, никакая нейросеть не заменит. Во всяком случае, очень надеюсь, что я до этого не доживу.