If you need to create foreign key while creating a new table
CREATE TABLE table1(
id SERIAL PRIMARY KEY,
column1 varchar(n) NOT NULL,
table2_id SMALLINT REFERENCES table2(id)
The above commands will create a table with name 'table1' and three columns named 'id'(Primary key), 'column1', 'table2_id'(foreign key of table1 that references id column of table2).
DATATYPE 'serial' will make the column that uses this datatype as a auto-generated column, when inserting values into the table you need not mention this column at all, or you can give 'default' without quotes at the value place.
A primary key column is always added to index of the table with value 'tablename_pkey'.
If foreign key is added at table creation time, A CONSTRAINT is added with pattern '(present_table_name)_(foreign_key_id_name)_fkey'.
When adding a foreign key, we have to input the keyword 'REFERENCES' next to column name because we want to tell the postgres that this column references a table and then next to references we have to give the table for reference and in brackets give the column name of the referenced table, usually foreign keys are given as primary key columns.
If you want foreign key to an existing table on existing column
ALTER TABLE table1
ADD CONSTRAINT table1_table2_id_id_fkey
FOREIGN KEY (table2_id) REFERENCES table2(id);
NOTE: brackets'()' after FOREIGN KEY and REFERENCES tabel2 are compulsory or else postgres will throw error.