Is there a way to specify data types and keep constraints when doing a Redshift CREATE TABLE AS
query?
In the below example, I'd like to be able to create a copy of table1 with the column column2
as NVARCHAR(500)
type rather than VARCHAR(255)
and keep the column1
NOT NULL
constraint.
CREATE TABLE test.table1 (column1 INT NOT NULL, column2 VARCHAR(255));
INSERT INTO test.table1
SELECT 1,'foo';
CREATE TABLE test.table2 AS
SELECT column1,CAST(column2 AS NVARCHAR(500))
FROM test.table1;
/* query executes successfully but still creates column2 as VARCHAR(255) and column1 is NULLABLE. */
CREATE TABLE test.table2 (
column1 INT NOT NULL
,column2 NVARCHAR(500)
) AS
SELECT column1
,column2
FROM test.table1;
/* ERROR: 42601: syntax error at or near "as" */
Edit: I'm aware that I could do this in two steps by explicitly creating test.table2
with the correct data types and constraints, then doing an INSERT statement using the data in test.table1
. I am curious though to see if this can be done in one CREATE TABLE AS query. Any workarounds or tips would be greatly appreciated! :)
From an SQL perspective, the answer is Yes and No. Yes, you can specify the datatype: use CAST
to convert the column to the type you want. No, you can't specify constraints, because you can't: there's no syntax to do that.
If you're concerned about the constraints of a table, make it part of the schema. If the data are determining the schema dynamically, something is amiss.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.