Fetch Data in PostgreSql
Fetching Data in PostgreSQL (SELECT Query) 🚀
The SELECT statement is used to retrieve data from PostgreSQL tables.
1. Basic Syntax
SELECT column1, column2 FROM table_name;
To fetch all columns, use:
SELECT * FROM table_name;
2. Fetch All Rows
SELECT * FROM users;
(Returns all columns and rows from the users table)
3. Fetch Specific Columns
SELECT name, email FROM users;
(Only returns name and email columns)
4. Fetch Data with Filtering (WHERE)
SELECT * FROM users WHERE age > 25;
(Returns users older than 25)
SELECT * FROM users WHERE email = 'alice@example.com';
(Returns only the user with email "alice@example.com")
5. Fetch Data with Sorting (ORDER BY)
SELECT * FROM users ORDER BY age DESC;
(Sorts users by age in descending order)
SELECT * FROM users ORDER BY name ASC;
(Sorts users alphabetically)
6. Fetch Limited Number of Rows (LIMIT)
SELECT * FROM users LIMIT 5;
(Only returns the first 5 rows)
SELECT * FROM users ORDER BY age DESC LIMIT 3;
(Returns the 3 oldest users)
7. Fetch Data with Offset (LIMIT OFFSET)
SELECT * FROM users ORDER BY id LIMIT 5 OFFSET 10;
(Skips the first 10 rows and fetches the next 5)