Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
GROUP BY and display only non-empty column values in MySQL
Let us first create a table −
mysql> create table DemoTable -> ( -> Id varchar(100), -> Message varchar(200) -> ); Query OK, 0 rows affected (1.17 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('1','');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('1','Hi');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('2','Hello');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('3','Awesome');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('3','Good Morning');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('2',NULL);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+------+--------------+ | Id | Message | +------+--------------+ | 1 | | | 1 | Hi | | 2 | Hello | | 3 | Awesome | | 3 | Good Morning | | 2 | NULL | +------+--------------+ 6 rows in set (0.00 sec)
Following is the query to group by and select first non-empty columns −
mysql> select Id,min(Message) from DemoTable -> where Message IS NOT NULL and length(Message) > 0 -> group by Id;
Output
+------+--------------+ | Id | min(Message) | +------+--------------+ | 1 | Hi | | 2 | Hello | | 3 | Awesome | +------+--------------+ 3 rows in set (0.06 sec)
Advertisements