Wednesday, December 2, 2026

Max Server Memory

Açıklaması şöyle
Kubernetes üzerinde PostgreSQL veya SQL Server koştururken pod'un belleğini ayarlamak standart bir stateless microservice'e benzemez.

Yapılan en büyük hata şudur:
Pod için `limits.memory: 16Gi` verilir, ardından veritabanının önbellek parametresi de (PostgreSQL'de shared_buffers, SQL Server'da max server memory) tam 16 GB veya 14 GB olarak ayarlanır.

Birkaç gün sonra pod hiçbir log bırakmadan aniden yeniden başlar: Exit Code 137 (OOMKilled).

Bunun nedeni:
Veritabanı hafızası sadece veri önbelleğinden ibaret değildir.
• Açılan her client bağlantısı kendi hafıza alanını tüketir (Postgres'te work_mem, maintenance_work_mem).
• İşletim sistemi sayfa tabloları (page tables) ve disk tamponları cgroup sınırına dahil edilir.
• Geçici sorgu sıralamaları ve karmaşık join işlemleri hafızayı anlık olarak yukarı fırlatır.

Pod'un Linux cgroup sınırına çarpıp kernel tarafından öldürülmesini engellemek için şu oran kuralı uygulanmalıdır:

Veritabanının maksimum bellek kullanımını (shared_buffers / max server memory), pod limitinin en fazla %65 - %70'ine sabitleyin. 
Kalan %30 - %35'lik payı bağlantı havuzuna, geçici sorgu işlemlerine ve işletim sistemi tamponlarına bırakın.

Örneğin pod için 16 GiB sınırınız varsa, veritabanı çekirdeğine 10-11 GiB'den fazla alan tanımlamayın.

Monday, November 30, 2026

Compression

1. Row Compression
Örnek
Şöyle yaparız
CREATE TABLE dbo.RowStorageDemo
(
    RecordId INT NOT NULL,
    DepartmentCode CHAR(20) NOT NULL,
    Quantity BIGINT NOT NULL,
    TotalAmount DECIMAL(12, 2) NULL
)
WITH (DATA_COMPRESSION = ROW);

2. Page Compression
Row compression + prefix compression ve dictionary compression olarak düşünülebilir

Prefix compression
Açıklaması şöyle
Prefix compression allows SQL Server to store a shared prefix within a special compression information structure on the page.
Örneğin bir sütünda müşteri bilgisi vep CUSTOMER- şeklinde başlıyorsa işe yarar

Dictionary Compression
Açıklaması şöyle
This technique searches for repeated byte sequences throughout the page, without restricting the search to the beginning of values or a particular column.
Örnek
Şöyle yaparız
CREATE TABLE dbo.CustomerReferenceDemo
(
    RecordId INT NOT NULL
        PRIMARY KEY CLUSTERED,
    CustomerReference VARCHAR(30) NOT NULL,
    RegionCode VARCHAR(20) NOT NULL
)
WITH (DATA_COMPRESSION = PAGE);

Friday, November 27, 2026

INSTEAD OF INSERT Trigger

Örnek
Şöyle yaparız
CREATE TRIGGER Foo_Redirect
ON Foo
INSTEAD OF INSERT
AS

BEGIN
  SET NOCOUNT OM;
  INSERT INTO Bar(CreatedAt,ProtocolNo,SubType,TableName,FieldName,FieldBuffer)

  SELECT 
    ISNULL(ModifDate, GETUTCDATE()),
    ProtocolNo,
    SubType,
    TableName,
    FieldName,
    RecBuffer
  FROM inserted
END;

Tuesday, November 24, 2026

System-Versioned Temporal Table

Create a system-versioned temporal table ve

Ne İşe Yarar
Elimizde şöyle bir sql olsun
UPDATE Employee SET Salary = 6000 WHERE Id = 1;
SQL server şunları yapar
SQL Server automatically:
1. Copies the old row into EmployeeHistory.
2. Updates the current row in Employee.
3. Maintains the validity timestamps.

İki Tane Sütun Lazım
SQL Server uses two special columns:

- ValidFrom: When this version became valid.
- ValidTo: When this version stopped being valid.

These timestamps are managed automatically by SQL Server.
Mevcut Tabloya Eklemek
Şöyle yaparız
ALTER TABLE dbo.Employee
ADD
    ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START
        HIDDEN NOT NULL
        DEFAULT SYSUTCDATETIME(),

    ValidTo DATETIME2 GENERATED ALWAYS AS ROW END
        HIDDEN NOT NULL
        DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),

    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
Daha sonra system versioning etkinleştirilir
ALTER TABLE dbo.Employee
SET
(
    SYSTEM_VERSIONING = ON
    (
        HISTORY_TABLE = dbo.EmployeeHistory
    )
);

Ne olur
What happens to existing records?
- Existing records remain in Employee.
- They receive ValidFrom and ValidTo values.
- SQL Server does not create historical versions of changes that happened before conversion.
- From the moment versioning is enabled, updates and deletes automatically generate history.









Tuesday, November 10, 2026

Transaction Isolation Level - Snapshot

PostgreSQL REPEATABLE READ = SQL Server SNAPSHOT (similar transaction-level snapshot behavior).

Read Committed Snapshot Isolation - RSCI

Giriş
Açıklaması şöyle. Varsayılan RSCI OFF yani reader ve writer lock kullanır
RCSI OFF: Readers use shared locks. Readers and writers can block each other.

RCSI ON: Readers use row versions instead of shared data locks. Readers normally don't block writers, and writers normally don't block readers.
Yani
PostgreSQL READ COMMITTED = SQL Server READ COMMITTED with RCSI ON.

Transaction Isolation Level - Repeatable Read

Repeatable Read aslında Read Lock gibi. Başkaları o satırı okuyabilir ama kimse yazamaz.

Transaction Isolation Level

SQL Server Concurrency Problems

Problem Explanation
Dirty ReadReading uncommitted changes from another transaction.
Non-Repeatable ReadReading the same row twice and getting different values.
Phantom ReadRepeating a query returns additional or missing rows due to concurrent inserts or deletes.
Lost UpdateOne transaction overwrites another transaction's update.
Write SkewTransactions read the same state and update different rows, jointly violating a business constraint.
Read SkewReading related data at different times, resulting in an inconsistent combination.
Dirty WriteOverwriting data modified by another uncommitted transaction.
DeadlockTransactions wait for each other in a circular dependency. SQL Server aborts one victim.
LivelockA transaction repeatedly loses opportunities to proceed due to competing transactions.
StarvationA transaction is continually denied resources or access.
Lock EscalationSQL Server replaces many fine-grained locks with a table-level or partition-level lock.
Hot SpotMany transactions compete for the same frequently accessed row or resource.

SQL Server Isolation Levels

Problem Read Uncommitted Read Committed Repeatable Read Snapshot Serializable
Dirty ReadPossibleNoNoNoNo
Non-Repeatable ReadPossiblePossibleNoNoNo
Phantom ReadPossiblePossiblePossibleNoNo
Lost UpdatePossiblePossible*Possible*No**No
Write SkewPossiblePossiblePossiblePossibleNo
Read SkewPossiblePossiblePossibleNoNo

Notes:

  • READ COMMITTED is the default SQL Server isolation level.
  • READ_COMMITTED_SNAPSHOT uses row versioning for Read Committed.
  • SNAPSHOT provides transaction-level consistent reads.
  • SNAPSHOT detects conflicting updates to the same row.
  • SERIALIZABLE uses range locks to prevent phantom inserts and serialization anomalies.
  • * Lost updates depend on the read-modify-write pattern and locking strategy.
  • ** SNAPSHOT aborts one transaction when both transactions attempt conflicting updates to the same row.

Thursday, August 20, 2026

VSS vs. VDI Backup

Giriş
İlk olarak burada gördüm

1.Volume Shadow Copy Service (VSS)
Sanırım Windows diskin kopyasını alıyor

2. Virtual Device Interface (VDI)
SQL Server SDK ile derlemek gerekir. SQL Server Engine veriyi kendisini VDI olarak tanıtan uygulamaya stream eder

Monday, August 17, 2026

Failover

Giriş
Açıklaması şöyle. Yani master ve replica arasındaki senkronizyon kopmuş ise replica otomatik olarak devralmaz. Elle FORCE_ALLOW_DATA_LOSS yapmak gerekir
PostgreSQL'de otomatik failover'ı açmak için replikasyonu senkron moda almak zorunda değilsiniz. Asenkron bir yapıda bile, primary çöktüğünde bir replica otomatik olarak terfi edebilir. Yani "biraz veri kaybı olabilir ama sistem kendi kendine ayağa kalksın" senaryosuna izin verir.

SQL Server tarafında ise durum farklı. Always On'da otomatik failover'ın devreye girebilmesi için replica'nın senkron modda olması ŞART. Asenkron bir replica otomatik failover hedefi olamaz. Siz veri kaybını göze alsanız bile sistem buna kendiliğinden izin vermez; ancak force allow data loss diyerek, bilinçli ve manuel bir müdahaleyle failover yapabilirsiniz.

Aradaki fark aslında bir tasarım felsefesi farkı. SQL Server "otomatik bir karar asla veri kaybına yol açmamalı, veri kaybı ancak insanın bilerek onayıyla olur" diyor. PostgreSQL ise "kayıp riskini kabul edip etmemek senin kararın, otomasyonu buna göre kur" diyor. İkisi de savunulabilir, ama aynı problemi farklı yerden çözüyorlar.

Friday, June 5, 2026

Columnstore Index

Giriş
Açıklaması şöyle
Columnstore mantığı temelinde basit: rowstore’da satır satır saklarız, columnstore’da kolon kolon. 1 milyarlık fact tablo üzerinde SUM(amount) hesaplayacaksak rowstore tüm satırı sayfaya getirir; columnstore sadece amount kolonunu okur, geri kalan kolonlar tek byte bile transfer olmaz.
Örnek şöyle
-- Ordered nonclustered columnstore (SQL Server 2025+)
CREATE NONCLUSTERED COLUMNSTORE INDEX nccsi_orders_ordered
    ON dbo.Orders (CustomerID, OrderDate, Amount)
    ORDER (OrderDate);

-- Sorgu artık OrderDate üzerinden segment elimination yapar
SELECT SUM(Amount)
FROM dbo.Orders
WHERE OrderDate >= '2025-01-01'
  AND OrderDate <  '2025-04-01';

Wednesday, May 6, 2026

Transaction Log (.ldf Dosyası) - WAL İçindir

Giriş
PostgreSQL'deki WAL dosyası ile aynıdır. PostgreSQL'den farklı olarak bu dosya sonsuza kadar büyür.

Thursday, March 26, 2026

XACT_ABORT

SELECT CASE 
    WHEN ( ( ( @@OPTIONS & 512 ) = 512 ) ) THEN 'ON' 
    ELSE 'OFF' 
END AS XACT_ABORT_STATUS;

-- When XACT_ABORT is ON → any runtime error rolls back the entire transaction automatically.
-- When OFF → some errors (like PK violations) do not abort the transaction, and subsequent statements still run.

SET XACT_ABORT ON;

CREATE TABLE MyTable (
    Id INT PRIMARY KEY,
    Name VARCHAR(100)
);


SELECT * FROM MyTable;

BEGIN TRANSACTION;
INSERT INTO MyTable (Id, Name) VALUES (1, 'Alice');
INSERT INTO MyTable (Id, Name) VALUES (1, 'Bob');
-- INSERT INTO MyTable (Id, Name)
-- SELECT 1, 'Bob'
-- WHERE NOT EXISTS (
--     SELECT 1
--     FROM MyTable
--     WHERE Id = 1
-- );
SELECT * FROM MyTable;
commit;

SELECT * FROM MyTable;

Output is

Output:

303 ms
XACT_ABORT_STATUS
-----------------
ON               
Id          Name                                                                                                
----------- ----------------------------------------------------------------------------------------------------
Msg 2627, Level 14, State 1, Server 6f1d64a248a3, Line 23
Violation of PRIMARY KEY constraint 'PK__MyTable__3214EC07149F63D5'. Cannot insert duplicate key in object 'dbo.MyTable'. The duplicate key value is (1).

Eğer OFF yaparsak
Output:

433 ms
XACT_ABORT_STATUS
-----------------
ON               
Id          Name                                                                                                
----------- ----------------------------------------------------------------------------------------------------
Msg 2627, Level 14, State 1, Server de2db788b1d3, Line 23
Violation of PRIMARY KEY constraint 'PK__MyTable__3214EC078BA094A9'. Cannot insert duplicate key in object 'dbo.MyTable'. The duplicate key value is (1).
The statement has been terminated.
Id          Name                                                                                                
----------- ----------------------------------------------------------------------------------------------------
          1 Alice                                                                                               
Id          Name                                                                                                
----------- ----------------------------------------------------------------------------------------------------
          1 Alice   


Wednesday, March 25, 2026

DuplicateKeyException

Giriş

Elimizde legacy bir veri tabanı var. Primary Key (PK) alanların datetime + ms şeklinde tasarlanmış. Böylece satırların kolayca sıralanabileceği düşünülmüş. Ancak bir problem var. Yazma istekleri arttıkça DuplicateKeyException hataları alıyoruz. Yani aslında veri tabanı saati PK için iyi bir kaynak değil. Çünkü aynı anda gelen iki istek için aynı zaman değerini verebiliyor


Ancak PK olarak şu seçenekleri değerlendirebiliriz

  • - Sequence kullanılsaydı harika olurdu
  • - Snowflake Id kullanılsaydı yine olurdu  ancak o zamanlar Snowflake yoktu
  • - UUIDv4 kullanamıyoruz, çünkü sırayı kaybediyoruz
  • - UUIDv7 kullanılabilir, sırayı muhafaza ederiz
  • - PK'ya bir alan daha ilave edebilsek, rastgele bir şey örneğin threadId problemi azaltır, tam çözmez


Wednesday, March 11, 2026

Table Partitioning

Giriş
Partition Funciton
Örnek
Başlangıçta şöyle yaparız
CREATE PARTITION FUNCTION pfAudit(datetime2)
AS RANGE RIGHT FOR VALUES
(
    '2025-01-01',
    '2026-01-01',
    '2027-01-01'
);
Split ile yeni range eklemek için sonra şöyle yaparız
ALTER PARTITION FUNCTION pfAudit()
SPLIT RANGE ('2028-01-01');
2025 artık arşive taşınınca şöyle yaparız. MERGE RANGE ile 2025 silinir.
ALTER PARTITION FUNCTION pfAudit()
MERGE RANGE ('2026-01-01');

1. Data Delete
The idea is:
Move old data out of the active table.
Then TRUNCATE the old partition/table instead of doing a huge DELETE.

This is much faster because TRUNCATE is minimally logged and doesn't scan rows.
Örnek
CREATE TABLE AuditLog (
    Id bigint IDENTITY,
    CreatedDate datetime2 NOT NULL,
    Message nvarchar(200)
);

Step 1: Create partition function
CREATE PARTITION FUNCTION pfAuditLog(datetime2)
AS RANGE RIGHT FOR VALUES
(
    '2024-01-01',
    '2025-01-01',
    '2026-01-01'
);

Step 2: Switch out old partition
ALTER TABLE AuditLog
SWITCH PARTITION 1
TO AuditLog_Archive;

Step 3: Truncate archive
TRUNCATE TABLE AuditLog_Archive;

2. Data Loading 
Data Loading yaparken kullanılabilecek yöntemler şöyle
1. bcp
2. BULK INSERT
3. SQL Server Integration Services (SSIS)

Açıklaması şöyle
Table partitioning is one of the most powerful strategies for improving load performance while maintaining data availability. At a financial services company processing billions of monthly transactions, implementing partition switching transformed their loading process. Instead of inserting directly into the main table and blocking queries, we loaded an identical staging table and instantly switched it into the partitioned main table: 
Örnek
Şöyle yaparız
-- Create staging table with same structure as target partition
SELECT * INTO Sales.Transactions_Staging
FROM Sales.Transactions
WHERE 1 = 0;

-- Load staging table (much faster than loading production table)
BULK INSERT Sales.Transactions_Staging
FROM '\\FileServer\Imports\NewTransactions.csv'
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n');

-- Switch staging table into partition in an instant operation
ALTER TABLE Sales.Transactions
SWITCH PARTITION 12 TO Sales.Transactions_Staging;

Thursday, June 19, 2025

msdb Veri Tabanı - System Database

Giriş
Açıklaması şöyle
In SQL Server environments, system databases play crucial roles in ensuring smooth and reliable database operations. Among these, the msdb database is critical as it handles a variety of operational tasks, including job scheduling via SQL Server Agent, alert management, database mail configuration, and backup and restore history tracking. These functions are essential for automating routine maintenance, monitoring system health, and managing administrative workflows.
Açıklaması şöyle
msdb is a system database that stores metadata and configuration for:
  • SQL Server Agent jobs

  • Backup and restore history

  • Database mail

  • Service Broker

  • Log shipping

  • Maintenance plans

  • Alerts and operators

  • SSIS package storage (when using MSDB storage)

Sunday, April 6, 2025

Sütun Tipleri - REAL

Giriş
Açıklaması şöyle
- Equivalent to a 32-bit floating-point number (single precision)
- IEEE standard floating-point value (7-digit precision)
- Storage size: 4 bytes
- Synonym: FLOAT(24)

Sunday, February 16, 2025

ORDER BY + OFFSET + FETCH - Sayfalama İçindir

Örnek
SQL Server 2012 ve sonrasında şöyle yaparız
SELECT * FROM Employees ORDER BY EmployeeID ASC
OFFSET 10 ROWS         -- Skip the first 10 rows
FETCH NEXT 5 ROWS ONLY; -- Fetch the next 5 rows
Örnek
SQL Server 2008 ve öncesinde şöyle yapılır
SELECT TOP 5 *
FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY EmployeeID ASC) AS RowNum
    FROM Employees
) AS SubQuery
WHERE RowNum > 10;




Monday, February 10, 2025

DROP DATABASE

Örnek
Force drop için şöyle yaparız
-- Set the database to SINGLE_USER mode with ROLLBACK IMMEDIATE to kill all connections
ALTER DATABASE my_new_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

-- Drop the database
DROP DATABASE my_new_db;



Max Server Memory

Açıklaması şöyle Kubernetes üzerinde PostgreSQL veya SQL Server koştururken pod'un belleğini ayarlamak standart bir stateless microservi...