Showing posts with label postgresql. Show all posts
Showing posts with label postgresql. Show all posts

 

How to Query Data in PostgreSQL — A Beginner’s Guide with Examples

Introduction

PostgreSQL (or Postgres) is one of the most powerful and open-source relational database systems used by developers, data analysts, and businesses worldwide.

If you’ve already created a database and inserted some records, the next logical step is learning how to query data — that means retrieving, filtering, sorting, and analyzing the information stored in your tables.

In this post, we’ll explore how to query data in PostgreSQL using simple and practical SQL commands that even beginners can master.


What Is a Query?

A query is a request you send to the database to get specific information.
You use SQL (Structured Query Language) commands to write these requests.

In PostgreSQL, the most common query command is:

SELECT
It tells the database which columns and records you want to retrieve.

Basic Query Syntax

Here’s the basic structure of a SELECT query in PostgreSQL:

SELECT column1, column2, ...
FROM table_name;
Example:
SELECT first_name, last_name
FROM employees;
✅ This retrieves the first_name and last_name columns from the employees table.

If you want to select all columns, use the asterisk *:

SELECT * FROM employees;

🔍 Filtering Data with WHERE

To get only specific records, use the WHERE clause.

Example:

SELECT * 
FROM employees
WHERE department = 'Finance';

This query returns only employees who work in the Finance department.

You can also use comparison operators like:

Operator Description Example
=         Equal to         WHERE salary = 50000
<> or !=         Not equal to         WHERE department <> 'HR'
>, <, >=, <=         Greater or less than         WHERE age > 30
LIKE         Pattern matching      WHERE name LIKE 'A%' (names starting with A)
IN         Matches a list         WHERE department IN ('HR', 'IT', 'Finance')

🎯 Sorting Results with ORDER BY

To arrange results in ascending or descending order:

SELECT name, salary
FROM employees
ORDER BY salary DESC;

DESC = descending (highest first)
ASC = ascending (lowest first, default)


🧮 Limiting the Number of Results

You can show only a specific number of rows using LIMIT.

Example:

SELECT * 
FROM employees
LIMIT 5;

This displays only the first five rows from the result set.


🧠 Combining Conditions with AND / OR

SELECT * 
FROM employees
WHERE department = 'IT' AND salary > 40000;

You can also use OR:

SELECT * 
FROM employees
WHERE department = 'IT' OR department = 'Finance';

📊 Aggregate Functions for Summary Data

PostgreSQL supports powerful functions for summarizing data:

Function Description Example
COUNT() Counts rows SELECT COUNT(*) FROM employees;
AVG() Average value SELECT AVG(salary) FROM employees;
SUM() Total value SELECT SUM(salary) FROM employees;
MAX() Highest value SELECT MAX(salary) FROM employees;
MIN() Lowest value SELECT MIN(salary) FROM employees;

You can combine them with GROUP BY for summaries by category:

SELECT department, AVG(salary)
FROM employees
GROUP BY department;

🔗 Joining Tables

In real projects, data is often split into multiple tables.
To combine related data, use JOIN.

Example (joining employees and departments):

SELECT e.name, d.department_name
FROM employees e
JOIN departments d
ON e.department_id = d.id;

Types of joins:

  • INNER JOIN – only matching records

  • LEFT JOIN – all from left + matches from right

  • RIGHT JOIN – all from right + matches from left

  • FULL JOIN – all records from both sides


🧰 Practical Example

Let’s assume we have a database with a table called students.

id name age grade city
1 Arun 15 A Kochi
2 Meera 14 B Thrissur
3 Rahul 15 A Ernakulam
4 Anju 13 C Kollam

Query example:

SELECT name, grade
FROM students
WHERE city = 'Ernakulam';

Output:

name grade
Rahul A

⚙️ Tools to Run PostgreSQL Queries

You can write and test these queries using:

  • pgAdmin (PostgreSQL’s official GUI)

  • psql command-line tool

  • DBeaver (open-source database client)

  • DataGrip (JetBrains IDE)

  • VS Code SQL extensions


🚀 Conclusion

Querying data in PostgreSQL is one of the most essential skills for working with databases.
With the right SELECT, WHERE, and JOIN commands, you can pull meaningful insights from your data easily.

Start simple, practice often, and soon you’ll be able to write complex queries confidently.

💡 Tip: Try combining filters, joins, and aggregates in a single query — that’s where PostgreSQL truly shines!












 


INSERT QUERY IN POSTGRESQL

INSERT — create new rows in a table.

What is insert query?

The Insert command in the relational databases PostgreSQL, SQL Server, and Oracle's Structured Query Language (SQL) data manipulation language (DML) is often used. The insert command is used to add one or more rows with certain table column values to a database table.

How do you write an insert query?

The INSERT INTO statement has two fundamental syntaxes, which are shown below. 

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) 
VALUES (value1, value2, value3,...valueN);

These are the names of the columns in the table that you wish to enter the data into: column1, column2, column3,...columnN. 
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

If you are adding values to all of the table's columns, you might not need to specify the column(s) name in the SQL query. But make sure the data are arranged in the same order as the table's column order. 
CREATE TABLE Item
(  ItemId       BIGINT          PRIMARY KEY,
   ItemCode     VARCHAR(30)     NOT NULL,
   ItemName     VARCHAR(100)    NOT NULL
); 

Check created tables list in PostgreSQL database. Click here to check Postgres show tables.

Insert a single row into table item 

INSERT INTO item VALUES
(1, 'I001', 'Cabinet'); 

To insert multiple rows using the multirow VALUES syntax

INSERT INTO item (itemid, itemcode, itemname) VALUES
(2,'B6717', 'Tampopo'),
(3,'HG120', 'The Dinner Game');

 

Please visit other related articles



novice techie

 

How to create user in PostgreSQL | How to create new database user account

In Postgre SQL CREATE USER command used to create new database user account. To use the CREATE USER command the you must be a database superuser with all privilege. CREATE USER command can be used using the PSQL and PgAdmin tool.

Postgres Create user with password in post gre sql using PSQL syntax

CREATE USER username WITH ENCRYPTED PASSWORD  'password';

Postgres Create user with password in postgresql using PSQL example 

CREATE USER novice WITH ENCRYPTED PASSWORD  'novice';

Postgresql Novice techie

After successful creation of new user with password using the PSQL, the message will be displayed like above. 

Postgres Create user with password in postgresql using PgAdmin query tool syntax

CREATE USER username WITH ENCRYPTED PASSWORD  'password';

Postgres Create user with password in post gre sql using PgAdmin query tool example 

CREATE USER novice1 WITH ENCRYPTED PASSWORD  'novice1';
Postgresql Novice techie

After successful creation of new user with password using the PgAdmin, the message will be displayed like above. You can see the newly created users under the Login/Group Roles section in PgAdmin.
Postgresql Novice techie

PostgreSQL - Grant all privileges postgres | Postgres grant all privileges on database to user?

We can create database with the name novicetechie and create a user with the name novice to check the below mentioned postgresql grant permission sql queries. For create database example click here. For creating user example check above.

Grant CONNECT privileges to the database syntax

GRANT CONNECT ON DATABASE database_name TO username;

Grant CONNECT privileges to the database example

GRANT CONNECT ON DATABASE novicetechie TO novice;

Grant USAGE on schema syntax

GRANT USAGE ON SCHEMA schema_name TO username;

Grant USAGE on schema example

GRANT USAGE ON SCHEMA public TO novice;

Grant on all tables for DML statements: SELECT, INSERT, UPDATE, DELETE syntax

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA schema_name TO username;

Grant on all tables for DML statements: SELECT, INSERT, UPDATE, DELETE example

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO novice;

Grant all privileges on all tables in the schema syntax

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA schema_name TO username;

Grant all privileges on all tables in the schema example

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO novice;

Grant all privileges on all sequences in the schema syntax

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA schema_name TO username;

Grant all privileges on all sequences in the schema example

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO novice;

Grant all privileges on the database syntax

GRANT ALL PRIVILEGES ON DATABASE database_name TO username

Grant all privileges on the database example

GRANT ALL PRIVILEGES ON DATABASE novicetechie TO novice;

Permission to create database syntax

ALTER USER username CREATEDB;

Permission to create database example

ALTER USER novice novicetechie;

Make a user as superuser syntax

ALTER USER username WITH SUPERUSER;

Make a user as superuser example

ALTER USER novice WITH SUPERUSER;

Remove superuser status syntax

ALTER USER username WITH NOSUPERUSER;

Remove superuser status example

ALTER USER novice WITH NOSUPERUSER;

PostgreSQL security : Postgres grant all privileges to user on a specific database only | Postgresql database security best practices

Please visit other related articles

PostgreSQL: Add macros in PgAdminIII
PostgreSQL: Export PostgreSQL data in to excel file
PostgreSQL: How to restrict the user access to the databases in Postgresql based on the permission
PostgreSQL: List table details using Alt+F1 in PostgreSQL
PostgreSQL: How to get ROW_COUNT of last executed query in PostgreSQL like MS SQL @@ROWCOUNT ?

 

Postgresql Novice techie

PostgreSQL Index | Postgres Index Types | Can we CREATE INDEX in Postgresql?

PostgreSQL has several index types: B-tree, Hash, GiST, SP-GiST, GIN and BRIN. Each Index type uses a different algorithm that is best suited to different types of queries. By default, the postgres CREATE INDEX command creates B-tree indexes, which fit the most common situations. 

Postgres CREATE INDEX | Postgresql Index

When you create index PostgreSQL keep in mind that the postgresql index name should be the meaningful name and it should be identifiable to which table this index is created. So the PostgreSQL index naming should be easy to remember and meaningful. Specify any of the index type like B-tree, Hash, GiST, SP-GiST, GIN and BRIN, if not specified any index type by default it will create the post gre sql index with the type B-tree. The basic syntax of postgres CREATE INDEX statement is as follows.

CREATE INDEX index_name ON table_name;

Singlecolumn Index

An index created on a single column in a table is known as singlecolumn index. The basic syntax for singlecloumn index in postgres is as follows
CREATE INDEX IndexName ON TableName (ColumnName);
An example for singlecolumn index in postgres is as follows
CREATE INDEX index_employee_name ON employee(name);

Can we CREATE INDEX on multiple columns in Postgresql?

Multicolumn Index | Create Index postgres multiple columns

An index created on more than one column is known as a multicolumn index.  The basic syntax for multiplecloumn index in postgres is as follows 
CREATE INDEX IndexName ON TableName (ColumnName1,ColumnName2);

An example for the multicolumn index in postgres is as follows

CREATE INDEX index_employee_code_name ON employee (code,name);

Postgres add Unique Constraint - Unique Index

Unique indexes are used to prevent duplicate data.
CREATE UNIQUE INDEX index_employee_code ON employee (code);

Postgres DROP INDEX

DROP INDEX in postgres drops an existing index from the database. You must be the index owner in order to run this command.
DROP INDEX index_employee_name;

Postgres show indexes

PostgreSQL list indexes created in a table using the pg_indexes view. The details about index created in a PostgreSQL database can be retrieve from the pg_indexes view. These five columns in the pg_indexes view gives the useful information about the indexes created in postgresql table. 

schemaname - Displays the name of the schema that contains the tables and indexes
tablename Displays the name of the tables of indexes
indexname Displays the index names
tablespace Displays the tablespace name that contains the indexes
indexdef - Displays the create index statement

Execute below sql statement to show the all postgresql index details in postgresql database.
SELECT * FROM pg_indexes WHERE schemaname = 'public';

Execute below sql statement to show the postgresql index details of a specific table.
SELECT * FROM pg_indexes WHERE schemaname = 'public' AND tablename = 'item';










How to create database in PgAdmin 4


how to create database in pgadmin 4

Open connected server, then right click "databases" to create new database. Select "Create" then click on the option "Database".


how to create database in pgadmin 4

Create Database wizard will be opened to create database. 

how to create database in pgadmin 4

Give database name and other details to create database using PgAdmin 4. Here we will give the database name as "NoviceTechie", then click "Save"

how to create database in pgadmin 4


Database will be created under the Databases.

Create database in PostgreSQL using PSQL

In Postgres CREATE DATABASE command creates new PostgreSQL database. The syntax to create database in PostgreSQL is
CREATE DATABASE database_name
WITH
   [OWNER =  role_name]
   [TEMPLATE = template]
   [ENCODING = encoding]
   [LC_COLLATE = collate]
   [LC_CTYPE = ctype]
   [TABLESPACE = tablespace_name]
   [ALLOW_CONNECTIONS = true | false]
   [CONNECTION LIMIT = max_concurrent_connection]
   [IS_TEMPLATE = true | false ]

PSQL command to create database in PostgreSQL server is

CREATE DATABASE database_name;

Using above postgres createdb command will create a new database in post gre sql server with default parameter. To execute the CREATE DATABASE statement you need to have a superuser role or a special CREATEDB privilege.

Psql list databases command is

A Single Postgres server process has the capability to handle multiple databases simultaneously. Each database is stored in distinct sets of files within its dedicated directory within the server's data directory. To observe all the defined databases on the server, you can utilize the \list meta-command or its shortcut \l.
\l

This command used to list all databases created in Postgresql server.

Postgres list tables using PSQL PgAdmin, Postgres Show tables using PSQL

PgAdmin list tables

Open Server then click on Databases tree, then click on database which you want to see the tables list, then click Public, then click on tables menu, from there you can view tables list from PgAdmin 4.
By expanding tables menu you can view the tables list.



Postgres list tables shortcut in pgadmin using macros

We can enable macro for using shortcut keys in PostgreSQL PgAdmin. To enable macro open post gre sql query window to select the "Manage macros" menu from "Macros".

How to add macros in PgAdmin.

How to display tables list in the current database using PostgreSQL

Postgres list tables using SQL query in a database. 
SELECT  relname as "Table"
FROM 	pg_catalog.pg_statio_user_tables 
ORDER BY relname;
Using above mentioned query all user defined tables in a PostgreSQL database can list. Using macros feature we can add the shortcuts for tables list in post gre sql database. To enable macro refer How to enable macros in PgAdmin.


PostgreSQL list tables by size | Postgresql table size list
SQL query to display all table names and table size in a PostgreSQL database.
SELECT	relname 								AS "Table",
	pg_size_pretty(pg_total_relation_size(relid)) 				AS "Total Size",
	pg_size_pretty(pg_relation_size(relid)) 				AS "Data Size",
	pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) AS "Index Size"
FROM 	pg_catalog.pg_statio_user_tables 
ORDER BY pg_total_relation_size(relid) DESC;

Using above mentioned query all user defined tables list and its table size in a post gre sql database can list. Using macros feature we can add the shortcuts for tables list in PostgreSQL database. To enable macro refer How to enable macros in PgAdmin.


How to get PostgreSQL column list and datatypes of that table?

Postgres show tables using PSQL

PSQL show tables - In PSQL commands for listing tables in PostgreSQL database is

\dt

The \dt command in PSQL list tables in the database which we selected.

Postgres show tables - Using the below PSQL commands, Postgres show tables more details
\dt+
The \dt+ command in PSQL list tables along with the tables size and name of columns.

Show databases in PSQL

In PSQL commands for show databases in a PostgreSQL server is
\l
The \l command in PSQL show databases in a PostgreSQL server.

PSQL show db size 

PSQL list databases with size using below mentioned PSQL command. Postgres show databases size , database name and other details related to the databases in a PostgreSQL server
\l+

List database size postgres 

Postgres list database size using the below mentioned  SQL query.
SELECT 	t1.datname AS db_name,  
	pg_size_pretty(pg_database_size(t1.datname)) AS db_size
FROM 	pg_database t1
ORDER BY pg_database_size(t1.datname) DESC;

Please visit other related articles

PostgreSQL: Add macros in PgAdminIII
PostgreSQL: Export PostgreSQL data in to excel file
PostgreSQL: How to restrict the user access to the databases in Postgresql based on the permission
PostgreSQL: List table details using Alt+F1 in PostgreSQL
PostgreSQL: How to get ROW_COUNT of last executed query in PostgreSQL like MS SQL @@ROWCOUNT ?