query-optimization

ruby
class AddSettingsToAccounts < ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def change
    add_column :accounts, :settings, :jsonb, null: false, default: {}

Postgres JSONB Partial Index for Feature Flags

rails postgres jsonb
by codesnips 3 tabs
ruby
class ReportQuery
  SQL = <<~SQL.freeze
    SELECT date_trunc('day', events.created_at) AS day,
           count(*) AS total,
           count(*) FILTER (WHERE events.kind = 'purchase') AS purchases
    FROM events

Safe Raw SQL with exec_query + Binds

rails activerecord sql
by codesnips 2 tabs
sql
CREATE TABLE posts (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    author_id    bigint NOT NULL REFERENCES authors (id),
    title        text   NOT NULL,
    body         text   NOT NULL,
    published_at timestamptz NOT NULL DEFAULT now()

Cursor-based pagination with stable ordering

postgres performance pagination
by codesnips 4 tabs
ruby
module ExistenceChecks
  extend ActiveSupport::Concern

  class_methods do
    def has_any?(conditions = {})
      relation = conditions.present? ? where(conditions) : all

Fast “Exists” Checks with select(1) and LIMIT

rails activerecord performance
by codesnips 4 tabs
sql
-- Basic query debugging with EXPLAIN
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';

-- Output shows query plan:
-- Seq Scan on users (cost=0.00..25.00 rows=1 width=100)
--   Filter: (email = 'test@example.com'::text)

Query debugging and troubleshooting techniques

postgresql debugging troubleshooting
by Maria Garcia 2 tabs
typescript
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function getFeedNaive(limit = 20) {
  const posts = await prisma.post.findMany({

Prisma: avoid N+1 with include/select

prisma performance typescript
by codesnips 3 tabs
sql
-- INNER JOIN: Only matching rows
SELECT
  users.name,
  orders.order_number,
  orders.total
FROM users

Advanced SQL joins and query optimization

sql joins query-optimization
by Maria Garcia 2 tabs
ruby
# In rails console
query = Post.joins(:author)
           .where(published_at: 1.week.ago..Time.current)
           .where(users: { status: 'active' })
           .order(created_at: :desc)

Database query explain analysis for optimization

rails postgresql performance
by Alex Kumar 2 tabs
sql
-- Basic EXPLAIN
EXPLAIN
SELECT * FROM users WHERE email = 'alice@example.com';

-- EXPLAIN with cost and row estimates
-- Output shows: Seq Scan on users (cost=0.00..15.50 rows=1 width=100)

EXPLAIN and query plan optimization

sql explain query-optimization
by Maria Garcia 2 tabs
sql
CREATE TABLE subscriptions (
    id                  BIGGENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id         BIGINT       NOT NULL,
    plan_code           TEXT         NOT NULL,
    status              TEXT         NOT NULL DEFAULT 'active',
    current_period_end  TIMESTAMPTZ  NOT NULL,

Partial index for “active” rows in Postgres

postgres performance sql
by codesnips 3 tabs