If you’ve already built a Rails 8 app using the default SQLite setup and now want to switch to PostgreSQL, here’s a clean step-by-step guide to make the transition smooth:
1.🔧 Setup PostgreSQL in macOS
🔷 Step 1: Install PostgreSQL via Homebrew
Run the following:
brew install postgresql
This created a default database cluster for me, check the output. So you can skip the Step 3.
==> Summary
🍺 /opt/homebrew/Cellar/postgresql@14/14.17_1: 3,330 files, 45.9MB
==> Running `brew cleanup postgresql@14`...
==> postgresql@14
This formula has created a default database cluster with:
initdb --locale=C -E UTF-8 /opt/homebrew/var/postgresql@14
To start postgresql@14 now and restart at login:
brew services start postgresql@14
Or, if you don't want/need a background service you can just run:
/opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14
Sometimes Homebrew does this automatically. If not:
initdb /opt/homebrew/var/postgresql@<version>
Or a more general version:
initdb /usr/local/var/postgres
Key functions of initdb: Creates a new database cluster, Initializes the database cluster’s default locale and character set encoding, Runs a vacuum command.
In essence, initdb prepares the environment for a PostgreSQL database to be used and provides a foundation for creating and managing databases within that cluster
🔷 Step 4: Create a User and Database
PostgreSQL uses a role-based access control. Create a user with superuser privileges:
# createuser creates a new Postgres user
createuser -s postgres
createuser is a shell script wrapper around the SQL command CREATE USER via the Postgres interactive terminal psql. Thus, there is nothing special about creating users via this or other methods
Then switch to psql:
psql postgres
You can also create a database:
createdb <db_name>
🔷 Step 5: Connect and Use psql
psql -d <db_name>
Inside the psql shell, try:
\l -- list databases
\dt -- list tables
\q -- quit
Then go to http://localhost:3000 and confirm everything works.
7. Check psql manually (Optional)
psql -d your_app_name_development
Then run:
\dt -- view tables
\q -- quit
8. Update .gitignore
Note: If not already added /storage/*
Make sure SQLite DBs are not accidentally committed:
/storage/*.sqlite3
/storage/*.sqlite3-journal
After moving into PostgreSQL
I was getting an issue with postgres column, where I have the following data in the migration:
# migration
t.decimal :rating, precision: 1, scale: 1
# log
ActiveRecord::RangeError (PG::NumericValueOutOfRange: ERROR: numeric field overflow
12:44:36 web.1 | DETAIL: A field with precision 1, scale 1 must round to an absolute value less than 1.
12:44:36 web.1 | )
Value passed is: 4.3. I was not getting this issue in SqLite DB.
What does precision: 1, scale: 1 mean?
precision: Total number of digits (both left and right of the decimal).
scale: Number of digits after the decimal point
If you want to store ratings like 4.3, 4.5, etc., a good setup is:
t.decimal :rating, precision: 2, scale: 1
# revert and migrate for products table
✗ rails db:migrate:down VERSION=2025031XXXXX -t
✗ rails db:migrate:up VERSION=2025031XXXXXX -t
Then go to http://localhost:3000 and confirm everything works.
For a Ruby on Rails 8 application, the choice of database depends on your specific needs, but here’s a breakdown of the best options and when to use each:
PostgreSQL (Highly Recommended)
Best overall choice for most Rails apps.
Why:
First-class support in Rails.
Advanced features like full-text search, JSONB support, CTEs, window functions.
Strong consistency and reliability.
Scales well vertically and horizontally (with tools like Citus).
Used by: GitHub, Discourse, Basecamp, Shopify.
Use if:
You’re building a standard Rails web app or API.
You need advanced query features or are handling complex data types (e.g., JSON).
SQLite (For development/testing only)
Lightweight, file-based.
Fast and easy to set up.
But not recommended for production.
Use if:
You’re building a quick prototype or local dev/testing app.
NOT for multi-user production environments.
MySQL / MariaDB
Also supported by Rails.
Can work fine for simpler applications.
Lacks some advanced features (like robust JSON support or full Postgres-style indexing).
Not the default in many modern Rails setups.
Use if:
Your team already has MySQL infrastructure or legacy systems.
You need horizontal scaling with Galera Cluster or similar setups.
Others (NoSQL like MongoDB, Redis, etc.)
Use Redis for caching and background job data (not as primary DB).
Use MongoDB or other NoSQL only if your data model really demands it (e.g., unstructured documents, event sourcing).
Recommendation Summary:
Use Case
Recommended DB
Production web/API app
PostgreSQL
Dev/prototyping/local testing
SQLite
Legacy systems/MySQL infrastructure
MySQL/MariaDB
Background jobs/caching
Redis
Special needs (e.g., documents)
MongoDB (with caution)
If you’re starting fresh or building something scalable and modern with Rails 8, go with PostgreSQL.
Let’s break that down:
💬 What does “robust JSON support” mean?
PostgreSQL supports a special column type: json and jsonb, which lets you store structured JSON data directly in your database — like hashes or objects.
Why it matters:
You can store dynamic data without needing to change your schema.
You can query inside the JSON using SQL (->, ->>, @>, etc.).
You can index parts of the JSON — for speed.
🔧 Example:
You have a products table with a specs column that holds tech specs in JSON:
SELECT * FROM products WHERE specs->>'color' = 'black';
Or check if the JSON contains a value:
SELECT * FROM products WHERE specs @> '{"brand": "Libas"}';
You can even indexspecs->>'color' to make these queries fast.
💬 What does “full Postgres-style indexing” mean?
PostgreSQL supports a wide variety of powerful indexing options, which improve query performance and flexibility.
⚙️ Types of Indexes PostgreSQL supports:
Index Type
Use Case
B-Tree
Default; used for most equality and range searches
GIN (Generalized Inverted Index)
Fast indexing for JSON, arrays, full-text search
Partial Indexes
Index only part of the data (e.g., WHERE active = true)
Expression Indexes
Index a function or expression (e.g., LOWER(email))
Covering Indexes (INCLUDE)
Fetch data directly from the index, avoiding table reads
B-Tree Indexes: B-tree indexes are more suitable for single-value columns.
When to Use GIN Indexes: When you frequently search for specific elements within arrays, JSON documents, or other composite data types.
Example for GIN Indexes: Imagine you have a table with a JSONB column containing document metadata. A GIN index on this column would allow you to quickly find all documents that have a specific author or belong to a particular category.
Why does this matter for our shopping app?
We can store and filter products with dynamic specs (e.g., kurtas, shorts, pants) without new columns.
Full-text search on product names/descriptions.
Fast filters: color = 'red' AND brand = 'Libas' even if those are stored in JSON.
Index custom expressions like LOWER(email) for case-insensitive login.
💬 What are Common Table Expressions (CTEs)?
CTEs are temporary result sets you can reference within a SQL query — like defining a mini subquery that makes complex SQL easier to read and write.
WITH recent_orders AS (
SELECT * FROM orders WHERE created_at > NOW() - INTERVAL '7 days'
)
SELECT * FROM recent_orders WHERE total > 100;
Breaking complex queries into readable parts.
Re-using result sets without repeating subqueries.
In Rails (via with from gems like scenic or with_cte):
Window functions perform calculations across rows related to the current row — unlike aggregate functions, they don’t group results into one row.
🔧 Example: Rank users by their score within each team:
SELECT
user_id,
team_id,
score,
RANK() OVER (PARTITION BY team_id ORDER BY score DESC) AS rank
FROM users;
Use cases:
Ranking rows (like leaderboards).
Running totals or moving averages.
Calculating differences between rows (e.g. “How much did this order increase from the last?”).
🛤 In Rails:
Window functions are available through raw SQL or Arel. Here’s a basic example:
User
.select("user_id, team_id, score, RANK() OVER (PARTITION BY team_id ORDER BY score DESC) AS rank")
CTEs and Window functions are fully supported in PostgreSQL, making it the go-to DB for any Rails 8 app that needs advanced querying.
JSONB Support
JSONB stands for “JSON Binary” and is a binary representation of JSON datathat allows for efficient storage and retrieval of complex data structures.
This can be useful when you have data that doesn’t fit neatly into traditional relational database tables, such as nested or variable-length data structures.
Absolutely — storing JSON in a relational database (like PostgreSQL) can be super powerful when used wisely. It gives you schema flexibility without abandoning the structure and power of SQL. Here are real-world use cases for using JSON columns in relational databases:
Here are real-world use cases for using JSON columns in relational databases:
🔧 1. Flexible Metadata / Extra Attributes
Let users store arbitrary attributes that don’t require schema changes every time.
A lightweight version that only declares attribute accessors for keys inside a JSON column. Doesn’t include serialization logic — so you usually use it with a json/jsonb/text column that already works as a Hash.
👉 Example:
class User < ApplicationRecord
store_accessor :settings, :theme, :notifications
end
This gives you:
user.theme, user.theme=
user.notifications, user.notifications=
🤔 When to Use Each?
Feature
When to Use
store
When you need both serialization and accessors
store_accessor
When your column is already serialized (jsonb, etc.)
If you’re using PostgreSQL with jsonb columns — it’s more common to just use store_accessor.
Querying JSON Fields
User.where("settings ->> 'theme' = ?", "dark")
Or if you’re using store_accessor:
User.where(theme: "dark")
💡 But remember: you’ll only be able to query these fields efficiently if you’re using jsonb + proper indexes.
🔥 Conclusion:
PostgreSQL can store, search, and index inside JSON fields natively.
This lets you keep your schema flexible and your queries fast.
Combined with its advanced indexing, it’s ideal for a modern e-commerce app with dynamic product attributes, filtering, and searching.
To install and set up PostgreSQL on macOS, you have a few options. The most common and cleanest method is using Homebrew. Here’s a step-by-step guide:
Ruby on Rails 8 introduces several improvements that make development easier, more secure, and more maintainable. In this guide, we’ll walk through setting up a new Rails 8 application while noting the significant configurations and features that come out of the box.
Rails 8 provides new shortcuts and syntax improvements for database migrations:
NOT NULL Constraints with ! Shortcut
You can impose NOT NULL constraints directly from the command line using !:
# Example for not null constraints:
➜ rails generate model User name:string!
Type Modifiers in Migrations
Rails 8 allows passing commonly used type modifiers directly via the command line. These modifiers are enclosed in curly braces {} after the field type.
# Example for model generation:
➜ rails generate model Product name:string description:text
# Example for passing modifiers:
➜ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
Generating a Scaffold for the Product Model
Let’s generate a complete scaffold for our Product model:
The rails g resource command is a powerful way to generate models, controllers, migrations, and routes all in one go. This is particularly useful when setting up RESTful resources in a Rails application.
Basic Syntax
➜ rails g resource product
This command creates the necessary files for a new resource, including:
A model (app/models/product.rb)
A migration file (db/migrate/)
A controller (app/controllers/product_controller.rb)
Routes in config/routes.rb
A test file (test/controllers/product_controller_test.rb or spec/)
Example Usage
To generate a Post resource with attributes:
➜ rails g resource Product title:string! description:text brand:references
This will:
Create a Product model with title and description attributes.
Add a brand_id foreign key as a reference.
Apply a NOT NULL constraint on title (! shortcut).
Generate a corresponding migration file.
Set up routes automatically (resources :products).
Running the Migration
After generating a resource, apply the migration to update the database:
➜ rails db:migrate
Difference Between resource and scaffold
Rails provides both rails g resource and rails g scaffold, but they serve different purposes:
Feature
rails g resource
rails g scaffold
Generates a Model
✅
✅
Generates a Migration
✅
✅
Generates a Controller
✅ (empty actions)
✅ (full CRUD actions)
Generates Views (HTML/ERB)
❌
✅ (index, show, new, edit, etc.)
Generates Routes
✅
✅
Generates Helper Files
❌
✅
Generates Tests
✅
✅
rails g resource is minimal—it generates only essential files without view templates. It’s useful when you want more control over how your views and controller actions are built.
rails g scaffold is more opinionated and generates full CRUD functionality with prebuilt forms and views, making it ideal for rapid prototyping.
If you need full CRUD functionality quickly, use scaffold. If you prefer a leaner setup with manual control over implementation, use resource.
Conclusion
Rails 8 significantly enhances the development experience with built-in security tools, CI/CD workflows, streamlined deployment via Kamal, and modern front-end support with Turbo & Stimulus. It also improves caching, background jobs, and real-time features with Solid tools.
These improvements make Rails 8 a robust framework for modern web applications, reducing the need for additional dependencies while keeping development efficient and secure.
How does Puma handle multiple HTTP requests? How do threads work and what happens when multiple requests access the database simultaneously?
To understand this properly, we need to understand four concepts:
Processes and threads.
I/O-bound requests.
Database connections and connection pools.
Database locking and concurrent queries.
Let’s start from the beginning.
1. Why Did Rails Move from WEBrick to Puma?
Historically, WEBrick was commonly used as the default Rails development server.
With Rails 5.0, Rails changed its default development server from WEBrick to Puma.
One important reason was the introduction of Action Cable in Rails 5.
Action Cable introduced WebSocket support for real-time features such as chat, notifications and presence. It needed to operate alongside the Rails application in development.
Puma provided a better fit for this concurrent application-server architecture.
Puma provides:
Multithreading: Handles multiple requests using separate threads.
Better concurrency: Allows requests waiting for I/O to overlap.
Copy-on-write memory optimisation when using application preloading.
Production-oriented server capabilities.
One clarification: WEBrick could also create threads for requests. The change wasn’t simply because WEBrick could only process one request at a time. Puma offered a more suitable combination of thread-based and process-based concurrency.
Also, WEBrick’s removal from Ruby’s standard library in Ruby 3.0 was a separate event, not the original reason Rails moved to Puma.
Q) Does puma developed as a ruby library? Or puma has been written in another language and created in ruby as a gem?
Yes! Puma is a Ruby web server, distributed as a Ruby gem, and primarily written in Ruby.
It is not a web server written in another language with a Ruby wrapper.
You install it directly into a Rails application:
# Gemfile
gem "puma"
And start it using:
bundle exec puma
Puma runs inside the Ruby runtime (MRI/CRuby, JRuby, etc.). It uses Ruby’s threading and process capabilities to handle concurrent HTTP requests.
There is one interesting implementation detail: Puma is primarily Ruby, but it also uses native code for performance-critical components.
For example:
Most server logic is implemented in Ruby.
Its HTTP parser is based on Mongrel’s parser, implemented using Ragel and compiled to native C (or Java for certain Ruby implementations).
It uses Ruby’s thread and process APIs to manage concurrent requests.
How does Puma fit into Rails?
HTTP Request
|
v
Puma Server
(Ruby Gem)
|
Rack Interface
|
v
Rails Middleware
|
v
Rails Router
|
v
Controller / Model
|
v
PostgreSQL
Puma is not part of Ruby itself, nor is it part of the Rails framework core. It is an independent Ruby gem that serves Rack applications, including Rails.
Ianswer:
Puma is a Ruby-based, multithreaded and multiprocess HTTP server distributed as a Ruby gem. It implements the Rack interface, allowing it to serve Rails applications. Most of its implementation is Ruby, with native extensions for performance-critical components such as HTTP parsing.
You can also explore its actual source code: Puma GitHub Repository. It’s a useful project to study as a senior Ruby developer.
2. What Is the Difference Between a Process and a Thread?
This is fundamental to understanding Puma.
Process
A process is an independent running instance of an application.
Each process has its own:
Memory space.
Ruby interpreter state.
Global VM Lock (GVL) under MRI Ruby.
Active Record connection pool.
Processes are isolated from one another.
Thread
A thread is an execution unit running inside a process.
Multiple threads within the same process share:
Application memory.
Loaded classes and modules.
Global variables.
Other process-level resources.
However, each thread has its own execution context and can handle a different HTTP request.
Example
Suppose Puma is configured with:
workers 2
threads 3, 3
This means:
2 worker processes.
3 request threads per worker.
Total request-thread capacity:
2 workers × 3 threads = 6 concurrent requests
Conceptually:
Puma Master Process
|
---------------------
| |
Worker 1 Worker 2
Process Process
| |
----------- -----------
| | | | | |
T1 T2 T3 T1 T2 T3
3 threads 3 threads
Total: 6 request threads
A worker is a process, not a thread.
This distinction is extremely important in ints.
3. What Is the Global VM Lock (GVL)?
When using MRI Ruby (the standard CRuby implementation), Ruby has a Global VM Lock.
The GVL ensures that only one thread within a process executes Ruby code at a time.
For example:
Thread.new do
1_000_000.times { |i| i * 2 }
end
Thread.new do
1_000_000.times { |i| i * 2 }
end
Although two threads exist, they cannot execute Ruby bytecode simultaneously within the same MRI process.
Then why do we need multiple threads?
Because not all application work involves executing Ruby code.
A Rails application spends significant time waiting for external operations:
Database queries.
HTTP requests to third-party APIs.
Redis operations.
File and network I/O.
During blocking I/O, Ruby can release the GVL, allowing another thread to execute.
Important distinction:
Threads improve concurrency by overlapping waiting time.
Multiple processes allow MRI Ruby code to execute in parallel across CPU cores.
Puma supports both.
4. What Are I/O-Bound Requests?
An I/O-bound request spends a significant portion of its execution time waiting for an external operation to complete.
Consider this Rails action:
def show
user = User.find(params[:id])
response = HTTParty.get(
"https://api.example.com/profile"
)
render json: {
user: user,
external_profile: response.parsed_response
}
end
Imagine:
Operation
Time
Ruby processing
10 ms
Database query
50 ms
External API request
500 ms
JSON response processing
10 ms
Total
570 ms
The application spends only 20 ms actively processing Ruby code.
The remaining 550 ms is waiting for external operations.
This is an I/O-bound request.
How do Puma threads help?
Imagine three requests arrive simultaneously.
Without useful concurrency, a single execution path might spend time waiting for each external API response.
With Puma:
Thread 1: Ruby code -> Wait for API -> Resume -> Response
Thread 2: Ruby code -> Wait for API -> Resume -> Response
Thread 3: Ruby code -> Wait for API -> Resume -> Response
While Thread 1 waits for its API response, Thread 2 or Thread 3 can execute.
The server uses waiting time more efficiently.
This improves throughput and reduces unnecessary request queuing.
What about CPU-bound requests?
Consider:
def calculate
result = 0
100_000_000.times do |i|
result += i * 2
end
render json: { result: result }
end
This request spends most of its time executing Ruby code.
Increasing Puma threads does not provide true parallel Ruby execution within one MRI process because of the GVL.
For CPU-heavy Ruby workloads, multiple worker processes are more useful because each process has its own GVL.
5. Does Accessing the Database Lock It for Other Requests?
This is an important question.
No. A database connection or a database query does not automatically lock the entire database.
We need to distinguish three different things:
Database connection.
Database connection pool.
Database locks.
They are not the same.
Database connections
A database connection represents a communication session between your Rails process and PostgreSQL.
Multiple connections can exist simultaneously.
For example:
Rails Thread 1 ---- DB Connection 1 ---- PostgreSQL
Rails Thread 2 ---- DB Connection 2 ---- PostgreSQL
Rails Thread 3 ---- DB Connection 3 ---- PostgreSQL
Each connection can execute its own SQL queries.
PostgreSQL is designed to handle concurrent database sessions.
What happens when two requests access the same table?
The pool: 5 setting means that this Active Record connection pool can provide up to five simultaneous database connections.
It doesn’t mean that only five requests can execute in Rails.
It means that only five threads can hold a connection from this particular pool at the same time.
How does the connection pool work?
Suppose three Puma threads receive requests.
Puma Worker Process
|
|
Active Record
Connection Pool
|
---------------------
| | |
DB Conn 1 DB Conn 2 DB Conn 3
| | |
---------------------
|
PostgreSQL
Here’s what happens:
Thread 1 receives a request.
Thread 1 executes an Active Record query.
Active Record checks out a connection from the pool.
The connection executes SQL against PostgreSQL.
The request completes.
Rails returns the acquired connection to the pool.
The connection becomes available to another thread.
The pool creates connections as needed, up to its configured limit.
What happens if all connections are busy?
Suppose:
pool: 2
But three threads simultaneously need database connections.
Thread 1 -> Connection 1 (Busy)
Thread 2 -> Connection 2 (Busy)
Thread 3 -> Waiting for a connection
Thread 3 waits until one of the connections becomes available.
If it cannot obtain a connection before checkout_timeout expires, Rails raises:
ActiveRecord::ConnectionTimeoutError
This is a common production issue when the connection pool is too small for the application’s database workload.
7. How Do Puma Workers and Active Record Connection Pools Work Together?
This is where everything comes together.
Remember that every Puma worker is a separate process.
Each worker process maintains its own Active Record connection pool.
A connection checked out by a thread in Worker 1 cannot be used by a thread in Worker 2.
What if we configure 5 Puma threads but only 2 DB connections?
workers 1
threads 5, 5
pool: 2
Five requests can be in progress, but only two threads can hold database connections simultaneously.
The remaining threads may wait for an available connection.
This can increase response latency and eventually cause connection timeouts.
What should the connection pool size be?
A useful starting rule is:
Set the connection pool at least as large as the maximum number of concurrent threads that need database connections in that process.
For example:
threads 5, 5
A pool size of five is a sensible starting point.
You may need a larger pool when using additional concurrent database consumers, such as asynchronous Active Record query executors.
You don’t always need one database connection for every Puma thread if only some requests access the database. A smaller pool is possible, but it introduces connection-pool contention.
What about Sidekiq?
Sidekiq is another process that can execute multiple jobs concurrently.
Suppose:
# config/sidekiq.yml
:concurrency: 10
If ten Sidekiq threads can execute database operations simultaneously, its Active Record connection pool should generally support at least ten connections per relevant database pool.
Remember:
Puma has its own database pool per worker process.
Sidekiq has its own database pool per process.
Console sessions and other application processes also consume database connections.
Always calculate total possible database connections across the entire application deployment.
A useful formula is:
Total DB connections =
(Puma workers × Puma pool size)
+ (Sidekiq processes × Sidekiq pool size)
+ Other application connections
This total must fit within your database connection capacity, leaving room for administration and other required sessions.
8. How Can We Configure Puma for Better Rails Performance?
Puma configuration mainly involves two important settings:
You can increase the thread count for applications with substantial I/O waiting.
However, don’t blindly increase it.
More threads can increase:
Memory consumption.
GVL contention.
Database connection demand.
External service concurrency.
Rails 7.2 changed its generated Puma thread default from five to three after observing that excessive threading could increase GVL contention and request latency.
B. Configure the number of workers
workers 2
This starts two worker processes.
Each process has its own Ruby execution environment and GVL.
Multiple workers allow MRI Ruby code to execute in parallel on different CPU cores.
However, workers also consume memory and increase the total number of possible database connections.
Don’t blindly set workers equal to the number of available CPUs without considering memory and database capacity.
C. Application preloading
preload_app!
This loads the application before Puma forks its worker processes.
It can reduce memory usage through an operating-system feature called Copy-on-Write (CoW).
When memory pages are shared and neither process modifies them, the operating system can avoid duplicating those pages.
Preloading is useful in clustered deployments, but it has lifecycle implications. In particular, it cannot be combined with Puma’s phased restart feature.
When configuring preloading, follow the connection and background-thread lifecycle requirements of your Puma version and Rails application.
D. What is the best configuration?
There is no universal best configuration.
For a typical I/O-heavy Rails application, start with a modest number of threads and workers, then benchmark.
For example:
workers 2
threads 3, 3
This provides six simultaneous request slots.
Measure:
Request throughput (requests per second).
P95 and P99 response latency.
Worker memory consumption.
CPU utilisation.
Database connection-pool wait time.
Database CPU and query latency.
Increase workers or threads only when measurements show that the current configuration is limiting performance.
9. Putting Everything Together
Let’s consider a real-world example.
A Rails application receives 100 HTTP requests.
Puma is configured with:
workers 2
threads 3, 3
The application can process six requests concurrently across its two worker processes.
The remaining requests wait in the server’s request-handling queue.
Now assume every request needs a database connection.
Each worker has:
pool: 3
Therefore:
Worker 1: 3 concurrent DB connections
Worker 2: 3 concurrent DB connections
Total: 6 possible DB connections
PostgreSQL can execute queries using these independent connections.
If one transaction updates a particular row, another transaction attempting to update the same row may wait for the lock to be released.
Meanwhile, other unrelated queries can continue.
This is how Puma, Active Record and PostgreSQL work together to handle concurrent Rails requests.
10. Common Interview Questions
1. What is the difference between a Puma worker and a thread?
A worker is an independent operating-system process. A thread is an execution unit inside that process. Puma uses both to handle concurrent requests.
2. What are I/O-bound requests?
Requests that spend considerable time waiting for external operations such as database queries, HTTP calls, Redis, or file I/O.
3. Does MRI Ruby support multithreading?
Yes. MRI supports multiple threads, but the GVL prevents multiple threads in the same process from executing Ruby bytecode simultaneously. Threads can still overlap blocking I/O.
4. Why does Puma use multiple processes?
Multiple processes allow Ruby code to execute in parallel across CPU cores despite the MRI GVL. They also provide process isolation.
5. Does every Puma thread need a database connection?
Not necessarily at every moment. However, when multiple threads simultaneously require database connections, each needs its own checked-out connection.
6. What happens when the connection pool is exhausted?
Threads wait for a connection. If one does not become available before the checkout timeout, Rails raises ActiveRecord::ConnectionTimeoutError.
7. Does PostgreSQL lock an entire table when a record is updated?
Not normally. PostgreSQL uses MVCC and row-level locking for conflicting updates. Certain operations, such as some DDL commands, can acquire table-level locks.
8. Why not increase the number of Puma threads to 100?
Too many threads can increase GVL contention, memory usage, database connection requirements and request latency. Thread count must be tuned based on the workload.
9. What is the difference between concurrency and parallelism?
Concurrency means multiple tasks make progress during overlapping periods. Parallelism means multiple tasks execute simultaneously, typically on different CPU cores.
10. How do you troubleshoot Active Record connection-pool exhaustion?
Check the configured pool size, Puma thread count, Sidekiq concurrency, connection checkout wait time, long-running transactions and database connection limits. Increase the pool only after checking total database capacity.
🏁 Final Takeaway
Remember these relationships:
Puma workers = independent processes.
Puma threads = concurrent request execution within each process.
MRI GVL = one thread executes Ruby bytecode at a time per process.
I/O-bound operations = threads can make progress while another thread waits.
Active Record connection pool = manages reusable database connections for threads.
Database connection = a communication session, not a database lock.
PostgreSQL MVCC = allows concurrent access to consistent data snapshots.
users orders
John <-> 100
John <-> 200
Mary <-> 300
Mary <-> 400
Mary <-> 500
Bob X
Alice X
Only matches survive.
Rails Equivalent
User.joins(:orders)
Generated SQL:
SELECT users.*
FROM users
INNERJOIN orders
ON orders.user_id = users.id;
Int. Question
What type of JOIN does Rails joins use?
Answer:
INNER JOIN
Many candidates miss this.
2. LEFT JOIN
Returns:
All rows from LEFT table
+
matching rows from RIGHT table
Query
SELECT
users.name,
orders.amount
FROM users
LEFTJOIN orders
ON users.id = orders.user_id;
Result:
name
amount
John
100
John
200
Mary
300
Mary
400
Mary
500
Bob
NULL
Alice
NULL
Notice:
Bob exists
Alice exists
Even without orders.
Visual
LEFT TABLE = users
Keep everything
John -> order
Mary -> order
Bob -> NULL
Alice -> NULL
Rails Equivalent
User.left_joins(:orders)
Generated SQL:
LEFTOUTERJOIN
Practical Example
Find users without orders.
SELECT users.*
FROM users
LEFTJOIN orders
ON users.id = orders.user_id
WHERE orders.id ISNULL;
Result:
Bob
Alice
Rails:
User.left_joins(:orders)
.where(orders: { id:nil })
Common Int. Question
Find customers who never placed an order.
Expected answer:
LEFTJOIN
+
ISNULL
3. RIGHT JOIN
Opposite of LEFT JOIN.
Keep all rows from right table.
SELECT*
FROM users
RIGHTJOIN orders
ON users.id = orders.user_id;
In real-world Rails projects:
Rarely used
Most engineers rewrite it as LEFT JOIN.
4. FULL OUTER JOIN
Keep everything.
SELECT*
FROM users
FULLOUTERJOIN orders
ON users.id = orders.user_id;
Returns:
All users
+
All orders
matched where possible.
Used occasionally for:
reporting
analytics
reconciliation
Rare in Rails applications.
5. CROSS JOIN
Creates every possible combination.
Example:
CREATETABLE colors (
color VARCHAR(20)
);
INSERTINTO colors
VALUES('Red'),('Blue');
Sizes:
CREATETABLE sizes (
sizeVARCHAR(20)
);
INSERTINTO sizes
VALUES('S'),('M');
Query:
SELECT*
FROM colors
CROSSJOIN sizes;
Result:
Red S
Red M
Blue S
Blue M
Every row paired with every row.
Formula:
RowsA × RowsB
Int. Question:
10 rows × 100 rows
How many rows?
Answer:
1000
6. Self JOIN
A table joins itself.
Very common int. topic.
Create employees:
CREATETABLE employees (
id BIGSERIAL PRIMARYKEY,
name VARCHAR(100),
manager_id BIGINT
);
Insert:
INSERTINTO employees
(name, manager_id)
VALUES
('CEO',NULL),
('Manager1',1),
('Manager2',1),
('Developer1',2),
('Developer2',2);
Query:
SELECT
e.name AS employee,
m.name AS manager
FROM employees e
LEFTJOIN employees m
ON e.manager_id = m.id;
Result:
employee
manager
CEO
NULL
Manager1
CEO
Developer1
Manager1
Rails
classEmployee<ApplicationRecord
belongs_to:manager,
class_name:"Employee",
optional:true
has_many:subordinates,
class_name:"Employee",
foreign_key::manager_id
end
Why Duplicates Occur
Look at:
SELECT*
FROM users
INNERJOIN orders
ON users.id = orders.user_id;
Mary has:
3 orders
Therefore:
Mary appears 3 times
JOINs multiply rows.
This is one of the most misunderstood SQL concepts.
DISTINCT After JOIN
Sometimes we want unique users.
SELECTDISTINCT users.*
FROM users
JOIN orders
ON users.id = orders.user_id;
Rails
User.joins(:orders).distinct
The N+1 Query Problem
Every Rails int. asks this.
Suppose:
users=User.all
users.eachdo |user|
putsuser.orders.count
end
Queries:
SELECT*FROM users;
Then:
SELECT*FROM orders WHERE user_id=1;
SELECT*FROM orders WHERE user_id=2;
SELECT*FROM orders WHERE user_id=3;
...
100 users:
101 queries
Called:
N+1 problem
Fix Using includes
User.includes(:orders)
Rails loads:
SELECT*FROM users;
and
SELECT*FROM orders
WHERE user_id IN(...);
Only 2 queries.
joins vs includes
This is a favorite int. question.
joins
Used for filtering.
User.joins(:orders)
SQL:
INNERJOIN
Purpose:
Filter data
includes
Used for eager loading.
User.includes(:orders)
Purpose:
Avoid N+1
Example
Find users with orders.
User.joins(:orders)
Display users and orders.
User.includes(:orders)
Int. Question
Which is better?
joins
or
includes
Answer:
Depends on the problem.
Different purposes.
Real Int. Queries
Find users with orders
SELECTDISTINCT users.*
FROM users
JOIN orders
ON users.id = orders.user_id;
Rails:
User.joins(:orders).distinct
Find users without orders
SELECT users.*
FROM users
LEFTJOIN orders
ON users.id = orders.user_id
WHERE orders.id ISNULL;
Rails:
User.left_joins(:orders)
.where(orders: { id:nil })
Find total orders per user
SELECT
users.name,
COUNT(orders.id)
FROM users
LEFTJOIN orders
ON users.id = orders.user_id
GROUPBY users.name;
We’ll study GROUP BY in Day 4.
Senior-Level Insights
1. Most Rails JOINs are INNER JOINs
joins
means:
INNERJOIN
2. LEFT JOIN + IS NULL
is the standard pattern for:
Find missing records
Examples:
users without orders
customers without subscriptions
products without inventory
3. JOINs Multiply Rows
One user:
3 orders
becomes:
3 result rows
Always remember this.
4. Understand the Generated SQL
When writing:
User.joins(:orders)
you should mentally see:
INNERJOIN orders
ON orders.user_id = users.id
immediately.
Practical Exercises
Exercise 1
Find all users with orders.
Exercise 2
Find all users without orders.
Exercise 3
Add 3 more orders for John.
Run:
INNERJOIN
Observe duplicates.
Exercise 4
Use:
DISTINCT
to remove duplicates.
Exercise 5
Create:
categories
products
and practice:
INNERJOIN
LEFTJOIN
Homework
Create the following schema:
authors
books
publishers
Relationships:
Author has many Books
Publisher has many Books
Book belongs to Author
Book belongs to Publisher
Insert sample data.
Write queries:
Books with author names
Books with publisher names
Authors without books
Publishers without books
Unique authors who have books
Write both:
SQL
ActiveRecord
Qn) I cannot see any difference in output between left join and full outer join with our example. can u create a new data to see me correct difference between them?
I am working on a project where we face issues in an ancestral path data in PostgreSql DB. Working with hierarchical data in PostgreSQL often involves dealing with ancestry paths stored as delimited strings. This comprehensive guide explores how to extract specific values from ancestry columns and utilize them effectively in join operations, complete with practical examples, troubleshooting tips and how I fixed the issues.
PostgreSQL’s robust string manipulation capabilities make it ideal for handling complex hierarchical data structures. When working with ancestry values stored in text columns, you often need to extract specific parts of the hierarchy for data analysis, reporting, or joining operations.
This article demonstrates how to:
✨ Extract values from ancestry strings using regular expressions
🔗 Perform efficient joins on extracted ancestry data
🛡️ Handle edge cases and avoid common pitfalls
⚡ Optimize queries for better performance
❓ Problem Statement
📊 Scenario
Consider a projects table with an ancestry column containing hierarchical paths like:
Extract the last integer value from the ancestry path
Use this value in a JOIN operation to fetch parent project data
Handle edge cases like NULL values and malformed strings
🏗️ Understanding the Data Structure
📁 Table Structure
CREATE TABLE projects (
id BIGINT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
ancestry TEXT, -- Stores parent hierarchy as "id1/id2/id3"
created_at TIMESTAMP DEFAULT NOW()
);
-- Sample data
INSERT INTO projects (id, name, ancestry) VALUES
(1, 'Root Project', NULL),
(2, 'Department A', '1'),
(3, 'Team Alpha', '1/2'),
(4, 'Task 1', '1/2/3'),
(5, 'Subtask 1A', '1/2/3/4');
🧭 Ancestry Path Breakdown
Project ID
Name
Ancestry
Immediate Parent
1
Root Project
NULL
None (root)
2
Department A
1
1
3
Team Alpha
1/2
2
4
Task 1
1/2/3
3
5
Subtask 1A
1/2/3/4
4
🔧 Solution Overview
🎯 Core Approach
🔍 Pattern Matching: Use regex to identify the last number in the ancestry string
✂️ Value Extraction: Extract the matched value using regexp_replace()
🔄 Type Conversion: Cast the extracted string to the appropriate numeric type
🔗 Join Operation: Use the converted value in JOIN conditions
📝 Basic Query Structure
SELECT projects.*
FROM projects
LEFT OUTER JOIN projects AS parent_project
ON CAST(
regexp_replace(projects.ancestry, '.*\/(\d+)$', '\1')
AS BIGINT
) = parent_project.id
WHERE projects.ancestry IS NOT NULL;
📝 Regular Expression Deep Dive
🎯 Pattern Breakdown: .*\/(\d+)$
Let’s dissect this regex pattern:
.* -- Match any characters (greedy)
\/ -- Match literal forward slash
(\d+) -- Capture group: one or more digits
$ -- End of string anchor
📊 Pattern Matching Examples
Ancestry String
Regex Match
Captured Group
Result
"6/4/5/3"
5/3
3
✅ 3
"1/2"
1/2
2
✅ 2
"9"
No match
–
❌ Original string
"abc/def"
No match
–
❌ Original string
🔧 Alternative Regex Patterns
-- For single-level ancestry (no slashes)
regexp_replace(ancestry, '^(\d+)$', '\1')
-- For extracting first parent instead of last
regexp_replace(ancestry, '^(\d+)\/.*', '\1')
-- For handling mixed delimiters (/ or -)
regexp_replace(ancestry, '.*[\/\-](\d+)$', '\1')
💻 Implementation Examples
🔧 Example 1: Basic Parent Lookup
-- Find each project with its immediate parent information
SELECT
p.id,
p.name AS project_name,
p.ancestry,
parent.id AS parent_id,
parent.name AS parent_name
FROM projects p
LEFT OUTER JOIN projects parent
ON CAST(
regexp_replace(p.ancestry, '.*\/(\d+)$', '\1')
AS BIGINT
) = parent.id
WHERE p.ancestry IS NOT NULL
ORDER BY p.id;
Expected Output:
id | project_name | ancestry | parent_id | parent_name
----+--------------+----------+-----------+-------------
2 | Department A | 1 | 1 | Root Project
3 | Team Alpha | 1/2 | 2 | Department A
4 | Task 1 | 1/2/3 | 3 | Team Alpha
5 | Subtask 1A | 1/2/3/4 | 4 | Task 1
🎯 Example 2: Handling Edge Cases
-- Robust query that handles all edge cases
SELECT
p.id,
p.name AS project_name,
p.ancestry,
CASE
WHEN p.ancestry IS NULL THEN 'Root Level'
WHEN p.ancestry !~ '.*\/(\d+)$' THEN 'Single Parent'
ELSE 'Multi-level'
END AS hierarchy_type,
parent.name AS parent_name
FROM projects p
LEFT OUTER JOIN projects parent ON
CASE
-- Handle multi-level ancestry
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
-- Handle single-level ancestry
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
ELSE NULL
END = parent.id
ORDER BY p.id;
📈 Example 3: Aggregating Child Counts
-- Count children for each project
WITH parent_child_mapping AS (
SELECT
p.id AS child_id,
CASE
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
ELSE NULL
END AS parent_id
FROM projects p
WHERE p.ancestry IS NOT NULL
)
SELECT
p.id,
p.name,
COUNT(pcm.child_id) AS direct_children_count
FROM projects p
LEFT JOIN parent_child_mapping pcm ON p.id = pcm.parent_id
GROUP BY p.id, p.name
ORDER BY direct_children_count DESC;
-- ✅ Correct: Cast only the extracted value
CAST(
regexp_replace(projects.ancestry, '.*\/(\d+)$', '\1')
AS BIGINT
) = parent.id
❌ Error 2: Unexpected Results with Single-Level Ancestry
Problem: Single values like "9" don’t match the pattern .*\/(\d+)$
Solution:
-- ✅ Handle both multi-level and single-level ancestry
CASE
WHEN ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN ancestry ~ '^\d+$' THEN
CAST(ancestry AS BIGINT)
ELSE NULL
END
❌ Error 3: NULL Ancestry Values Causing Issues
Problem: NULL values can cause unexpected behaviour in joins
Solution:
-- ✅ Explicitly handle NULL values
WHERE ancestry IS NOT NULL
AND ancestry != ''
🛡️ Complete Error-Resistant Query
SELECT
p.id,
p.name AS project_name,
p.ancestry,
parent.id AS parent_id,
parent.name AS parent_name
FROM projects p
LEFT OUTER JOIN projects parent ON
CASE
WHEN p.ancestry IS NULL OR p.ancestry = '' THEN NULL
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
ELSE NULL
END = parent.id
ORDER BY p.id;
⚡ Performance Considerations
📊 Indexing Strategies
-- Create index on ancestry for faster pattern matching
CREATE INDEX idx_projects_ancestry ON projects (ancestry);
-- Create partial index for non-null ancestry values
CREATE INDEX idx_projects_ancestry_not_null
ON projects (ancestry)
WHERE ancestry IS NOT NULL;
-- Create functional index for extracted parent IDs
CREATE INDEX idx_projects_parent_id ON projects (
CASE
WHEN ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN ancestry ~ '^\d+$' THEN
CAST(ancestry AS BIGINT)
ELSE NULL
END
) WHERE ancestry IS NOT NULL;
🔄 Query Optimization Tips
🎯 Use CTEs for Complex Logic
WITH parent_lookup AS (
SELECT
id,
CASE
WHEN ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN ancestry ~ '^\d+$' THEN
CAST(ancestry AS BIGINT)
END AS parent_id
FROM projects
WHERE ancestry IS NOT NULL
)
SELECT p.*, parent.name AS parent_name
FROM parent_lookup p
JOIN projects parent ON p.parent_id = parent.id;
⚡ Consider Materialized Views for Frequent Queries
CREATE MATERIALIZED VIEW project_hierarchy AS
SELECT
p.id,
p.name,
p.ancestry,
CASE
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
END AS parent_id
FROM projects p;
-- Refresh when data changes
REFRESH MATERIALIZED VIEW project_hierarchy;
🛠️ Advanced Techniques
🔍 Extracting Multiple Ancestry Levels
-- Extract all ancestry levels as an array
SELECT
id,
name,
ancestry,
string_to_array(ancestry, '/') AS ancestry_array,
-- Get specific levels
split_part(ancestry, '/', 1) AS level_1,
split_part(ancestry, '/', 2) AS level_2,
split_part(ancestry, '/', -1) AS last_level
FROM projects
WHERE ancestry IS NOT NULL;
🧮 Calculating Hierarchy Depth
-- Calculate the depth of each project in the hierarchy
SELECT
id,
name,
ancestry,
CASE
WHEN ancestry IS NULL THEN 0
ELSE array_length(string_to_array(ancestry, '/'), 1)
END AS hierarchy_depth
FROM projects
ORDER BY hierarchy_depth, id;
🌳 Building Complete Hierarchy Paths
-- Recursive CTE to build full hierarchy paths
WITH RECURSIVE hierarchy_path AS (
-- Base case: root projects
SELECT
id,
name,
ancestry,
name AS full_path,
0 AS level
FROM projects
WHERE ancestry IS NULL
UNION ALL
-- Recursive case: child projects
SELECT
p.id,
p.name,
p.ancestry,
hp.full_path || ' → ' || p.name AS full_path,
hp.level + 1 AS level
FROM projects p
JOIN hierarchy_path hp ON
CASE
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
END = hp.id
)
SELECT * FROM hierarchy_path
ORDER BY level, id;
✅ Best Practices
🎯 Data Validation
✅ Validate Ancestry Format on Insert/Update
-- Add constraint to ensure valid ancestry format
ALTER TABLE projects
ADD CONSTRAINT check_ancestry_format
CHECK (
ancestry IS NULL
OR ancestry ~ '^(\d+)(\/\d+)*$'
);
🔍 Regular Data Integrity Checks
-- Find orphaned projects (ancestry points to non-existent parent)
SELECT p.id, p.name, p.ancestry
FROM projects p
WHERE p.ancestry IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM projects parent
WHERE parent.id = CASE
WHEN p.ancestry ~ '.*\/(\d+)$' THEN
CAST(regexp_replace(p.ancestry, '.*\/(\d+)$', '\1') AS BIGINT)
WHEN p.ancestry ~ '^\d+$' THEN
CAST(p.ancestry AS BIGINT)
END
);
🛡️ Error Handling
-- Function to safely extract parent ID
CREATE OR REPLACE FUNCTION extract_parent_id(ancestry_text TEXT)
RETURNS BIGINT AS $$
BEGIN
IF ancestry_text IS NULL OR ancestry_text = '' THEN
RETURN NULL;
END IF;
IF ancestry_text ~ '.*\/(\d+)$' THEN
RETURN CAST(regexp_replace(ancestry_text, '.*\/(\d+)$', '\1') AS BIGINT);
ELSIF ancestry_text ~ '^\d+$' THEN
RETURN CAST(ancestry_text AS BIGINT);
ELSE
RETURN NULL;
END IF;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- Usage
SELECT p.*, parent.name AS parent_name
FROM projects p
LEFT JOIN projects parent ON extract_parent_id(p.ancestry) = parent.id;
📊 Monitoring and Maintenance
-- Query to analyze ancestry data quality
SELECT
'Total Projects' AS metric,
COUNT(*) AS count
FROM projects
UNION ALL
SELECT
'Projects with Ancestry' AS metric,
COUNT(*) AS count
FROM projects
WHERE ancestry IS NOT NULL
UNION ALL
SELECT
'Valid Ancestry Format' AS metric,
COUNT(*) AS count
FROM projects
WHERE ancestry ~ '^(\d+)(\/\d+)*$'
UNION ALL
SELECT
'Orphaned Projects' AS metric,
COUNT(*) AS count
FROM projects p
WHERE p.ancestry IS NOT NULL
AND extract_parent_id(p.ancestry) NOT IN (SELECT id FROM projects);
📝 Conclusion
Working with ancestry data in PostgreSQL requires careful handling of string manipulation, type conversion, and edge cases. By following the techniques outlined in this guide, you can:
🎯 Key Takeaways
🔍 Use robust regex patterns to handle different ancestry formats
🛡️ Always handle edge cases like NULL values and malformed strings
⚡ Consider performance implications and use appropriate indexing
✅ Implement data validation to maintain ancestry integrity
🔧 Create reusable functions for complex extraction logic
💡 Final Recommendations
🎯 Test thoroughly with various ancestry formats
📊 Monitor query performance and optimize as needed
🔄 Consider alternative approaches like ltree for complex hierarchies
📚 Document your ancestry format for team members
🛠️ Implement proper error handling in production code
The techniques demonstrated here provide a solid foundation for working with hierarchical data in PostgreSQL. Whether you’re building organizational charts, category trees, or project hierarchies, these patterns will help you extract and manipulate ancestry data effectively and reliably! 🚀
PostgreSQL, also known as Postgres, is a powerful and feature-rich relational database management system. One of its notable features is the array aggregation function, array_agg, which allows you to aggregate values from multiple rows into a single array. In this blog post, we’ll explore how array_agg works, its applications, and considerations for performance.
How Does array_agg Work?
The array_agg function takes an expression as an argument and returns an array containing the values of that expression for all the rows that match the query. Let’s illustrate this with an example.
Consider a table called employees with columns id, name, and department. Suppose we want to aggregate all the names of employees belonging to the “Sales” department into an array. We can achieve this using the following query:
SELECT array_agg(name) AS sales_employees
FROM employees
WHERE department = 'Sales';
The result of this query will be a single row with a column named sales_employees, which contains an array of all the names of employees in the “Sales” department.
Usage of array_agg with Subqueries
The ability to get an array as the output opens up various possibilities, especially when used in subqueries. You can leverage this feature to aggregate data from related tables or filter results based on complex conditions.
For instance, imagine you have two tables, orders and order_items, where each order can have multiple items. You want to retrieve a list of orders along with an array of item names for each order. The following query achieves this:
SELECT o.order_id, (
SELECT array_agg(oi.item_name)
FROM order_items oi
WHERE oi.order_id = o.order_id
) AS item_names
FROM orders o;
In this example, the subquery within the main query’s select list utilizes array_agg to aggregate item names from the order_items table, specific to each order.
Complex Query Example Using array_agg
To demonstrate a more complex scenario, let’s consider a database that stores books and their authors. We have three tables: books, authors, and book_authors (a join table that associates books with their respective authors).
Suppose we want to retrieve a list of books along with an array of author names for each book by alphabetical order. We can achieve this using a query that involves joins and array_agg:
SELECT b.title, array_agg(a.author_name ORDER BY a.author_name ASC) AS authors
FROM books b
JOIN book_authors ba ON b.book_id = ba.book_id
JOIN authors a ON ba.author_id = a.author_id
GROUP BY b.book_id;
In this query, we join the tables based on their relationships and use array_agg to aggregate author names into an array for each book. The GROUP BY clause ensures that each book’s array of author names is grouped correctly.
Performance Considerations
While array_agg is a powerful function, it’s essential to consider its performance implications, especially when working with large datasets. Aggregating values into arrays can be computationally intensive, and the resulting array can consume significant memory.
If you anticipate working with large result sets or complex queries involving array_agg, it’s worth optimizing your database schema, indexing relevant columns, and analyzing query performance using PostgreSQL’s built-in tools.
Additionally, consider whether array_agg is the most efficient solution for your specific use case. Sometimes, alternative approaches, such as using temporary tables or custom aggregate functions, might offer better performance.
Conclusion
The array_agg function in PostgreSQL provides a powerful mechanism for aggregating values into arrays. It offers flexibility and opens up opportunities for various applications, including subqueries and complex data manipulations. However, when working with large datasets, it’s crucial to be mindful of potential performance implications and explore optimization strategies accordingly.
List of commands to remember using postgres DB managment system.
Login, Create user and password
# login to psql client
psql postgres # OR
psql -U postgres
create database mydb; # create db
create user abhilash with SUPERUSER CREATEDB CREATEROLE encrypted password 'abhilashPass!';
grant all privileges on database mydb to myuser; # add privileges
Connect to DB, List tables and users, functions, views, schema
\l # lists all the databases
\c dbname # connect to db
\dt # show tables
\d table_name # Describe a table
\dn # List available schema
\df # List available functions
\dS [your_table_name] # List triggers
\dv # List available views
\du # lists all user accounts and roles
\du+ # is the extended version which shows even more information.
Show history, save to file, edit using editor, execution time, help
SELECT version(); # version of psql
\g # Execute the previous command
\s # Command history
\s filename # save Command history to a file
\i filename # Execute psql commands from a file
\? # help on psql commands
\h ALTER TABLE # To get help on specific PostgreSQL statement
\timing # Turn on/off query execution time
\e # Edit command in your own editor
\e [function_name] # It is more useful when you edit a function in the editor. Do \df for functions
\o [file_name] # send all next query results to file
\o out.txt
\dt
\o # switch
\dt
Change output, Quit psql
# Switch output options
\a command switches from aligned to non-aligned column output.
\H command formats the output to HTML format.
\q # quit psql
and then copy the *-service.jar into the same folder
You can see these are processing and started in the server logs.
INFO [com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][AutoDeployDir:263] Processing sitesService.api.jar
~/liferay-ce-portal-tomcat-7.3.0-ga1-20200127150653953/liferay-ce-portal-7.3.0-ga1/osgi/modules][BundleStartStopLogger:39] STARTED sitesService.api_1.0.0 [1115]
[com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][AutoDeployDir:263] Processing sitesService.service.jar
~/liferay-ce-portal-tomcat-7.3.0-ga1-20200127150653953/liferay-ce-portal-7.3.0-ga1/osgi/modules][BundleStartStopLogger:39] STARTED sitesService.service_1.0.0 [1116]
Now check the database, if the Site_ table with all columns are created or not
You can see the table and columns are created. In the next topic we discuss about adding services to this service builder.
keep a specified number of backups in storage. After each backup is performed, it will remove older backup package files based on the keep setting.
keep as a Number
If a number has been specified and once the keep limit has been reached, the oldest backup will be removed.
Note that if keep is set to 5, then the 6th backup will be transferred and stored, before the oldest is removed. So be sure you have space available for keep + 1 backups
keep as Time
When a Time object is set to keep it will keep backups until that time. Everything older than the set time will be removed.