Posts

Showing posts with the label engineering

Row-level Locks

Image
Introduction Row-level locks are used to protect specific rows when data is being modified. Unlike table locks, Postgres does any row lock storage outside of RAM, writing them directly into the tuples (data rows) on the hard disk to avoid memory overflow. Differences Table-level Lock (8 modes): Protects the table schema and controls broad behaviors, such as full-table reads, table writes, or column alterations. You can imagine these 8 modes as "admission tickets" that control who can enter the building and what they can do inside. Row-level Lock (4 modes): Protects the actual data values inside specific rows to prevent two people from modifying the same record simultaneously. It is like locking individual small rooms inside the building. Connections Although Table-level Lock and Row-level Lock are two distinct sets of lock modes, they always run in parallel and support each other. When you act on a row, Postgres automatically assigns both a table lock and a row lock under...

How Index and B-Tree Index Work

Image
Introduction Index When creating an Index, PostgreSQL creates a separate physical file on the disk. Each index has a Relfilenode which is a unique identifier number. An index does not store the entire information of a row but only contains Index Entries, each entry including: Key: The value of the column you index. TID (Tuple Identifier): A physical pointer consisting of a BlockNumber and an OffsetNumber, used for reference to point to the location of that row in the main table (HEAP). When executing a query, the Query Planner Cost Model in Postgres will calculate to choose between reading data from the index or retrieving it directly from the HEAP (Sequential Scan). {Index Scan Cost} = {Index file reading cost} + {Random block reading cost in the table} {Seq Scan Cost} = {Sequential block reading cost in the table} Because the Index only contains the TID to point to the data in the main table, after loading the index content and finding the necessary values, it must perform random I...