CREATE TABLE
So far in the SQL programming series, we have been using a sample
database that came pre-installed with DBeaver software. Now we are going
to learn some essential techniques to create our own tables and populate
them with data. We begin with the fundamental
The
CREATE TABLE SYNTAX
To create a table with the
CREATE TABLE test_stock
(
Ticker VARCHAR(10) NOT NULL,
Open DOUBLE NOT NULL,
High DOUBLE NOT NULL,
Low DOUBLE NOT NULL,
Close DOUBLE NOT NULL,
Volume INT
);
In the example above, we have created a table named
We can query our new table to verify that these columns have been created and confirm that no data has been inserted into the table yet.
CREATE TABLE test_stock
(
Ticker VARCHAR(10) NOT NULL,
Open DOUBLE NOT NULL,
High DOUBLE NOT NULL,
Low DOUBLE NOT NULL,
Close DOUBLE NOT NULL,
Volume INT
);
SELECT *
FROM test_stock
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 syntax to create a table from a query looks like this:
CREATE TABLE test_stock_data AS
SELECT *
FROM stock_data
As we can see from the execution, the table has been successfully created. The new table now contains all the rows returned by the query. We can verify that it contains all the expected data by querying the new table using the following statement:
select *
from test_stock_data
As demonstrated in the output, all the records that were retrieved in the original query used to create the table are now permanently stored in our new table. This method is particularly useful for creating backup tables, filtered datasets, or transformed versions of existing data.
This concludes our comprehensive discussion on the