You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
PostgreSQL, often simply called Postgres, is a powerful, open-source object-relational database management system (ORDBMS). It has a strong reputation for reliability, feature robustness, and performance. PostgreSQL runs on all major operating systems, including Linux, Mac OS, and Windows.
4
-
5
-
PostgreSQL was first developed in 1986 at the University of California, Berkeley as part of the POSTGRES project. It has since evolved into one of the most advanced and widely-used database systems, with a strong community supporting its development.
6
-
3
+
PostgreSQL, often simply called Postgres, is a powerful, open-source object-relational database management system (ORDBMS). It has a strong reputation for reliability, feature robustness, and performance. PostgreSQL was first developed in 1986 at the University of California, Berkeley as part of the POSTGRES project. It has since evolved into one of the most advanced and widely-used database systems, with a strong community supporting its development. PostgreSQL supports all major operating systems, including Linux, Mac OS, and Windows.
7
4
8
5
## Key Features of PostgreSQL
9
6
10
7
PostgreSQL offers a wide range of features that make it a popular choice for many applications:
11
8
12
-
1.**Extensive data types**: PostgreSQL supports a large variety of built-in data types and allows users to define their own custom data types. It can handle complex data types such as arrays, JSON, and geometric types[1][2].
9
+
1.**Extensive data types**: PostgreSQL supports a large variety of built-in data types and allows users to define their own custom data types. It can handle complex data types such as arrays, JSON, and geometric types.
13
10
14
-
2.**ACID compliance**: PostgreSQL adheres to the ACID principles (Atomicity, Consistency, Isolation, Durability), ensuring reliable and trustworthy transactions[2].
11
+
2.**ACID compliance**: PostgreSQL adheres to the ACID principles (Atomicity, Consistency, Isolation, Durability), ensuring reliable and trustworthy transactions. [More details](databases_introduction.md#acid-compliance)
15
12
16
-
3.**Concurrency control**: PostgreSQL uses multi-version concurrency control (MVCC) to provide high concurrency without conflicts, allowing multiple transactions to access the same data simultaneously[2][4].
13
+
3.**Concurrency control**: PostgreSQL uses multi-version concurrency control (MVCC) to provide high concurrency without conflicts, allowing multiple transactions to access the same data simultaneously.
17
14
18
-
4.**Advanced querying capabilities**: PostgreSQL supports complex SQL queries, subqueries, common table expressions (CTEs), recursive queries, and window functions. It also allows users to define their own functions, triggers, and stored procedures in various programming languages[2][4].
15
+
4.**Advanced querying capabilities**: PostgreSQL supports complex SQL queries, subqueries, common table expressions (CTEs), recursive queries, and window functions. It also allows users to define their own functions, triggers, and stored procedures in various programming languages.
19
16
20
-
5.**Full-text search**: PostgreSQL provides powerful full-text search capabilities, including stemming, ranking, and phrase-searching support. It uses indexes like B-tree, hash, and GiST to optimize search performance[2].
17
+
5.**Full-text search**: PostgreSQL provides powerful full-text search capabilities, including stemming, ranking, and phrase-searching support. It uses indexes like B-tree, hash, and GiST to optimize search performance.
21
18
22
-
6.**Replication and high availability**: PostgreSQL supports various replication strategies, such as asynchronous streaming, logical, and synchronous replication, providing data redundancy, fault tolerance, and high availability[2].
19
+
6.**Replication and high availability**: PostgreSQL supports various replication strategies, such as asynchronous streaming, logical, and synchronous replication, providing data redundancy, fault tolerance, and high availability.
23
20
24
-
7.**Security and authentication**: PostgreSQL offers robust security features, including SSL encryption, username/password authentication, LDAP authentication, Kerberos authentication, role-based access control (RBAC), and row-level security (RLS)[2].
25
-
26
-
8.**Extensibility**: PostgreSQL is designed to be extensible, allowing users to add custom data types, operators, and functions to the database to expand its capabilities[1][2].
21
+
7.**Security and authentication**: PostgreSQL offers robust security features, including SSL encryption, username/password authentication, LDAP authentication, Kerberos authentication, role-based access control (RBAC), and row-level security (RLS).
27
22
28
23
## Setting Up PostgreSQL
29
24
30
25
To get PostgreSQL running on your local machine, you will need to have the following tools installed:
31
26
32
-
1.**PostgreSQL Server**: To set up PostgreSQL server on your local machine, follow these step-by-step instructions provided on the [official website](https://www.postgresql.org/download/). Once the installation is complete, you can run the server by opening the application.
27
+
1.**PostgreSQL Server**: You can follow the step-by-step instructions provided on the [official website](https://www.postgresql.org/download/). Once the installation is complete, you can run the server by opening the application.
33
28
34
-
2.**PostgreSQL Admin/Dev Tools**: Once the PostgreSQL server is installed, you can install tools to manage PostgreSQL and interact with it. There are multiple such tools, each with its own set of features but most of them support the basic features. Here are famous ones - [PgAdmin](https://www.pgadmin.org/), [DBeaver](https://dbeaver.io/), or you can even use terminal tools like [Psql](https://www.postgresql.org/docs/current/app-psql.html).
29
+
2.**PostgreSQL Admin/Dev Tools**: Once the PostgreSQL server is installed, you can install tools to manage and interact with PostgreSQL. There are multiple choices, each with its own set of unique features and all of them support the basic functionalities. Here are some famous ones - [PgAdmin](https://www.pgadmin.org/), [DBeaver](https://dbeaver.io/), or you can even use terminal tools like [Psql](https://www.postgresql.org/docs/current/app-psql.html).
35
30
36
31
!!! Hint
37
32
**Installation on Mac**
38
33
39
-
PostgreSQL can be installed on Mac by using homebrew by just running the command `brew install postgresql`. For more options, follow the [official website](https://www.postgresql.org/download/macosx/).
40
-
41
-
## Snippets
42
-
43
-
Learning PostgreSQL through sample code is a great way to understand its capabilities and how it can be used in different scenarios. Below are 10 sample code snippets in increasing order of complexity, designed to help you understand various aspects of PostgreSQL:
44
-
45
-
### PostgreSQL Query Language
46
-
47
-
Let's first explore some of the most basic operations in PostgreSQL. To get started we will cover the PostgreSQL Query Language, which is a variant of the SQL language and would look very familar if you are a beginner.
34
+
PostgreSQL can be installed on Mac by using `homebrew`. Run the command `brew install postgresql`. For more details and options, follow the [official website](https://www.postgresql.org/download/macosx/).
48
35
49
-
If you are using terminal, then you can activate psql mode by running `psql`. Once inside you can connect to the database by running the following command:
36
+
## Learning the Basics
50
37
51
-
```sql
52
-
-- Connecting to a PostgreSQL database
53
-
-- Use a client or terminal with appropriate access credentials
54
-
\c my_database;
55
-
```
38
+
Practice makes man perfect, so let's learn PostgreSQL through sample codes. Below are some sample code snippets in increasing order of complexity, designed to help you understand various aspects of PostgreSQL.
56
39
57
-
Or you can use any of the user-interface tools like PgAdmin for better user experience.
58
-
59
-
#### Connecting to a PostgreSQL Database
40
+
!!! Hint
41
+
Before we begin, please note that to interact with the database, you need to use the PostgreSQL Query Language, which is a variant of the SQL language. If you are using terminal, then you can activate psql mode by running `psql`. Once inside you can connect to the database by running the following command:
60
42
43
+
```sql
44
+
-- Connecting to a PostgreSQL database
45
+
-- Use a client or terminal with appropriate access credentials
46
+
\c my_database;
47
+
```
48
+
Or you can use any of the user-interface tools like PgAdmin for better user experience.
61
49
62
-
####Creating a Database
50
+
**1. Creating a Database**
63
51
64
52
```sql
65
-
-- Creating a database
53
+
-- Creating a database. Replace `my_database` with your database name
66
54
CREATEDATABASEmy_database;
67
55
```
68
56
69
-
#### Creating a Table
57
+
**2. Creating a Table**
58
+
70
59
71
60
```sql
72
-
-- Creating a simple table
61
+
-- Creating a simple table. Replace `employees` with your table name
73
62
CREATETABLEemployees (
74
63
id SERIALPRIMARY KEY,
75
64
name VARCHAR(50),
76
65
position VARCHAR(50),
66
+
departmentid INT,
77
67
salary DECIMAL
78
68
);
79
69
```
80
70
71
+
!!! Hint
72
+
[Here is a detailed list](https://www.postgresql.org/docs/current/datatype.html) of all supported data types in PostgreSQL. Note, you can also [create custom data types](https://www.postgresql.org/docs/current/sql-createtype.html).
-- Using an aggregate function to get the average salary
149
163
SELECTAVG(salary) FROM employees;
164
+
165
+
-- Group by a column (ex: getting the average salary by department)
166
+
SELECT department_name, AVG(salary) AS avg_salary
167
+
FROM employees
168
+
JOIN departments ONemployees.id=departments.id
169
+
GROUP BY department_name;
150
170
```
151
171
152
172
**10. Complex Query with Subquery and Grouping**
@@ -160,27 +180,208 @@ FROM (
160
180
JOIN departments ONemployees.id=departments.id
161
181
) AS department_salaries
162
182
GROUP BY department_name;
163
-
164
183
```
165
184
166
185
These examples cover a range of basic to more complex tasks you can perform with PostgreSQL, from establishing a connection to executing advanced queries. As you become more comfortable with these operations, you'll be able to tackle more complex scenarios and optimize your database interactions.
167
186
168
-
### Python Sample Code
187
+
## Python Sample Code
188
+
189
+
There are multiple python packages available for PostgreSQL like, [psycopg2](https://pypi.org/project/psycopg2/) and [asyncpg](https://pypi.org/project/asyncpg/). For this section, we will use [asyncpg](https://pypi.org/project/asyncpg/) package that provides support for asynchronous programming.
190
+
191
+
A sample code to connect to the PostgreSQL server and fetch the result is shown below,
192
+
193
+
```python linenums="1"
194
+
# import
195
+
import asyncio
196
+
import asyncpg
197
+
198
+
# the main function that connect to the PostgreSQL server,
Creating dynamic queries based on user input can be easily done by passing the variables to the `fetch` function. Below is the modification you need to do. If you notice, we have two variables in the query for `id` and `limit` denoted by `$1` and `$2` respectively. The respective values are passed in the `fetch` function. Rest of the code remains same.
171
220
172
-
## Conclusion
221
+
```python linenums="1"
222
+
# fetch the result
223
+
result =await conn.fetch(
224
+
'SELECT * FROM mytbl where id = $1 LIMIT $2',
225
+
123, 1
226
+
)
227
+
```
173
228
174
-
PostgreSQL's combination of features, performance, and reliability makes it a popular choice for a wide range of applications, from small projects to large-scale enterprise systems. Its open-source nature, strong community support, and continuous development ensure that PostgreSQL will remain a leading database management system for years to come.
229
+
You can use `conn.execute` to run the query without fetching the result. Below is the modification to the code shown above.
175
230
176
-
## References
231
+
```python linenums="1"
232
+
# insertion example (one row)
233
+
result =await conn.execute(
234
+
'INSERT INTO mytbl (code, name) VALUES ($1, $2) where id = $3',
'INSERT INTO mytbl (code, name) VALUES ($1, $2) where id = $3',
245
+
[(123, 'mohit', 1), (124, 'mayank', 2)]
246
+
)
247
+
```
248
+
249
+
You might want to create a generic function to execute queries and retry in case of failure. Here is how you can do it using the `tenacity` library. The below code will retry 3 times if the query fails with exponential backoff.
250
+
251
+
```python linenums="1"
252
+
# import
253
+
import asyncio
254
+
import asyncpg
255
+
import functools
256
+
from tenacity import TryAgain, retry, stop_after_attempt, wait_exponential
257
+
258
+
# custom retry logging function
259
+
defcustom_retry_log(retry_state, msg):
260
+
if retry_state.attempt_number !=1:
261
+
print(f"Retrying {retry_state.attempt_number -1} for {msg}")
If you notice, all of the above examples are executing the query in one transaction. In case you want to execute multiple queries in one transaction, you can do as shown below,
307
+
308
+
```python linenums="1"
309
+
# import
310
+
import asyncio
311
+
import asyncpg
312
+
import functools
313
+
from tenacity import TryAgain, retry, stop_after_attempt, wait_exponential
records =await conn.fetch('SELECT * FROM mytbl where projectid = $1 LIMIT $2', 2, 1)
325
+
326
+
# update the table
327
+
await conn.execute('UPDATE mytbl SET name = $1 where projectid = $2', 'mohit', 2)
328
+
329
+
# handle exception
330
+
exceptExceptionas e:
331
+
# in case of exception rollback the transaction
332
+
await conn.execute('ROLLBACK;')
333
+
334
+
finally:
335
+
# close db connections
336
+
await conn.close()
337
+
```
338
+
339
+
## Snippets
340
+
341
+
Real world problems will require much more than what we covered in the above sections. Lets cover some important queries in this section.
342
+
343
+
**Casting a column to a different data type**
344
+
345
+
```sql
346
+
-- Casting a column to a different data type
347
+
SELECT CAST(salary ASVARCHAR) FROM employees;
348
+
```
349
+
350
+
**Using JSONB column**
351
+
352
+
```sql
353
+
-- Extracting data from JSONB column
354
+
-- Suppose data column contains {"name": "John", "address": {"city": "New York", "state": "NY"}}
355
+
SELECT name, jsonb_extract_path(data, 'address', 'city') AS city FROM employees;
356
+
```
357
+
358
+
**Extracting components from a DateTime column**
359
+
360
+
```sql
361
+
-- Extracting month from DATE column
362
+
-- Suppose in a tbl, order_date col contains info like 2022-01-01
363
+
SELECT DATE_TRUNC('month', order_date) AS month, COUNT(*) AS order_count
364
+
FROM orders
365
+
GROUP BY month
366
+
ORDER BY month;
367
+
368
+
-- Extract year from DATE column, use: DATE_TRUNC('year', order_date)
369
+
-- Extract quarter from DATE column, use: DATE_TRUNC('quarter', order_date)
370
+
-- Extract week from DATE column, use: DATE_TRUNC('week', order_date)
371
+
-- Extract day from DATE column, use: DATE_TRUNC('day', order_date)
372
+
-- Extract hour from DATE column, use: DATE_TRUNC('hour', order_date)
373
+
-- Extract minute from DATE column, use: DATE_TRUNC('minute', order_date)
374
+
-- Extract second from DATE column, use: DATE_TRUNC('second', order_date)
375
+
```
376
+
377
+
## Conclusion
378
+
379
+
PostgreSQL's combination of features, performance, and reliability makes it a popular choice for a wide range of applications, from small projects to large-scale enterprise systems. Its open-source nature, strong community support, and continuous development ensure that PostgreSQL will remain a leading database management system for years to come. Hope this article helped you understand the basics of PostgreSQL and piqued your interest in learning more.
0 commit comments