Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - CREATE TABLE FROM SELECT

Tags:

sql

postgresql

I have two tables, one contains a large list of IDs and Info regarding those ids.

I have a second table Graph which just has two columns, each column contains the aforementioned id numbers, multiple times. I want to trim the size of my Info table by selecting only those ids that appear in my graph and creating a new smaller Info table. Is there a simple way of doing this?

CREATE TABLE FROM SELECT?  

Thanks!

like image 433
user2923767 Avatar asked Apr 09 '14 05:04

user2923767


People also ask

How do I create the same table structure in PostgreSQL?

To copy a table with partial data from an existing table, users can use the following statement: Syntax: CREATE TABLE new_table AS SELECT * FROM existing_table WHERE condition; The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.

How do you create a table in Greenplum?

To be able to create a table, you must have USAGE privilege on all column types or the type in the OF clause, respectively. If you specify a schema name, Greenplum creates the table in the specified schema. Otherwise Greenplum creates the table in the current schema.

How do I create a table from one table to another in SQL?

Answer: To do this, the SQL CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2); For example: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1=2);


1 Answers

It's as easy as:

create table new_table as  select t1.col1, t2.col2 from some_table t1    join t2 on t1.id = t2.some_id; 

You can use any select statement for that. The column names of the new table are defined by the column aliases used in th query.

More details in the manual: http://www.postgresql.org/docs/current/static/sql-createtableas.html

like image 147
a_horse_with_no_name Avatar answered Oct 03 '22 12:10

a_horse_with_no_name