# BAD: N+1 query problem
@users = User.all
@users.each do |user|
puts user.posts.count # Fires query for each user!
end
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,
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
package store
import (
"context"
"github.com/jackc/pgx/v5"
package store
import (
"context"
"database/sql"
)
class Tag < ApplicationRecord
has_many :taggings, dependent: :destroy
scope :top, ->(limit = 20) {
joins(:taggings)
.group(Arel.sql("tags.id"))
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."""
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) }
-- ROW_NUMBER: Unique sequential number
SELECT
name,
department,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) as overall_rank,
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()
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,
module ExistenceChecks
extend ActiveSupport::Concern
class_methods do
def has_any?(conditions = {})
relation = conditions.present? ? where(conditions) : all