58

I have a table in my database and I want run a query like

SELECT column1, column2 FROM my_table WHERE my_condition;

but I want the mysql to return the column2 in utf8 encoding. Is it any function in mysql to do such task? What is that?

orezvani
  • 3,595
  • 8
  • 43
  • 57

4 Answers4

81

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;
josh-fuggle
  • 3,097
  • 2
  • 26
  • 27
  • 2
    how to do this for `select *` as this is an syntax error `select convert(* using utf8)` – Gaurav Aggarwal Oct 22 '18 at 12:51
  • 2
    Hey mate, I believe you can't use the wildcard character and have to convert columns individually: `SELECT CONVERT(mycol1 USING utf8), CONVERT(mycol2 USING utf8)` – josh-fuggle Oct 22 '18 at 22:31
48
SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
28

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

ManuelAtWork
  • 2,198
  • 29
  • 34
13

I have used next code for LATIN1 (or your db's charset) to UTF8 problems :

SELECT column1,
       CONVERT(CAST(CONVERT(column2 USING LATIN1) AS BINARY) USING UTF8) AS column2
  FROM my_table
 WHERE my_condition

It converts from LATIN1 to BINARY, then to UTF8, because straight from LATIN1 to UTF8 might not work.