w3resource

PostgreSQL Create Table: Create a table countries, with columns country_id, country_name and region_id


1. Write a SQL statement to create a simple table countries, including columns country_id, country_name and region_id.

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:

postgres=# CREATE TABLE countries (
postgres(# COUNTRY_ID varchar(3),
postgres(# COUNTRY_NAME varchar(45),
postgres(# REGION_ID decimal(10,0)
postgres(# );
CREATE TABLE

To see the structure of the created table :

postgres=# postgres=# \d countries;
           Table "public.countries"
    Column    |         Type          | Modifiers
--------------+-----------------------+-----------
 country_id   | character varying(3)  |
 country_name | character varying(45) |
 region_id    | numeric(10,0)         |

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Next: Write a SQL statement to create a simple table countries, including columns country_id,country_name and region_id which already exist.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/postgresql-exercises/create-table/create-table-exercise-1.php