PostgreSQL Create Table: Create a table to restrict one of the columns to contain any duplicate values
10. Write a SQL statement to create a table named countries, including columns country_id, country_name and region_id and make sure that the country_id column will be a key field which will not contain any duplicate data at the time of insertion.
Sample Solution:
Code:
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 'COUNTRY_ID', 'COUNTRY_NAME', and 'REGION_ID' columns cannot contain NULL values.
- The UNIQUE constraint ensures that each value in the 'COUNTRY_ID' column must be unique across all rows in the table.
- The PRIMARY KEY constraint sets the 'COUNTRY_ID' column as the primary key for the table, ensuring uniqueness and providing a unique identifier for each row in the table.
The above statement can be written like below.
Code:
Output:
postgres=# postgres=# CREATE TABLE IF NOT EXISTS countries ( postgres(# COUNTRY_ID varchar(2) NOT NULL UNIQUE PRIMARY KEY, 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 created table :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a SQL statement to create a table named jobs, including job_id, job_title, min_salary and max_salary, and make sure that, the default value for job_title is blank and min_salary is 8000 and max_salary is NULL will be entered automatically at the time of insertion if no value assigned for the specified columns.
Next: Write a SQL statement to create a table countries including columns country_id, country_name and region_id and make sure that the column country_id will be unique and store an auto-incremented value.
What is the difficulty level of this exercise?