Introduction
In this article, the content will be specifically focus on the process for creating a PostgreSQL table. So, it will show how to create a table in PostgreSQL database. In this case, there is a specific query command which is important for creating that table. Before getting on to the command execution for creating the table, below are the preparation in order to be able to do that :
-
First of all, prepare PostgreSQL database server or PostgreSQL tool. For a reference, just check into several articles exist discussing about that in order to be able to do that.
-
Following after, just start the PostgreSQL database server.
-
Soon after that, try to get in to the PostgreSQL database command console as follows :
Microsoft Windows [Version 10.0.22000.1219] (c) Microsoft Corporation. All rights reserved. C:\Users\Personal>psql -Upostgres Password for user postgres: psql (14.2) WARNING: Console code page (437) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page "Notes for Windows users" for details. Type "help" for help. postgres=#
How to Create PostgreSQL Table using specific query command
Using the preparation above, just continue on the process by executing the query command. Off course, it is the query command for creating table in PostgreSQL database server. The following is an example of a query command for creating a table with the name of ‘product’. That table consists of three columns including ‘product_id’ with the type of integer, product_code with the type of character and product_name with also the type of character.
-
First of all, just connect to the database or use the associated database. Actually, specifying the database is also possible in the beginning when performing or executing the command for accessing PostgreSQL database command console. Just add an additional parameter -d with the attribute of the database name. Below is the query for selecting the associated database in the PostgreSQL command console :
postgres=# \c db_myapp You are now connected to database "db_myapp" as user "postgres". db_myapp=#
-
Last but not least, just execute the query :
db_myapp=# create table t_product(product_id int primary key, product_code varchar(30) unique not null, product_name varchar(100) not null); CREATE TABLE db_myapp=# \d t_product; Table "public.t_product" Column | Type | Collation | Nullable | Default --------------+------------------------+-----------+----------+--------- product_id | integer | | not null | product_code | character varying(30) | | not null | product_name | character varying(100) | | not null | Indexes: "t_product_pkey" PRIMARY KEY, btree (product_id) "t_product_product_code_key" UNIQUE CONSTRAINT, btree (product_code) db_myapp=#