Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a sort key to an existing table in AWS Redshift

In AWS Redshift, I want to add a sort key to a table that is already created. Is there any command which can add a column and use it as sort key?

like image 324
jpdave Avatar asked Jul 26 '13 14:07

jpdave


People also ask

Can we change the sort key in Redshift?

Amazon Redshift now enables users to add and change sort keys of existing Redshift tables without having to re-create the table.

Can we have multiple sort keys in Redshift?

Redshift allows designating multiple columns as SORTKEY columns, but most of the best-practices documentation is written as if there were only a single SORTKEY.

How do you choose a sort key for a table?

If recent data is queried most frequently, specify the timestamp column as the leading column for the sort key. Queries are more efficient because they can skip entire blocks that fall outside the time range. If you do frequent range filtering or equality filtering on one column, specify that column as the sort key.

How many sort keys can Redshift have?

Amazon Redshift supports two different types of Sort Keys, Compound Sort Keys, and Interleaved Sort Keys. Selecting the right kind requires knowledge of the queries that you plan to execute.


1 Answers

As Yaniv Kessler mentioned, it's not possible to add or change distkey and sort key after creating a table, and you have to recreate a table and copy all data to the new table. You can use the following SQL format to recreate a table with a new design.

ALTER TABLE test_table RENAME TO old_test_table; CREATE TABLE new_test_table([new table columns]); INSERT INTO new_test_table (SELECT * FROM old_test_table); ALTER TABLE new_test_table RENAME TO test_table; DROP TABLE old_test_table; 

In my experience, this SQL is used for not only changing distkey and sortkey, but also setting the encoding(compression) type.

like image 69
Masashi M Avatar answered Oct 12 '22 12:10

Masashi M