๐Ÿ’ป [SQL] 5. NULL๊ฐ’ ์กฐํšŒ ๋ฐ NULL ๊ด€๋ จ ํ•จ์ˆ˜

thisk336ยท2023๋…„ 10์›” 4์ผ
0

SQL

๋ชฉ๋ก ๋ณด๊ธฐ
5/17
post-thumbnail

NULL ๊ฐ’์ด๋ž€?

NULL ๊ฐ’์˜ ํŠน์ง•

  • NULL์€ ๋ชจ๋ฅด๋Š” ๊ฐ’์„ ์˜๋ฏธํ•œ๋‹ค.
  • NULL์€ ๊ฐ’์˜ ๋ถ€์žฌ๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
  • NULL๊ณผ ์ˆซ์ž ํ˜น์€ ๋‚ ์งœ๋ฅผ ๋”ํ•˜๋ฉด NULL์ด ๋œ๋‹ค.
  • NULL๊ณผ ์–ด๋–ค ๊ฐ’์„ ๋น„๊ตํ•  ๋•Œ, '์•Œ ์ˆ˜ ์—†์Œ'์ด ๋ฐ˜ํ™˜๋œ๋‹ค.

NULL๊ฐ’ ์กฐํšŒ

  • NULL๊ฐ’์„ ์กฐํšŒํ•  ๊ฒฝ์šฐ์—๋Š” IS NULL์„ ์‚ฌ์šฉํ•˜๊ณ , NULL ๊ฐ’์ด ์•„๋‹Œ ๊ฒƒ์„ ์กฐํšŒํ•  ๊ฒฝ์šฐ์—๋Š” IS NOT NULL์„ ์‚ฌ์šฉํ•œ๋‹ค.
  • ๊ธฐ๋ณธ ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
SELECT [์ปฌ๋Ÿผ๋ช…] 
FROM [ํ…Œ์ด๋ธ”๋ช…]
WHERE [์ปฌ๋Ÿผ๋ช…] IS (NOT) NULL;

์œ„์™€ ๊ฐ™์€ ํ…Œ์ด๋ธ”์ด ์žˆ์„ ๋•Œ, lowest_price ์ปฌ๋Ÿผ ์ค‘ NULL๊ฐ’์ธ ์ปฌ๋Ÿผ์„ ์กฐํšŒํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค.

SELECT * FROM mytable
WHERE lowest_price IS NULL;

๋ฐ˜๋Œ€๋กœ lowest_price ์ปฌ๋Ÿผ ์ค‘ NULL๊ฐ’์ด ์•„๋‹Œ ์ปฌ๋Ÿผ์„ ์กฐํšŒํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค.

SELECT * FROM mytable
WHERE lowest_price IS NOT NULL;

NULL ๊ด€๋ จ ํ•จ์ˆ˜

ORACLE์—์„œ๋Š” NULL ๊ด€๋ จ ํ•จ์ˆ˜๋กœ NVL, NVL2 ๋“ฑ์ด ์žˆ์ง€๋งŒ MySQL์—์„œ๋Š” ๋น„์Šทํ•œ ๊ธฐ๋Šฅ์œผ๋กœ IFNULL , COALESCE๊ณผ ๊ฐ™์€ ํ•จ์ˆ˜๋“ค์ด ์žˆ๋‹ค.

IFNULL ํ•จ์ˆ˜

  • IFNULL ํ•จ์ˆ˜๋Š” ํ•ด๋‹น ์ปฌ๋Ÿผ์˜ ๊ฐ’์ด NULL์„ ๋ฐ˜ํ™˜ํ•  ๋•Œ, ๋‹ค๋ฅธ ๊ฐ’์œผ๋กœ ์ถœ๋ ฅํ•˜๋„๋ก ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

  • ๊ธฐ๋ณธ ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

SELECT IFNULL([์ปฌ๋Ÿผ๋ช…], "๋Œ€์ฒด ๊ฐ’") 
FROM [ํ…Œ์ด๋ธ”๋ช…]; 
SELECT IFNULL(lowest_price, "๊ฐ€๊ฒฉ ์ •๋ณด ์—†์Œ") AS "๊ฐ€๊ฒฉ"
FROM mytable;


์œ„ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ๋งˆ์ง€๋ง‰ row์—์„œ NULL๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๊ณ  "๊ฐ€๊ฒฉ ์ •๋ณด ์—†์Œ"์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

COALESCE ํ•จ์ˆ˜

  • COALESCE() ํ•จ์ˆ˜๋Š” ์ฃผ์–ด์ง„ ์ธ์ˆ˜์—์„œ NULL ์ด ์•„๋‹Œ ์ฒซ๋ฒˆ์งธ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋‹ค.

  • ๊ธฐ๋ณธ ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

SELECT COALESCE([๊ฐ’ 1], [๊ฐ’ 2], [๊ฐ’ 3], ...);
SELECT COALESCE(NULL, NULL, NULL, 1);


์ธ์ž์—๋Š” ๊ฐ’ ๋ง๊ณ ๋„ ์ปฌ๋Ÿผ๋ช…์„ ์ ์„ ์ˆ˜ ์žˆ๋‹ค.

SELECT COALESCE(lowest_price, "๊ฐ€๊ฒฉ ์ •๋ณด ์—†์Œ")
FROM mytable;

0๊ฐœ์˜ ๋Œ“๊ธ€