sql

ruby
class Article < ApplicationRecord
  scope :ranked, -> { order(score: :desc, id: :desc) }

  scope :after_cursor, ->(cursor) do
    return all if cursor.nil?

Deterministic Sorting with Secondary Key

rails activerecord pagination
by codesnips 4 tabs
sql
-- Product.active.touch_all(:cache_synced_at) for catalog 42
UPDATE "products"
SET "updated_at" = '2024-05-01 12:00:00.123456',
    "cache_synced_at" = '2024-05-01 12:00:00.123456'
WHERE "products"."catalog_id" = 42
  AND "products"."status" = 'active';

Use `touch_all` for Efficient “Bump Updated At”

rails activerecord performance
by codesnips 4 tabs
ruby
module KeysetPageable
  extend ActiveSupport::Concern

  included do
    scope :keyset_page, ->(cursor: nil, per: 20) do
      per = per.to_i.clamp(1, 100)

Safe Pagination with Keyset (No OFFSET)

rails activerecord performance
by codesnips 3 tabs
sql
ALTER TABLE documents ADD COLUMN version BIGINT NOT NULL DEFAULT 0;

Optimistic locking with a version column

go postgres sql
by Leah Thompson 2 tabs
sql
-- Basic CTE
WITH high_value_customers AS (
  SELECT
    user_id,
    SUM(total) as lifetime_value
  FROM orders

Common Table Expressions (CTEs) for readable queries

sql cte common-table-expressions
by Maria Garcia 2 tabs
sql
CREATE TABLE daily_events (
    id          BIGSERIAL PRIMARY KEY,
    category    TEXT        NOT NULL,
    item_id     BIGINT      NOT NULL,
    score       NUMERIC(10,2) NOT NULL DEFAULT 0,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()

Database-Driven “Daily Top” with window functions

postgres sql analytics
by codesnips 3 tabs
ruby
class UserSearchQuery
  def initialize(relation = User.all)
    @relation = relation
  end

  def call(params)

Query objects for complex database queries

ruby rails query-objects
by Sarah Mitchell 2 tabs
sql
CREATE TABLE daily_metrics (
    id          BIGGENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tenant_id   BIGINT      NOT NULL,
    metric      TEXT        NOT NULL,
    day         DATE        NOT NULL,
    count       BIGINT      NOT NULL DEFAULT 0,

SQL upsert for counters (ON CONFLICT DO UPDATE)

postgres sql concurrency
by codesnips 3 tabs
go
package paging

import (
  "encoding/base64"
  "encoding/json"
  "time"

Cursor pagination: opaque tokens with stable ordering

go api pagination
by Leah Thompson 1 tab
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
sql
CREATE TABLE idempotency_keys (
    request_key         text        NOT NULL,
    endpoint            text        NOT NULL,
    request_fingerprint text        NOT NULL,
    status              text        NOT NULL DEFAULT 'in_progress'
                                    CHECK (status IN ('in_progress', 'completed')),

Idempotency keys for “create” endpoints

reliability postgres idempotency
by codesnips 3 tabs
rust
use sqlx::PgPool;

#[derive(sqlx::FromRow)]
struct User {
    id: i32,
    name: String,

sqlx for compile-time checked SQL queries with async

rust database sql
by Marcus Chen 1 tab