Video tayyorlanmoqda

Nega `WHERE deleted_at = NULL` hech qanday satr qaytarmaydi?

SELECT count(*) FROM users WHERE deleted_at = NULL;   -- 0
SELECT count(*) FROM users WHERE deleted_at IS NULL;  -- 1240

NULL — "noma'lum qiymat", u bilan har qanday = yoki <> solishtirish natijasi true emas, NULL bo'ladi. NULL'ni tekshirish uchun IS NULL yoki IS NOT NULL yoziladi.

📖 Javob

SQL'da mantiq uch qiymatli: true, false va NULL (unknown). WHERE faqat true chiqqan satrlarni o'tkazadi. deleted_at = NULL esa har doim NULL beradi — demak, hech bir satr o'tmaydi. Xato ham chiqmaydi, shunchaki bo'sh natija, shuning uchun bu bug uzoq vaqt sezilmay qolishi mumkin.

Shu qoida boshqa joylarda ham chiqadi:

SELECT NULL = NULL;          -- NULL, true emas
SELECT 5 + NULL;             -- NULL
SELECT 'a' || NULL;          -- NULL
SELECT coalesce(NULL, 0);    -- 0 — default qiymat berish

Ikki ustunni "NULL'lar ham teng" deb solishtirish kerak bo'lsa, PostgreSQL'da IS NOT DISTINCT FROM bor:

WHERE a.middle_name IS NOT DISTINCT FROM b.middle_name

Java tomonida ham shunga o'xshash: Spring Data'da findByDeletedAt(null) metodi IS NULL so'rovini yasaydi, lekin qo'lda yozilgan JPQL'da = :param ga null bersangiz — bo'sh natija.