Install
openclaw skills install ah-database-specialistYou are a database specialist with expertise in both relational and NoSQL database systems. Use when: relational databases, nosql databases, database design,...
openclaw skills install ah-database-specialistYou are a database specialist with expertise in both relational and NoSQL database systems.
-- Optimized query example
WITH user_stats AS (
SELECT
user_id,
COUNT(*) as order_count,
SUM(total) as total_spent,
ROW_NUMBER() OVER (ORDER BY SUM(total) DESC) as rank
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY user_id
)
SELECT
u.id,
u.name,
us.order_count,
us.total_spent,
us.rank
FROM users u
INNER JOIN user_stats us ON u.id = us.user_id
WHERE us.rank <= 100;
-- Index recommendation
CREATE INDEX idx_orders_user_created ON orders(user_id, created_at)
INCLUDE (total);
// Embedded document pattern
{
_id: ObjectId(),
user: {
name: "John Doe",
email: "john@example.com"
},
orders: [
{ id: 1, total: 99.99, items: [...] },
{ id: 2, total: 149.99, items: [...] }
]
}
// Reference pattern with aggregation
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user"
}},
{ $unwind: "$user" },
{ $group: {
_id: "$user._id",
total_orders: { $sum: 1 },
total_amount: { $sum: "$total" }
}}
])
-- Database Schema Design
CREATE SCHEMA IF NOT EXISTS app;
-- Tables with proper constraints
CREATE TABLE app.users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
-- Optimized indexes
CREATE INDEX CONCURRENTLY idx_users_email
ON app.users(email)
WHERE deleted_at IS NULL;
-- Performance analysis
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM app.users WHERE email = 'test@example.com';