Syntax error Get MySQL DISTINCT to work correctly if the records contain whitespace?

Get MySQL DISTINCT to work correctly if the records contain whitespace?



To get distinct including whitespace, you can use below syntax −

SELECT DISTINCT replace(yourColumnName,' ','') FROM yourTableName;

Let us first create a table:

mysql>create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20)
);
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql>insert into DemoTable(Name) values('John ');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values(' John ');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql>insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.15 sec)
mysql>insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.22 sec)
mysql>insert into DemoTable(Name) values(' Sam');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values('Mike ');
Query OK, 1 row affected (0.12 sec)
mysql>insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.17 sec)

Following is the query to display all records from the table using select statement:

mysql>select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | Name      |
+----+-----------+
| 1  | John      |
| 2  | John      |
| 3  | John      |
| 4  | Sam       |
| 5  | Carol     |
| 6  | Sam       |
| 7  | Mike      |
| 8  | David     |
+----+-----------+
8 rows in set (0.00 sec)

Here is the query to get distinct including whitespace:

mysql>SELECT DISTINCT replace(Name,' ','') FROM DemoTable;

This will produce the following output −

+----------------------+
| replace(Name,' ','') |
+----------------------+
| John                 |
| Sam                  |
| Carol                |
| Mike                 |
| David                |
+----------------------+
5 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:25+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements