Querying data in PostgreSQL involves using SQL (Structured Query Language) statements to retrieve, manipulate, and manage data stored in a PostgreSQL database.
Some common SQL queries you can use to interact with your PostgreSQL database:
SELECT Statement:
SELECT column1, column2 FROM tablename WHERE condition;
FROM Clause:
SELECT column1, column2 FROM employees;
WHERE Clause:
SELECT column1, column2 FROM tablename WHERE column3 = 'value';
ORDER BY Clause:
SELECT column1, column2 FROM tablename ORDER BY column1 ASC;
LIMIT and OFFSET:
SELECT column1, column2 FROM tablename LIMIT 10 OFFSET 20;
GROUP BY Clause:
SELECT department, COUNT(*) FROM employees GROUP BY department;
Aggregate Functions:
SELECT department, AVG(salary) FROM employees GROUP BY department;
JOIN Statements:
SELECT orders.order_id, customers.customer_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id;
Subqueries:
SELECT column1 FROM tablename WHERE column2 IN (SELECT column2 FROM othertable WHERE condition);
Conditional Statements (CASE):
SELECT name, CASE WHEN age >= 18 THEN 'Adult' ELSE 'Minor' END AS age_category FROM people;
DISTINCT:
SELECT DISTINCT column1 FROM tablename;
LIKE Operator:
SELECT product_name FROM products WHERE product_name LIKE 'A%';
DELETE Statement:
DELETE FROM tablename WHERE condition;
UPDATE Statement:
UPDATE tablename SET column1 = new_value WHERE condition;
INSERT INTO Statement:
INSERT INTO tablename (column1, column2) VALUES (value1, value2);
Remember to connect to your PostgreSQL database using a PostgreSQL client or tool (e.g., psql
, pgAdmin, or a programming language-specific library) before executing these SQL queries.
Make sure you have the necessary privileges to perform the desired operations on the database tables.