1

I have a table which contains 2 columns { Names of cities and Info}

Name    Info
Qandahar    {"Population": 237500}
Kabul    {"Population": 1780000}
Herat    {"Population": 186800}
Mazar-e-Sharif    {"Population": 127800}
Amsterdam    {"Population": 731200}
Rotterdam    {"Population": 593321}

and so on. I tried to sort it by Population but this does not work

SELECT Name,Info ORDER BY CAST(SUBSTRING(Info, 16, LENGTH(Info)-16) AS INT) FROM city

but it outputs nothing. I get ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT) FROM city' at line 1.

adikinzor
  • 55
  • 1
  • 5

2 Answers2

0

You can't cast as INT

These are the following data type you can cast

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

You need to use this:

SELECT 
  Name, 
  Info,
  CAST(SUBSTRING(Info, 16, LENGTH(Info)-16) AS UNSIGNED) as info_cast 
FROM city 
order by info_cast

Answer is taken from: Cast from VARCHAR to INT - MySQL

Community
  • 1
  • 1
Mahedi Sabuj
  • 2,894
  • 3
  • 14
  • 27
0

You have deleted the symbols from the left, but you need to delete a } symbol from the right before casting. Like this:

CAST(TRIM(TRAILING '}' FROM SUBSTRING(Info,16,LENGTH(Info)-16)) AS INT)

By the way, why do you use such a table structure? Wouldn't it be better to have an integer column to keep integers?

CREATE TABLE Info ( NAME VARCHAR(20), POPULATION INT)