I recently had a technical interview where I was asked about multicolumn indexes.I brought up an example: an index on (a, b, c). If a query filters only on b and c, I wouldn’t expect PostgreSQL to use that index. Column order matters, and the query skips the leading column, a.I was told I was wrong and that the index would be used. No one explained why.After the interview, I tested it. I created a table with 100,000 rows, inserted numbers in random order, and added an index on (a, b, c). For a query filtering on b and c, PostgreSQL chose a sequential scan.If you ask this question in an interview or tell someone their answer is wrong, at least specify which PostgreSQL version you mean and explain your reasoning. Candidates shouldn’t have to guess.PostgreSQL 18 introduced skip scans, which can make this index useful even without a condition on a. But PostgreSQL 18 isn’t widely used everywhere yet. Earlier versions can also use the index, but they would have to scan the whole thing, so PostgreSQL will often choose a sequential scan instead.So «the index will be used» is just as questionable as «the index won’t be used» if you don’t know the version, the data, or the query plan.
1 Aralık 2026 Salı
MultiColumn Index - Skip Scans
Açıklaması şöyle
29 Kasım 2026 Pazar
Parameter-sensitive query planning - Prepared Statement Generic Plan vs Custom Plan Problem
Örnek
Burada bir örnek var
Lnux - vm.swappiness
Açıklaması şöyle
Linux üzerinde veritabanı koşturan sunucularda en sık rastlanan garipliklerden biri şudur: Sunucuda 256 GB RAM vardır, 100 GB'ı boş görünüyordur ama işletim sistemi gitmiş veritabanının belleğini diske (swap alanına) yazmaya başlamıştır.Sonuç:Rastgele zamanlarda saniyeler süren sorgu kilitlenmeleri ve anlamsız disk I/O sıçramaları.Sebep:Linux çekirdeği varsayılan olarak "vm.swappiness = 60" değeriyle gelir. Bu ayar genel amaçlı sunucular veya masaüstü sistemler için uygundur; Linux boşta gördüğü belleği dosya önbelleğine (page cache) ayırmak için çalışan process'lerin hafızasını agresif şekilde swap'e taşır.Ancak bir PostgreSQL veya SQL Server çalıştırıyorsanız durum farklıdır. Veritabanı engine'i kendi önbelleğini (buffer pool / shared_buffers) işletim sisteminden çok daha iyi yönetir. Veritabanı sayfalarının diske takaslanması performansı doğrudan öldürür.Çözüm:Veritabanı sunucularında swappiness değerini 1'e düşürmek gerekir. (0 yapmak OOM-Killer riskini artırabileceği için önerilmez, 1 en güvenli alt sınırdır.)Anlık uygulamak için:sudo sysctl -w vm.swappiness=1Kalıcı hale getirmek için /etc/sysctl.conf dosyasına ekleyin:vm.swappiness = 1Sunucuda bolca boş RAM varken diskin swap ile boğulmasını bu tek satırla engelleyebilirsiniz.
19 Kasım 2026 Perşembe
16 Kasım 2026 Pazartesi
Active-Active Replication
pgactive ile gerçekleştirilir
10 Kasım 2026 Salı
Transaction Isolation Level - Serializable
Örnek
Şöyle yaparız
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;SELECT *FROM doctorsWHERE status = 'ON_CALL';
Örnek
Şöyle yaparız
40001 hatası verir. Elimizde şöyle bir kod olsun.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class OrderService {
@Transactional(isolation = Isolation.SERIALIZABLE)
public OrderResult placeOrder(OrderRequest request) {
// 1. Read current database state (e.g., check stock count)
// 2. Validate business rules (e.g., is stock > 0?)
// 3. Apply database modifications (e.g., deduct stock, save order)
return new OrderResult("Success");
}
}import org.springframework.dao.PessimisticLockingFailureException;import org.springframework.stereotype.Component;import java.sql.SQLException;@Componentpublic class TransactionRetryManager {private final OrderService orderService;public TransactionRetryManager(OrderService orderService) {this.orderService = orderService;}public OrderResult processWithRetry(OrderRequest request) {int maxAttempts = 3;for (int attempt = 1; attempt <= maxAttempts; attempt++) {try {// Try executing the transactional methodreturn orderService.placeOrder(request);} catch (RuntimeException ex) {// Check if this exception was caused by Postgres SQLSTATE 40001if (!isSerializationFailure(ex)) {throw ex; // It's a different error (e.g., bad SQL syntax), give up immediately}// If we ran out of attempts, stop retrying and throw the errorif (attempt == maxAttempts) {throw ex;}// Optional: Add a brief pause (backoff) here before trying again}}throw new IllegalStateException("Unexpected retry state reached");}private boolean isSerializationFailure(RuntimeException ex) {// Look down the exception chain to find the root JDBC SQLExceptionThrowable cause = ex.getCause();while (cause != null) {if (cause instanceof SQLException sqlEx) {// Deterministically match the exact Postgres serialization error codeif ("40001".equals(sqlEx.getSQLState())) {return true;}}cause = cause.getCause();}return false;}}
2 Kasım 2026 Pazartesi
Patroni - High Availability İçindir
Giriş
Açıklaması şöyle. Yani primary_restart_timeout süresi içinde PG ayağa kalkarsa lider değişmez.
Patroni ile yönetilen bir PostgreSQL cluster’ında lider restart olduğu halde lider neden değişmez?HA denince akla genelde “lider gittiği an replica devreye girer” fikri geliyor. Oysa ister MSSQL Always On olsun ister Patroni, iki tarafta da kısa ve toparlanabilir bir kesinti için hemen failover yapılmıyor. Patroni tarafında bunun nasıl işlediğine bakalım.Patroni liderliği DCS üzerinde tutulan bir lock ile yönetiyor. Lider node’daki Patroni bu lock’u düzenli olarak yeniledikçe diğer node’lar lider olmaya kalkmıyor. PostgreSQL process’i çökse bile Patroni ayaktaysa lock yenilenmeye devam ediyor ve Patroni PG’yi aynı node üzerinde tekrar başlatıyor. Failover ancak lock’un süresi dolduğunda ya da PG belirlenen süre içinde ayağa kalkamadığında devreye giriyor.Bu tercih kesintiyi uzatıyor gibi görünse de çoğu zaman tam tersi oluyor. Yerinde bir restart genelde birkaç saniyede tamamlanır. Failover’da ise önce liderin gerçekten gittiğinden emin olmak için beklemek, ardından promote ve trafiğin yeni lidere yönlenmesi gerekir. Asenkron replikasyonda buna bir de veri kaybı riski eklenir.Failover olduğunda işin bir de timeline tarafı var. Promote olan replica yeni bir timeline açıyor ve eski timeline’dan hangi noktada ayrıldığını bir history dosyasına yazıyor. Eski lider geri döndüğünde Patroni onun son WAL konumunu bu ayrışma noktasıyla karşılaştırıyor.Eski liderde yeni liderin hiç görmediği kayıtlar yoksa node doğrudan replica olarak devam ediyor. Varsa ve use_pg_rewind açıksa pg_rewind bu kayıtları atıp node’u yeni liderle hizalıyor. Rewind’in çalışabilmesi için data_checksums ya da wal_log_hints açık olmalı. Rewind kapalıysa ya da başarısız olursa geriye reinit, yani replica’yı baştan kopyalamak kalıyor.Burada sık gözden kaçan bir detay var. Asenkron modda rewind’in attığı kayıtlar, uygulamaya commit onayı verilmiş gerçek veriler olabilir. Senkron modda ise atılan kayıtlar henüz onaylanmamış işlemler. Rewind iki durumda da çalışabilir ama sonuçları aynı değil.Bir DBA olarak bu LSN karşılaştırmalarını çoğu zaman elle yapmıyoruz, o işi Patroni yapıyor. Bize düşen, patronictl list çıktısını ve Patroni loglarını doğru okumak. Node streaming durumdaysa ve timeline’ı liderle aynıysa sorun yok. Değilse sebebi loglarda
10 Eylül 2026 Perşembe
Graph Database
Giriş
Açıklaması şöyle
PostgreSQL, in their latest release, version 19, has shipped property graphs.We can now define a graph over our existing relational tables and query them. So, no need to install new extensions or run migrations.Let me give you an example. If you already have tables like users, follows, posts, today, we would need to write joins to answer questions like "who follows who" or "which posts got liked by friends of friends."But with this, we can just declare users as vertices and follows as edges, then query the relationship directly using pattern-matching syntax instead of chaining joins. And, this is apt for all graph use cases like:- social graphs- fraud detection- data lineage- dependency graphs, etc.Btw, this graph is a read-only view over your existing tables, and a really powerful part is that we can mix a graph query and a normal SQL query in the same statement.Of course, it is not as performant or powerful as regular graph databases (yet), but it is a pretty solid choice when you are in your 0 to 1 journey.You know things are serious when PG gets it as first-class support. Graphs are certainly cool again. Also, looks like this will forever remain true:Just use Postgres :)
In-memory database
Giriş
Açıklaması şöyle
Did you know you can make PostgreSQL run almost fully in-memory?Postgres docs explicitly describe a non-durable setup where you can put the whole data directory on a RAM disk and disable:fsync: don’t force writes to durable storagesynchronous_commit: don’t make COMMIT wait for WAL to flushYou basically trade durability for speed.Pretty interesting that PostgreSQL can be pushed this far without switching to a separate in-memory database.It’s a game-changer for running in CI, it’s so much faster
30 Nisan 2026 Perşembe
postgresql.conf Dosyası - work_mem Alanı
Açıklaması şöyle
PostgreSQL uses the work_mem configuration parameter to determine the amount of memory available for sorting and hashing operations. Properly configuring work_mem can greatly impact the performance of queries involving sorting or hash joins.Configuring the work_mem parameter in PostgreSQL is crucial for optimizing query performance, but it requires finding the right balance. Increasing work_mem on high-performance systems can speed up sorting and hashing operations, leading to faster query execution.However, setting it too high might cause excessive memory usage and potential memory contention, impacting overall performance. To determine the ideal work_mem value, start conservatively and monitor system performance while gradually increasing it. Keep a close watch on memory consumption and query execution times. Additionally, consider using partitioned queries or limiting result set sizes for resource-intensive queries to prevent excessive memory usage. Striking the right balance ensures PostgreSQL operates efficiently without overwhelming system memory and maximizes the benefits of work_mem for improved query performance.
Örnek
Şöyle yaparız
SET work_mem = "128MB";
Örnek
Sorgum neden bu kadar yavaş diye saatlerce baktın. Sorun sorguda değildi.EXPLAIN çıktısında "external merge Disk" yazıyordu. PostgreSQL sıralama işlemini RAM'de bitirememiş, diske taşmıştı. work_mem 4MB'da kalmış, varsayılan değerden hiç çıkmamıştık.PostgreSQL bellek yetmediğinde hata vermez, sessizce diske geçer. Sorgu yine de sonuç döndürür ama 200 milisaniyede bitmesi gereken iş 4 saniyeye uzar. Fark edilmesi zordur, çünkü sistem sizi uyarmaz.
6 Mart 2026 Cuma
PostgreSQL Health Check List
Giriş
Yazıyı buradan aldım
The PostgreSQL health check I run on every new database.Doesn't matter if it's a fresh install or a production instance someone hands me. Same checklist, every time.Here's what I look at first:Autovacuum settings. Is it actually running? Are the thresholds sane for the table sizes? Default scale_factor of 0.2 is fine for small tables but terrible for anything with millions of rows.Missing indexes. I check pg_stat_user_tables for tables with high sequential scan counts relative to index scans. If a table has 500k seq_scans and 12 idx_scans, something is wrong.Connection limits. How many connections are configured vs. how many are actually in use? I've seen instances running at 95% of max_connections with no connection pooler in sight.Replication lag. If there's a replica, how far behind is it? Seconds of lag might be acceptable. Minutes means trouble.Table bloat. Dead tuples piling up means autovacuum is either misconfigured or can't keep up. This is where most "the database is slow" complaints start.Idle transactions. Long-running idle-in-transaction sessions hold locks and block autovacuum. They're silent killers.I got tired of running through this manually on every instance, so I built these checks (and about 50 more) into mydba.dev. It runs them regularly and flags anything that needs attention.
2 Mart 2026 Pazartesi
Backup Araçları
Databasus
Açıklaması şöyle
Databasus is an industry standard for PostgreSQL backup tools, offering scheduled backups with compression and encryption for both individual developers and enterprise teams.
5 Aralık 2025 Cuma
pgloader
Örnek
Şöyle yaparız
pgloader mysql://user:pass@10.10.10.10:3306/zabbix \postgresql://user:pass@10.10.10.1:31320/zabbix
8 Ekim 2025 Çarşamba
pg_ivm - PostgreSQL Incremental View Maintenance
Giriş
Açıklaması şöyle
Açıklaması şöylean extension that transforms materialized views into self-updating, always-fresh data structures that update instantly as your base data changes.
Under the Hood: How pg_ivm WorksWhen you create an incremental materialized view, pg_ivm automatically:1. Installs triggers on all referenced base tables2. Captures changes through INSERT/UPDATE/DELETE monitoring3. Calculates deltas to determine the minimal impact4. Updates the view with only the necessary changes
REFRESH MATERIALIZED VIEW CONCURRENTLY - The Non-Blocking Approach
Giriş
Açıklaması şöyle.
The Good: Allows queries during refresh (requires a unique index)The Bad: Still recomputes the entire view from scratchThe Reality: Better UX, but still expensive and slow for large datasets.
Şöyle yaparız
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_summary;
REFRESH MATERIALIZED VIEW - Manual Refresh
Giriş
Açıklaması şöyle. Alternatif olarak REFRESH MATERIALIZED VIEW CONCURRENTLY kullanılabilir
The Good: Simple and straightforwardThe Bad: Locks the entire view during refresh, blocking all queriesThe Reality: Your users stare at loading spinners while the view rebuilds
Şöyle yaparız
REFRESH MATERIALIZED VIEW sales_summary;
18 Ağustos 2025 Pazartesi
Soft deletes vs. Journal tables
Örnek
create_journal_table() metodu şöyledir. Bu metod EVENT TRIGGER HANDLER içindir.
CREATE OR REPLACE FUNCTION create_journal_table()RETURNS event_triggerLANGUAGE plpgsqlAS $$DECLAREobj record;schema_name text;table_name text;journal_table_name text;BEGINFOR obj INSELECT * FROM pg_event_trigger_ddl_commands()LOOPIF obj.command_tag = 'CREATE TABLE' AND obj.object_type = 'table' THENschema_name := split_part(obj.object_identity, '.', 1);table_name := split_part(obj.object_identity, '.', 2);schema_name := trim(both '"' from schema_name);table_name := trim(both '"' from table_name);-- Skip journal tables to avoid recursionIF right(table_name, 8) = '_journal' THENCONTINUE;END IF;journal_table_name := format('%I.%I_journal', schema_name, table_name);EXECUTE format('CREATE TABLE IF NOT EXISTS %s (id bigserial PRIMARY KEY,action text NOT NULL,changed_at timestamptz DEFAULT now(),old_data jsonb,new_data jsonb)', journal_table_name);EXECUTE format('CREATE TRIGGER %I_to_journalAFTER INSERT OR UPDATE OR DELETE ON %I.%IFOR EACH ROWEXECUTE FUNCTION log_to_journal()',table_name, schema_name, table_name);END IF;END LOOP;END;$$;
Bu metodu register ederiz. Metod şöyledir. Bu metod CREATE EVENT TRIGGER içindir.
CREATE EVENT TRIGGER create_journal_after_table
ON ddl_command_end
WHEN TAG IN ('CREATE TABLE')
EXECUTE FUNCTION create_journal_table();log_to_journal() metodu şöyledir. Bu metod row level logging yapar
CREATE OR REPLACE FUNCTION log_to_journal()RETURNS triggerLANGUAGE plpgsqlAS $$DECLAREjournal_table text;BEGINjournal_table := format('%I.%I_journal', TG_TABLE_SCHEMA, TG_TABLE_NAME);IF TG_OP = 'INSERT' THENEXECUTE format('INSERT INTO %s (action, old_data, new_data) VALUES ($1, $2::jsonb, $3::jsonb)',journal_table)USING TG_OP, NULL, to_jsonb(NEW);ELSIF TG_OP = 'UPDATE' THENEXECUTE format('INSERT INTO %s (action, old_data, new_data) VALUES ($1, $2::jsonb, $3::jsonb)',journal_table)USING TG_OP, to_jsonb(OLD), to_jsonb(NEW);ELSIF TG_OP = 'DELETE' THENEXECUTE format('INSERT INTO %s (action, old_data, new_data) VALUES ($1, $2::jsonb, $3::jsonb)',journal_table)USING TG_OP, to_jsonb(OLD), NULL;END IF;RETURN NULL; -- AFTER triggerEND;$$;
20 Nisan 2025 Pazar
JSON_TABLE
Giriş
Açıklaması şöyle
Use JSON_TABLE() to transform JSON data into tabular format.
Örnek
Şöyle yaparız
SELECT *FROM JSON_TABLE('[{"name":"Alice","age":30},{"name":"Bob","age":25}]','$[*]'COLUMNS(name TEXT PATH '$.name', age INT PATH '$.age')) AS jt;
MERGE ... RETURNING - Postgres 17 İle Geliyor
Giriş
Açıklaması şöyle
You can now use it MERGE ... RETURNING to retrieve rows that were inserted, updated, or deleted—all in one go.
Örnek
Şöyle yaparız
MERGE INTO employees AS eUSING new_data AS dON e.id = d.idWHEN MATCHED THENUPDATE SET salary = d.salaryWHEN NOT MATCHED THENINSERT (id, salary) VALUES (d.id, d.salary)RETURNING *;
14 Ocak 2025 Salı
postgresql.conf Dosyası - Log Ayarları
log_min_duration_statement
Açıklaması şöyle
log_min_duration_statement: just logging the statements whose duration is more than this value in milliseconds. This is very useful for detecting slow queries.
Açıklaması şöyle
It sets the minimum execution time in milliseconds (ms) above which all statements will be logged.The default value for the log_min_duration_statement parameter is -1, which disables logging statements.Setting the PostgreSQL parameter log_min_duration_statement to 0 will print all statements' durations.
Örnek
Şöyle yaparız
# set log_min_duration_statement=1;SET # show log_min_duration_statement; log_min_duration_statement ---------------------------- 1ms (1 row)
PostgreSQL log dosyalarındaki statement log cümleleri şöyledir
LOG: duration: 5.477 ms statement: insert into abc values(1); LOG: duration: 8.656 ms statement: insert into abc values(2);
log_statement
ALL, MOD,DDL değerlerini alabilir
Açıklaması şöyle
Most fintech companies, who are required to log all user and application activities, set the most verbose option log_statement=all. This is the easiest way to bloat the log files and invite storage issues if storage consumption is not monitored. Pg_audit can be a smarter way of logging user activities, where you can specify which class of activities you want to log, such as READ, WRITE, DDL, or FUNCTION.
log_statement_sample_rate
Açıklama yaz
log_destination
Bu alanlar için Audit Trails yazısına bakabilirsiniz
PostgreSQL 15 için açıklama şöyle
PostgreSQL supports several methods for logging server messages, including stderr (default), csvlog, and syslog. With this release, jsonlog is also supported which is convenient for exporting logs and debugging. In order to enable this, add the jsonlog under the log_destination inside the postgresql.conf file.
This will be a nice feature to have with exports to logging and monitoring tools like HoneyComb and DataDog etc.
Kaydol:
Kayıtlar (Atom)