sql

ruby
# BAD: N+1 query problem
@users = User.all
@users.each do |user|
  puts user.posts.count  # Fires query for each user!
end

ActiveRecord query optimization and N+1 prevention

ruby rails activerecord
by Sarah Mitchell 3 tabs
ruby
class CreateTopSellersMv < ActiveRecord::Migration[7.0]
  def up
    execute <<~SQL
      CREATE MATERIALIZED VIEW top_sellers AS
        SELECT p.id            AS product_id,
               p.name          AS product_name,

Cache-Friendly “Top N” with Materialized View Refresh

rails postgres performance
by codesnips 4 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
go
package store

import (
  "context"

  "github.com/jackc/pgx/v5"

Postgres transaction pattern with pgx: defer rollback, commit explicitly

go postgres pgx
by Leah Thompson 1 tab
go
package store

import (
  "context"
  "database/sql"
)

sqlc transaction wrapper that keeps call sites clean

go sql postgres
by Leah Thompson 1 tab
ruby
class Tag < ApplicationRecord
  has_many :taggings, dependent: :destroy

  scope :top, ->(limit = 20) {
    joins(:taggings)
      .group(Arel.sql("tags.id"))

Memory-Safe “top tags” aggregation with pluck + group

rails activerecord performance
by codesnips 3 tabs
python
from django.db import connection
from blog.models import Post


def get_top_authors(limit=10):
    """Get authors with most published posts using raw SQL."""

Django raw SQL queries for complex operations

django python database
by Priya Sharma 1 tab
ruby
class Document < ApplicationRecord
  belongs_to :owner, class_name: "User"
  has_many :visibilities, class_name: "DocumentVisibility", dependent: :delete_all

  scope :public_documents, -> { where(is_public: true) }

Polymorphic “Visible To” Scope with Arel

rails activerecord arel
by codesnips 3 tabs
sql
-- ROW_NUMBER: Unique sequential number
SELECT
  name,
  department,
  salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) as overall_rank,

Window functions for advanced analytics

sql window-functions analytics
by Maria Garcia 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
sql
WITH ordered_events AS (
  SELECT
    customer_id,
    event_time,
    revenue,
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_time DESC) AS event_rank,

SQL window functions for feature extraction and behavioral ranking

sql window-functions feature-engineering
by Dr. Elena Vasquez 1 tab
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