PostgreSQL Create Table: Create a table countries, including columns which already exist
2. Write a SQL statement to create a simple table countries, including columns country_id,country_name and region_id which already exist.
Sample Solution:
Code:
-- This SQL statement creates a new table called 'countries' with specified columns.
CREATE TABLE countries (
COUNTRY_ID varchar(3), -- Defines a column 'COUNTRY_ID' to store country IDs as strings with a maximum length of 3 characters.
COUNTRY_NAME varchar(45), -- Defines a column 'COUNTRY_NAME' to store country names as strings with a maximum length of 45 characters.
REGION_ID decimal(10,0) -- Defines a column 'REGION_ID' to store region IDs as decimal numbers with a precision of 10 digits and no decimal places.
);
Explanation:
- The CREATE TABLE statement is used to create a new table in the database.
- The table is named 'countries'.
- Inside the parentheses, each line specifies a column in the table along with its data type and optional constraints.
- varchar(3) indicates a variable-length character string with a maximum length of 3 characters for the 'COUNTRY_ID' column.
- varchar(45) indicates a variable-length character string with a maximum length of 45 characters for the 'COUNTRY_NAME' column.
- decimal(10,0) indicates a decimal number with a precision of 10 digits and no decimal places for the 'REGION_ID' column.
- Each column definition is separated by a comma.
Output:
Here is the output for the above SQL statement. The following output shows an error message, because the table already exists.
postgres=# CREATE TABLE countries ( postgres(# COUNTRY_ID varchar(3), postgres(# COUNTRY_NAME varchar(45), postgres(# REGION_ID decimal(10,0) postgres(# ); ERROR: relation "countries" already exists
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a SQL statement to create a simple table countries, including columns country_id,country_name and region_id which already exist.
Next: Write a sql statement to create the structure of a table dup_countries similar to countries.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics