Home >Database >Mysql Tutorial >Is There a LISTAGG Equivalent in Older Oracle Versions to MySQL's GROUP_CONCAT?

Is There a LISTAGG Equivalent in Older Oracle Versions to MySQL's GROUP_CONCAT?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-15 12:19:45122browse

Is There a LISTAGG Equivalent in Older Oracle Versions to MySQL's GROUP_CONCAT?

Is there an equivalent of GROUP_CONCAT for MySQL in Oracle?

Question:

How to concatenate multiple values ​​in a specified column into a single comma separated string in Oracle? The input data follows a specific format and the desired output should group and concatenate values ​​for each unique key.

Answer:

For Oracle 11g and above:

Use the LISTAGG function:

<code class="language-sql">SELECT 
    col1,
    LISTAGG(col2, ', ') WITHIN GROUP (ORDER BY col2) "names"
FROM table_x
GROUP BY col1</code>

For Oracle 10g and lower:

One way is to create a custom function:

<code class="language-sql">CREATE OR REPLACE FUNCTION get_comma_separated_value (input_val  IN  NUMBER)
  RETURN VARCHAR2
IS
  return_text  VARCHAR2(10000) := NULL;
BEGIN
  FOR x IN (SELECT col2 FROM table_name WHERE col1 = input_val) LOOP
    return_text := return_text || ',' || x.col2 ;
  END LOOP;
  RETURN LTRIM(return_text, ',');
END;
/</code>

How to use:

<code class="language-sql">SELECT col1, get_comma_separated_value(col1) FROM table_name</code>

Note: Oracle versions prior to 11g have limited support for the WM_CONCAT function, but its use is deprecated due to potential issues (see Oracle documentation for details).

In MySQL (for reference only):

GROUP_CONCAT function available:

<code class="language-sql">SELECT col1, GROUP_CONCAT(col2) FROM table_name GROUP BY col1</code>

The above is the detailed content of Is There a LISTAGG Equivalent in Older Oracle Versions to MySQL's GROUP_CONCAT?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn