Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a column type from integer to string

Using PostgreSQL, what's the command to migrate an integer column type to a string column type?

Obviously I'd like to preserve the data, by converting the old integer data to strings.

like image 403
eye_mew Avatar asked May 20 '15 22:05

eye_mew


People also ask

How do you change the datatype of a column with data?

Change data types in Datasheet view Select the field (the column) that you want to change. On the Fields tab, in the Properties group, click the arrow in the drop-down list next to Data Type, and then select a data type. Save your changes.

How do I change data from numeric to character in SQL?

The following SQL statement converts integer data to characters using CAST(): SELECT item_name, CAST(item_quantity AS CHAR(8)) FROM items; As with CONVERT(), CAST() can use any data type which receives characters: VARCHAR, NCHAR and NVARCHAR.


1 Answers

You can convert from INTEGER to CHARACTER VARYING out-of-the-box, all you need is ALTER TABLE query chaning column type:

SQL Fiddle

PostgreSQL 9.3 Schema Setup:

CREATE TABLE tbl (col INT);
INSERT INTO tbl VALUES (1), (10), (100);
ALTER TABLE tbl ALTER COLUMN col TYPE CHARACTER VARYING(10);

Query 1:

SELECT col, pg_typeof(col) FROM tbl

Results:

| col |         pg_typeof |
|-----|-------------------|
|   1 | character varying |
|  10 | character varying |
| 100 | character varying |
like image 152
Crozin Avatar answered Oct 12 '22 15:10

Crozin