How To Convert STRING To INT In SQL SERVER


  • If the table column is in VARCHAR and contains all numeric values, then it can be obtained as an integer using the CAST or the CONVERT function.
  • we can use CAST and CONVERT function like below:-

SELECT CAST(VarcharCol AS INT) FROM Table
SELECT CONVERT(INT, VarcharCol) FROM Table


To display this, we are going to create some data like following and try to sort it in ascending order the results are not output as I need them to because the database don’t know this and outputs them correctly as it is text data.


Convert STRING To INT In SQL SERVER

CREATE TABLE Demo

(demotxt VARCHAR(20))

INSERT Demo
SELECT '1';

INSERT Demo
SELECT '2';

INSERT Demo
SELECT '21';

INSERT Demo
SELECT '12';

INSERT Demo
SELECT '15';

SELECT *
FROM Demo
ORDER BY demotxt;

output:-

Here we didn’t get the actual output after ORDER BY.


  • That’s why we need to use some additional sql function to convert the string values to integers and I am using the CONVERT() function to get the desire output.
SELECT *

FROM demo

ORDER BY CONVERT(INT, demotxt);

Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *