CREATE TABLE
So far in the series, we have been using a sample database pre-built to run queries. Now we are going to learn some useful ways to create our own table and how to fill them with data. We begin with the CREATE TABLE statement.
The
CREATE TABLE SYNTAX
In order to create a table with the
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100) NOT NULL,
category VARCHAR(50),
price DECIMAL(8,2) NOT NULL,
cost DECIMAL(8,2),
stock_quantity INT DEFAULT 0,
supplier_id INT,
launch_date DATE,
weight_kg DECIMAL(5,2),
is_discontinued BOOLEAN DEFAULT FALSE,
rating DECIMAL(2,1)
);
Implementing this query on a Postgres database or even SQLite DB would return a message like below:
CREATE TABLE
This of course means that your table has been created successfully. There is no data in the table yet. We can
confirm this by running the
SELECT *
FROM products
product_id | product_name | category | price | cost | stock_quantity | supplier_id | launch_date | weight_kg | is_discontinued | rating ------------+--------------+----------+-------+------+----------------+-------------+-------------+-----------+-----------------+-------- (0 rows)
CREATE TABLE FROM QUERY
Another powerful alternative is to create tables using queries that return data from existing tables. This approach is much more straightforward as it relieves you from having to manually define the correct data types—the new table automatically inherits the data types from the source table.
The example below demonstrates how to create a table from another table use the empty table we just created.
Notice the slight syntax change
in using the keyword
CREATE TABLE products_dup AS
SELECT *
FROM products;
We can then quickly check if this table has been created by selecting all the information and passing the table name
SELECT * FROM products_dup;
select * from products_dup; product_id | product_name | category | price | cost | stock_quantity | supplier_id | launch_date | weight_kg | is_discontinued | rating ------------+--------------+----------+-------+------+----------------+-------------+-------------+-----------+-----------------+--------
We definitely see that the table has been created and mirrors the table
This concludes our comprehensive discussion on the