Dynamic Pivot Table syntax error What's wrong with this Dynamic Pivot table query? I'm staring myself blind on this.

mysql&gt; SET @sql = NULL;
Query OK, 0 rows affected (0.00 sec)

mysql&gt; SELECT
    -&gt;   GROUP_CONCAT(DISTINCT
    -&gt;     CONCAT(
    -&gt;       'IF(q.label = ''',
    -&gt;       label,
    -&gt;       ''', 1, 2) AS ',
    -&gt;       label
    -&gt;    )
    -&gt;   ) INTO @sql
    -&gt; FROM question;
Query OK, 1 row affected (0.00 sec)

mysql&gt; SET @sql = CONCAT('SELECT a.id, ', @sql, ', q.id
    '&gt;       FROM answer a
    '&gt;       INNER JOIN question q ON questionId = q.id
    '&gt;       GROUP BY a.id');
Query OK, 0 rows affected (0.01 sec)

mysql&gt; PREPARE stmt FROM @sql;
ERROR 1064 (42000): You have an error in your SQL syntax ... near ' q.id


Why does the first one pass but the second one blows up?

Adding PREPARE stmt FROM @sql; on the GROUP_CONCAT query gives me this:

You have an error ... near 'IF(q.label = 'Q1', 1, 2) AS Q1,IF(q.label = 'Q2', 1, 2) AS Q2,IF(q.label = '', 1' at line 1


I'm not expecting the label to be empty on the last if, but I don't see how that would blow up the last query.

The query without the dynamic part returns this:

+----+-------+----+
| id | label | id |
+----+-------+----+
|  1 | Q1    |  1 |
|  2 | Q2    |  1 |
|  3 | Q1    |  1 |
|  4 | Q2    |  1 |
+----+-------+----+
This is the correct form of the if clause

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
     CONCAT(
       'IF(q.label = "',
       label,
       '", 1, 2) AS ',
       label
    )
   ) INTO @sql
    FROM question;
SET @sql = CONCAT('SELECT a.id, ', @sql, ', q.id
       FROM answer a
       INNER JOIN question q ON questionId = q.id
       GROUP BY a.id');
PREPARE stmt FROM @sql;


But still you should always write the result of
    SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
     CONCAT(
       'IF(q.label = "',
       label,
       '", 1, 2) AS ',
       label
    )
   ) INTO @sql
    FROM question;
 SELECT @sql;