PostgreSQL Create Table: Create a table countries set a constraint NULL
5. Write a SQL statement to create a table countries, set a constraint NULL.
Sample Solution:
Code:
-- This SQL statement creates a new table named 'countries' if it does not already exist,
-- defining the structure and constraints for the table columns.
CREATE TABLE IF NOT EXISTS countries (
COUNTRY_ID varchar(2) NOT NULL, -- Defines a column 'COUNTRY_ID' to store country IDs as strings with a maximum length of 2 characters. The column cannot contain NULL values.
COUNTRY_NAME varchar(40) NOT NULL, -- Defines a column 'COUNTRY_NAME' to store country names as strings with a maximum length of 40 characters. The column cannot contain NULL values.
REGION_ID decimal(10,0) NOT NULL -- Defines a column 'REGION_ID' to store region IDs as decimal numbers with a precision of 10 digits and no decimal places. The column cannot contain NULL values.
);
Explanation:
- The CREATE TABLE IF NOT EXISTS statement creates a new table only if it does not already exist in the database.
- The table is named 'countries'.
- Each column definition specifies the column name, data type, and optional constraints.
- varchar(2) indicates a variable-length character string with a maximum length of 2 characters for the 'COUNTRY_ID' column.
- varchar(40) indicates a variable-length character string with a maximum length of 40 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.
- The NOT NULL constraint ensures that each column must contain a value and cannot be left empty.
Output:
postgres=# CREATE TABLE IF NOT EXISTS countries ( postgres(# COUNTRY_ID varchar(2) NOT NULL, postgres(# COUNTRY_NAME varchar(40) NOT NULL, postgres(# REGION_ID decimal(10,0) NOT NULL postgres(# ); CREATE TABLE
Here is the command to see the structure of the table, just created :
postgres=# \d countries;
Table "public.countries"
Column | Type | Modifiers
--------------+-----------------------+-----------
country_id | character varying(2) | not null
country_name | character varying(40) | not null
region_id | numeric(10,0) | not null
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a SQL statement to create a duplicate copy of countries table, including structure and data by name dup_countries.
Next: Write a SQL statement to create a table named jobs, including job_id, job_title, min_salary, max_salary and check whether the max_salary amount exceeding the upper limit 25000.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics