snippetsqlModerate
How to get all distinct words in a column
Viewed 0 times
distinctallcolumnwordsgethow
Problem
I have a table with a text column that can contain a single word, more words separated by a space or a
For getting all the distinct column entries I use
but I don't know how to get all the distinct words.
NULL value. I need to get all the distinct words in that column (words non column entries).For getting all the distinct column entries I use
SELECT DISTINCT(col_name) AS col_name FROM table_name ORDER BY col_name ASCbut I don't know how to get all the distinct words.
Solution
SELECT DISTINCT
SUBSTRING_INDEX(SUBSTRING_INDEX(table_name.col_name, ' ', numbers.n), ' ', -1) col_name
FROM
(SELECT 1 n UNION ALL SELECT 2
UNION ALL SELECT 3 UNION ALL SELECT 4) numbers INNER JOIN table_name
ON CHAR_LENGTH(table_name.col_name)
-CHAR_LENGTH(REPLACE(table_name.col_name, ' ', ''))>=numbers.n-1
ORDER BY
col_name;You can see it here: http://sqlfiddle.com/#!2/b5be5/2/0
reference: https://stackoverflow.com/questions/17942508/sql-split-values-to-multiple-rows
Code Snippets
SELECT DISTINCT
SUBSTRING_INDEX(SUBSTRING_INDEX(table_name.col_name, ' ', numbers.n), ' ', -1) col_name
FROM
(SELECT 1 n UNION ALL SELECT 2
UNION ALL SELECT 3 UNION ALL SELECT 4) numbers INNER JOIN table_name
ON CHAR_LENGTH(table_name.col_name)
-CHAR_LENGTH(REPLACE(table_name.col_name, ' ', ''))>=numbers.n-1
ORDER BY
col_name;Context
StackExchange Database Administrators Q#81930, answer score: 10
Revisions (0)
No revisions yet.