Translate

Tuesday, October 29, 2024

How to define foreign key in POSTGRESQL

A foreign key is a column(s) in one table that references the primary key of another table, establishing a link between the two tables. 

Syntax


  constraint <title> Foreign key (<ColumnName>) References <SourceTableName>(<columnnameinsource>),
  

Example

CREATE TABLE Warriors (
  WarriorID uuid primary key,
  WarriorName VARCHAR(200),
  WarriorTitleID uuid not null,
  WarriorWingID uuid null,
  IsActive boolean,
  constraint Warrior_To_Title Foreign key (WarriorTitleID) References Titles(TitleID),
  constraint Warrior_To_Wing Foreign Key (WarriorWingID) References Wings(WingID)
);

How to define Primary Key in POSTGRESQL

 Primary Key is a key how data physically aligned in the memory system. It will give ability for fast retrieval of data.

Key aspects in primary key

  1. When you define a primary key PostgreSQL automatically creates a unique B-tree index on the columns available in the table.
  2. Use SERIAL or BIGSERIAL for auto-incrementing primary keys. These types automatically generate unique sequential values. refer (available data types in POSTGRESQL)
  3. Each table can have only one primary key
  4. but a primary key can consist of multiple columns (composite key).

Example for creating table

CREATE TABLE Wings
         ( 
             WingID uuid primary key, 
             WingName VARCHAR(100), 
             IsActive boolean 
        );

Alter the existing table:

ALTER TABLE Wings ADD COLUMN ColID SERIAL PRIMARY KEY;


How to Create Table in POSTGRESQL

Creating table in PostgreSQL is very much similar like MSSQL. Syntax is like below, 

 CREATE TABLE <TableName>
 (
    <column name1> <data type>,
    <column name2> <data type>,
    ...
);

Example: 
     CREATE TABLE Wings
         ( 
             WingID uuid primary key, 
             WingName VARCHAR(100), 
             IsActive boolean 
        );

Monday, October 28, 2024

PREGRESQL supported data types

 


Below table show the datatypes available in POSTGRESQL

NameAliasesDescription
bigintint8signed eight-byte integer
bigserialserial8autoincrementing eight-byte integer
bit [ (n) ] fixed-length bit string
bit varying [ (n) ]varbit [ (n) ]variable-length bit string
booleanboollogical Boolean (true/false)
box rectangular box on a plane
bytea binary data (byte array)
character [ (n) ]char [ (n) ]fixed-length character string
character varying [ (n) ]varchar [ (n) ]variable-length character string
cidr IPv4 or IPv6 network address
circle circle on a plane
date calendar date (year, month, day)
double precisionfloat8double precision floating-point number (8 bytes)
inet IPv4 or IPv6 host address
integerintint4signed four-byte integer
interval [ fields ] [ (p) ] time span
json textual JSON data
jsonb binary JSON data, decomposed
line infinite line on a plane
lseg line segment on a plane
macaddr MAC (Media Access Control) address
macaddr8 MAC (Media Access Control) address (EUI-64 format)
money currency amount
numeric [ (ps) ]decimal [ (ps) ]exact numeric of selectable precision
path geometric path on a plane
pg_lsn PostgreSQL Log Sequence Number
pg_snapshot user-level transaction ID snapshot
point geometric point on a plane
polygon closed geometric path on a plane
realfloat4single precision floating-point number (4 bytes)
smallintint2signed two-byte integer
smallserialserial2autoincrementing two-byte integer
serialserial4autoincrementing four-byte integer
text variable-length character string
time [ (p) ] [ without time zone ] time of day (no time zone)
time [ (p) ] with time zonetimetztime of day, including time zone
timestamp [ (p) ] [ without time zone ] date and time (no time zone)
timestamp [ (p) ] with time zonetimestamptzdate and time, including time zone
tsquery text search query
tsvector text search document
txid_snapshot user-level transaction ID snapshot (deprecated; see pg_snapshot)
uuid universally unique identifier
xml XML data               

How To Rename Existing Database in POSTGRESQL

using below query you can rename the database

ALTER DATABASE <FromDBName> RENAME TO <ToDBName>

Note: Apart from this connection need to close other open connection to the database to close the connection refer close existing connections

How to kill all open connections to POSTGRESQL using SQL command

 To close all existing connection to your database. We can pass the process/connection id to the predefined function pg_terminate_backend. Execute below query

SELECT 

    pg_terminate_backend(pid) 

FROM 

    pg_stat_activity 

WHERE 

    -- exclude current connection window

    pid <> pg_backend_pid()

    AND datname = '<database name>

Note: Database name is case sensitive

How to Create Data Base In POSTGRESQL Using pgAdmin

 In left pane select 

Select Server -> Databases right click -> select Create Database -> It will open create Database window.


In General tab provide the data base name and owner (user name) for the database
In Definition tab you can provide the template for the database
CREATE DATABASE actually works by copying an existing database. By default, it copies the standard system database named template1. Thus that database is the “template” from which new databases are made. If you add objects to template1, these objects will be copied into subsequently created user databases. This behavior allows site-local modifications to the standard set of objects in databases. For example, if you install the procedural language PL/Perl in template1, it will automatically be available in user databases without any extra action being taken when those databases are created.

However, CREATE DATABASE does not copy database-level GRANT permissions attached to the source database. The new database has default database-level permissions.

There is a second standard system database named template0. This database contains the same data as the initial contents of template1, that is, only the standard objects predefined by your version of PostgreSQL. template0 should never be changed after the database cluster has been initialized. By instructing CREATE DATABASE to copy template0 instead of template1, you can create a “pristine” user database (one where no user-defined objects exist and where the system objects have not been altered) that contains none of the site-local additions in template1. This is particularly handy when restoring a pg_dump dump: the dump script should be restored in a pristine database to ensure that one recreates the correct contents of the dumped database, without conflicting with objects that might have been added to template1 later on.

Another common reason for copying template0 instead of template1 is that new encoding and locale settings can be specified when copying template0, whereas a copy of template1 must use the same settings it does. This is because template1 might contain encoding-specific or locale-specific data, while template0 is known not to.

To create a database by copying template0, use:

SQL syntax

CREATE DATABASE dbname TEMPLATE template0;

In Security tab you can define what are the user will have access to the database and their access rights.


Save It will create the database in the server




How To create new login (user) in POSTGRESQL in pgAdmin


Once connecter to the server. In left pane 

Right click on User/Login Roles -> select create -> click on user/login role

It will Open window to create Group role. In General tab you can provide the name of the user and Definition  tab you provide the password, expiration date (user will be automatically deactivated after the specified date and time) and connection limit (concurrently how many connection can be done through the user). In Privileges tab you can define this user can login (if it is unchecked it will be considered as role) to the pgadmin and have any super user permission such as create database, create role and inherit rights from parent option (be caesious this will give all databases access which are already assigned to the creating user). In membership tab you can add this user to any group
         


 

Sunday, October 27, 2024

How To Connect POSTGRESQL

After Installation of POSTGRESQL open pgAdmin application. It is like MSSQL server management studio tool. It used to connect datatbase and run queries you wanted.


 In left panel expand the server list and pick which server you want to connect.

Right click on server name -> click on connect server


Enter password -> click Ok it will connect you to the server.