Posts

Showing posts with the label Database

Understanding Database Internals with PostgreSQL: From Seq Scan to Index Scan

  When working with databases in real-world systems, one of the most common performance issues is slow queries . Many developers rely on trial-and-error fixes, but understanding how the database actually executes queries is what truly differentiates an average engineer from a strong one. In this article, we’ll walk through key database internals using PostgreSQL — covering execution plans, index usage, and core architectural concepts. Getting Started: What is an Execution Plan? When you run a query, the database doesn’t execute it directly. Instead, it goes through: SQL → Parser → Optimizer → Execution Engine The optimizer decides how to execute your query efficiently. To see this decision, we use: EXPLAIN SELECT * FROM test."Employee"; Sequential Scan (Seq Scan) Example output: Seq Scan on "Employee" (cost=0.00..1736.00 rows=100000 width=27) What does this mean? Seq Scan → Database scans entire table row by row cost → Estimated effort (not actual time) rows ...

Select Nth Highest Salary

  select   min (salary)  from     ( select   distinct  salary  from  emp  order   by  salary  desc )    where  rownum < 3;   In   order   to  calculate the  second  highest salary use rownum < 3   In   order   to  calculate the third highest salary use rownum < 4  

Database Indexing

Image
 Database is divided into logical blocks and each block contains data. CPU works along with RAM. One by one Block loads into the RAM and CPU reads the block if the record is not found then another block will load into the memory. If we need to store 10000 records and 1 block can store 100 records. No. of blocks required = 10000/100->100 blocks. Indexing basically reduces the I/O cost means it reduces the number of blocks that get loaded in the RAM.    Block Size -> 1000 Bytes  Record Size -> 250 Bytes   Total No of records -> 10000   Records in a block -> 1000/250-> 4 records   Total No of blocks required -> 10000/4 -> 2500    Suppose it is taking 1 ms to read 1 block.    In best case it will take -> 1 ms    In worst case, it will be the last record -> 2500 ms   Average Case -> 2500/2 = 1250 (N/2)   If the data is sorted then we can implement binary search. Time Complexi...

Database Selection

Image