Skip to main content

Create Table As Select

Create a Magpie table from the result of a query, or replace an existing one. Run it in a SQL paragraph, or in a Magpie paragraph as sql(CREATE TABLE …), where it runs immediately and leaves result unchanged.

The table is saved the same way as Save Result saves one: as data files on the repository's default data source. To create a table that stores the query instead of its result, use Create View. See Creating Tables and Views with SQL for when to use this statement or Save Result.

Syntax​

CREATE TABLE [IF NOT EXISTS] <table> AS <query>

CREATE OR REPLACE TABLE <table> [WITHOUT GRANTS] AS <query>

Parameters​

table​

String — The table to create, as table or schema.table, in the current repository. Defaults to the current schema.

query​

Query — The query whose result becomes the table. It can read result and tables in other repositories.

Options​

if not exists​

If the table already exists, do nothing, without running the query. Magpie prints Table "<table>" already exists. Skipped table creation. Without this option, creating a table that exists is an error.

or replace​

If the table already exists, replace it, as save result … with replace does. The existing table must not be a view. Can't be combined with IF NOT EXISTS.

without grants​

Don't copy the replaced table's grants to the new table. By default, they're copied. Only with OR REPLACE.

Examples​

CREATE TABLE analytics.orders_2026 AS
SELECT * FROM sales.orders WHERE year(order_date) = 2026
CREATE OR REPLACE TABLE analytics.daily_sales AS
SELECT order_date, count(*) AS orders, sum(amount) AS revenue
FROM sales.orders
GROUP BY order_date

Errors​

MessageCause
CREATE TABLE cannot combine OR REPLACE with IF NOT EXISTSBoth options were given.
WITHOUT GRANTS can only be used with CREATE OR REPLACE TABLEWITHOUT GRANTS was given without OR REPLACE.
CREATE OR REPLACE TABLE cannot replace "<table>": it is a view. Use CREATE OR REPLACE VIEW <table> AS ..., or drop the view first with DROP VIEW <table>.The existing table is a view.
Error processing SQL statement: … Table or stream with name "<table>" already exists in schema.The table already exists, and neither IF NOT EXISTS nor OR REPLACE was given.
CREATE TABLE AS SELECT does not support a repository-qualified target …The table names a repository. Run use repository and name the table without it.
CREATE TABLE with a column list is not supported. Use CREATE TABLE ... AS SELECT ..., or the Magpie 'create table' command with a JSON specification.The statement defines columns instead of a query. Use a query, or Create Table.

Spark clauses such as USING, PARTITIONED BY, and TBLPROPERTIES aren't supported and fail with a parse error.

Security​

Requires Create permission on the schema, and Read permission on every table the query reads. OR REPLACE also requires Write permission on the existing table.