119

I have the following table structure

+  id  +  word  +
+------+--------+

The table gets filled with the words in lower cas of a given text, so the text

Hello bye hello

would result in

+  id  +  word  +
+------+--------+
+   1  + hello  +
+------+--------+
+   2  + bye    +
+------+--------+
+   3  + hello  +
+------+--------+

I want to make a SELECT query that will return the number of words that get repeated at least two times in the table (like hello)

SELECT COUNT(id) FROM words WHERE (SELECT COUNT(words.word))>1

which of course is so wrong and super overloading when table is big. Any idea on how to achieve such purpose? In the given example inhere-above, I would expect 1

1
  • 1
    Anyone else seeing the underscores like a "sagging" rope bridge?
    – droplet
    Mar 29, 2020 at 14:14

4 Answers 4

300

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1
2
  • 2
    Just an addon, you can use the alias as well in "having". Like SELECT words, COUNT(*) AS cnt FROM words GROUP BY word HAVING cnt > 1 Jan 31, 2016 at 6:47
  • The first example works well only grouping Data Sep 7 at 11:03
23
SELECT count(word) as count 
FROM words 
GROUP BY word
HAVING count >= 2;
1
  • CodeIgniter also supports having, so this was perfect. Thanks Feb 1, 2015 at 21:14
8

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

2

The HAVING option can be used for this purpose and query should be

SELECT word, COUNT(*) FROM words 
GROUP BY word
HAVING COUNT(*) > 1;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.