COALESCE ফাংশন ব্যবহার
COALESCE(val1, val2, ...) প্রথম নন-NULL ভ্যালু রিটার্ন করে। দুটি কলামে যেকোনোটি NULL হলে অন্যটি দেখানোর জন্য ব্যবহার করুন।
সিনট্যাক্স
SELECT COALESCE(column1, column2) AS combined FROM yourTable;
উদাহরণ
টেবিল তৈরি
mysql> create table combineTwoColumnsDemo (
-> UserId int,
-> UserName varchar(20),
-> UserAge int
-> );
Query OK, 0 rows affected (1.12 sec)
ডেটা ইনসার্ট (NULL সহ)
mysql> insert into combineTwoColumnsDemo values(101,'John',23); Query OK, 1 row affected (0.16 sec) mysql> insert into combineTwoColumnsDemo values(102,'Carol',20); Query OK, 1 row affected (0.14 sec) mysql> insert into combineTwoColumnsDemo values(103,'Bob',25); Query OK, 1 row affected (0.13 sec) mysql> insert into combineTwoColumnsDemo values(104,'Mike',26); Query OK, 1 row affected (0.18 sec) mysql> insert into combineTwoColumnsDemo values(105,NULL,23); Query OK, 1 row affected (0.22 sec) mysql> insert into combineTwoColumnsDemo values(105,'Maxwell',NULL); Query OK, 1 row affected (0.15 sec)
সকল রেকর্ড
mysql> SELECT * FROM combineTwoColumnsDemo;
আউটপুট
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 101 | John | 23 | | 102 | Carol | 20 | | 103 | Bob | 25 | | 104 | Mike | 26 | | 105 | NULL | 23 | | 105 | Maxwell | NULL | +--------+----------+---------+
COALESCE দিয়ে কম্বাইন
mysql> SELECT UserName, UserAge, COALESCE(UserName, UserAge) AS Combine_UserName_UserAge FROM combineTwoColumnsDemo;
আউটপুট
+----------+---------+--------------------------+ | UserName | UserAge | Combine_UserName_UserAge | +----------+---------+--------------------------+ | John | 23 | John | | Carol | 20 | Carol | | Bob | 25 | Bob | | Mike | 26 | Mike | | NULL | 23 | 23 | | Maxwell | NULL | Maxwell | +----------+---------+--------------------------+
ব্যাখ্যা: ৫ম রোতে UserName NULL, তাই UserAge (২৩) দেখাচ্ছে। ৬ম রোতে UserAge NULL, তাই UserName (Maxwell) দেখাচ্ছে।