今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

标签:#SQL

找到 81 篇相关文章

AI 资讯

SQLite Internals: lcd-ex vs hctree; PostgreSQL 19 SQL/PGQ Rewrites & pg_timetable Migration

SQLite Internals: lcd-ex vs hctree; PostgreSQL 19 SQL/PGQ Rewrites & pg_timetable Migration Today's Highlights This week's highlights feature a deep dive into SQLite's internal data structures, offering insights for advanced optimization. Also, PostgreSQL users gain practical guidance on migrating to pg_timetable for robust job scheduling and understanding how SQL/PGQ translates to efficient joins in PostgreSQL 19. Replacing pgAgent with pg_timetable: Installing as a Linux Service (Planet PostgreSQL) Source: https://postgr.es/p/9pE Regina Obe presents a crucial guide for PostgreSQL administrators looking to modernize their task automation by replacing pgAgent with pg_timetable . This second part of the series focuses specifically on the practical steps of installing and configuring pg_timetable as a systemd service on Linux, ensuring it runs reliably in a production environment. The article details the process from downloading binaries and creating dedicated user accounts to setting up service files and enabling autostart, providing a comprehensive walkthrough for seamless integration. pg_timetable offers significant advantages over pgAgent , including advanced scheduling capabilities, event-driven task execution, parallel job processing, and improved logging. This migration strategy is vital for enhancing the robustness and efficiency of database maintenance, data synchronization, and complex ETL pipelines within the PostgreSQL ecosystem. By following this guide, developers and DBAs can transition to a more powerful and flexible job scheduler, leading to greater control and reliability over their automated PostgreSQL operations. Comment: Migrating to pg_timetable from pgAgent is a significant step forward for job scheduling in PostgreSQL. This guide provides the hands-on steps needed to get it running as a service, which is essential for any production deployment. SQLite Forum Discusses lcd-ex vs hctree (SQLite Forum) Source: https://sqlite.org/forum/info/3494bff42

2026-07-15 原文 →
AI 资讯

🚀 How I Optimize Slow MySQL Queries in Laravel: My Practical Checklist

One of the most common questions I hear is: "My API is slow. Where do I start?" The first instinct is usually: Upgrade the server Increase CPU Add more RAM But in many cases, the database query is the real bottleneck . Whenever I investigate a slow Laravel application, I follow the same checklist. It helps me identify performance issues before making unnecessary infrastructure changes. Let's go through it. 1️⃣ Find the Slow Queries First Don't start optimizing random queries. Start with the queries that are executed the most or take the most time. Useful tools: Laravel Telescope Laravel Debugbar (development) MySQL Slow Query Log Application Performance Monitoring (APM) You can't optimize what you haven't measured. 2️⃣ Stop Using SELECT * One of the easiest improvements. ❌ Instead of: SELECT * FROM users WHERE id = 10 ; Use: SELECT id , name , email FROM users WHERE id = 10 ; Why? Less data transferred Lower memory usage Faster response Easier for MySQL to use covering indexes Only fetch the columns your application actually needs. 3️⃣ Always Check the Execution Plan Before changing anything, run: EXPLAIN SELECT id , name FROM users WHERE email = 'john@example.com' ; Things I usually look for: Is MySQL scanning the whole table? Is an index being used? How many rows are examined? Is there a temporary table? Is filesort being used? EXPLAIN often tells you exactly why a query is slow. 4️⃣ Verify Your Indexes Indexes are one of the biggest performance improvements you can make—but only when they match your queries. Example: SELECT * FROM orders WHERE customer_id = 100 ; Create an index: CREATE INDEX idx_customer_id ON orders ( customer_id ); Now MySQL can jump directly to the matching rows instead of scanning the entire table. 5️⃣ Look for Composite Index Opportunities Suppose your query is: SELECT id , total FROM orders WHERE customer_id = 10 AND status = 'paid' ; Instead of two separate indexes: customer_id status A composite index is often better: CREATE INDEX idx_cu

2026-07-14 原文 →
AI 资讯

DuckDB Iceberg MERGE, PostgreSQL GUCs, SQLite Optimization Checklist

DuckDB Iceberg MERGE, PostgreSQL GUCs, SQLite Optimization Checklist Today's Highlights This week's highlights include powerful new Iceberg data manipulation features in DuckDB v1.5.3 and a deep dive into an obscure PostgreSQL GUC. Plus, the SQLite community discusses a practical optimization checklist for embedded databases. New DuckDB-Iceberg Features in v1.5.3 (DuckDB Blog) Source: https://duckdb.org/2026/05/29/new-iceberg-features.html The latest DuckDB v1.5.3 release significantly enhances its integration with Apache Iceberg, introducing a suite of powerful new features for data engineers and analysts. Key among these are the support for MERGE INTO and ALTER TABLE statements, allowing for more robust data manipulation directly within DuckDB for Iceberg tables. This update enables complex operations like upserting data based on conditions, schema evolution (e.g., adding/dropping columns), and modifying table properties, all achievable through a familiar SQL environment. This capability is crucial for maintaining data integrity and adapting schemas without complex external tooling. Furthermore, DuckDB-Iceberg now supports partition transforms, making it easier to manage and query partitioned Iceberg datasets efficiently by defining how data is distributed across files. The release also brings support for Iceberg V3, ensuring compatibility with the latest features of the Iceberg format, including new manifest list and manifest file layouts which offer performance improvements. These additions position DuckDB as an even stronger tool for building performant data pipelines and performing complex analytics directly on large-scale Iceberg data lakes, fully leveraging DuckDB's in-process analytical capabilities and the flexibility of the Iceberg table format. Comment: This update is a game-changer for working with Iceberg tables directly in DuckDB. MERGE INTO support means simplified ETL for incremental loads, and V3 compatibility ensures we're ready for future Iceberg

2026-07-14 原文 →
AI 资讯

SQL: Data Constraints

Introdução Validar dados é uma responsabilidade que pode ficar na aplicação, no banco de dados, ou em ambos. Deixar tudo na aplicação é arriscado: diferentes sistemas podem acessar o mesmo banco, migrações podem rodar diretamente, um bug pode deixar passar um valor inválido. Constraints são regras definidas no próprio banco de dados — uma camada de proteção que age independente de quem está escrevendo os dados. PRIMARY KEY A chave primária identifica cada linha de forma única. Ela combina duas restrições implicitamente: NOT NULL e UNIQUE . Nenhuma linha pode ter o mesmo valor de chave primária, e nenhuma pode tê-la nula. CREATE TABLE clientes ( id INT PRIMARY KEY , nome VARCHAR ( 100 ) NOT NULL ); Quando a chave primária envolve mais de uma coluna, ela é declarada separadamente: CREATE TABLE matriculas ( aluno_id INT , curso_id INT , PRIMARY KEY ( aluno_id , curso_id ) ); Na maioria dos bancos, é comum usar uma chave primária auto-incremental para não precisar gerenciar os IDs manualmente: -- PostgreSQL id SERIAL PRIMARY KEY -- MySQL id INT AUTO_INCREMENTPRIMARY KEY -- SQL padrão (suportado por ambos) id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY FOREIGN KEY A chave estrangeira garante integridade referencial : um valor só pode existir numa coluna se ele existir como chave primária na tabela referenciada. É o que torna os relacionamentos entre tabelas confiáveis. CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_idINT REFERENCES clientes ( id ) ); Tentar inserir um pedido com cliente_id = 99 quando não existe cliente com esse id resulta em erro imediato. O banco rejeita a operação antes mesmo de ela chegar ao disco. O comportamento quando o registro referenciado é deletado pode ser configurado: CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_id INT REFERENCES clientes ( id ) ON DELETE CASCADE -- deleta os pedidos junto com o cliente ON UPDATE CASCADE -- atualiza o cliente_id se o id do cliente mudar ); As opções disponíveis são: Opção Comportamento RESTRICT

2026-07-13 原文 →
AI 资讯

SQL: Aggregate Queries

Introdução Consultas individuais respondem perguntas como "qual o email do cliente 42?". Mas as perguntas mais valiosas em qualquer sistema são de outro tipo: "qual o produto mais vendido?", "qual a receita média por pedido?", "quantos clientes se cadastraram esse mês?". Para responder isso, o SQL oferece as funções de agregação — operações que recebem um conjunto de linhas e devolvem um único valor resumido. Para os exemplos a seguir, considere esta tabela: pedidos: | id | cliente | produto | categoria | quantidade | valor | |----|------------|-------------|--------------|------------|--------| | 1 | Ana Lima | Notebook | Eletrônicos | 1 | 3500.00| | 2 | Ana Lima | Mouse | Periféricos | 2 | 80.00| | 3 | Bruno Melo | Teclado | Periféricos | 1 | 150.00| | 4 | Bruno Melo | Notebook | Eletrônicos | 1 | 3500.00| | 5 | Carla Nunes| Monitor | Eletrônicos | 2 | 1200.00| | 6 | Carla Nunes| Mouse | Periféricos | 1 | 80.00| As Funções de Agregação COUNT Conta o número de linhas — ou de valores não nulos em uma coluna específica. -- Total de pedidos SELECT COUNT ( * ) AS total_pedidosFROM pedidos ; -- Resultado: 6 -- Clientes distintos que fizeram pedidos SELECT COUNT ( DISTINCT cliente ) AS clientes_unicosFROM pedidos ; -- Resultado: 3 COUNT(*) conta todas as linhas, incluindo as que têm nulos. COUNT(coluna) conta apenas as linhas onde aquela coluna não é nula. COUNT(DISTINCT coluna) conta valores únicos — útil para saber quantos clientes, produtos ou categorias distintos aparecem no resultado. SUM Soma os valores de uma coluna numérica. -- Receita total SELECT SUM ( valor ) AS receita_total FROM pedidos ; -- Resultado: 8510.00 -- Total de itens vendidos SELECT SUM ( quantidade ) AS itens_vendidos FROM pedidos ; -- Resultado: 8 AVG Calcula a média aritmética dos valores. -- Valor médio por pedido SELECT AVG ( valor ) AS ticket_medio FROM pedidos ; -- Resultado: 1418.33 AVG ignora valores nulos automaticamente — calcula a média apenas sobre os registros que têm valor preenchid

2026-07-13 原文 →
AI 资讯

Mi INSERT tardaba 25 minutos y no era culpa de los datos: construyendo un Data Warehouse de e-commerce con PostgreSQL

Cargar 112.647 filas en una tabla de hechos debería tardar segundos. A mí me tardaba más de 25 minutos, y acababa cancelando la query. Los datos estaban bien, el SQL estaba bien, las dimensiones se poblaban sin problema. El culpable era otro, y descubrirlo fue la parte más instructiva de todo el proyecto. Todo esto surgió construyendo un Data Warehouse en estrella sobre datos reales de e-commerce: no una tabla bonita para hacer un SELECT * , sino un modelo dimensional completo, reproducible desde cero, capaz de responder preguntas de negocio de verdad. El dataset Trabajé con el Brazilian E-Commerce Public Dataset by Olist : pedidos reales de un marketplace brasileño entre septiembre de 2016 y octubre de 2018. Son 9 CSV relacionados entre sí: 99.441 pedidos y 112.650 líneas de venta 103.886 pagos y 104.719 reseñas 32.951 productos, 3.095 vendedores 1.000.163 registros de geolocalización Y con trampas de datos reales que hay que ver antes de que te muerdan: Un pedido puede tener varios pagos y varias reseñas. Si los unes tal cual a la tabla de hechos, duplicas ventas . Es el error clásico y silencioso: los totales salen inflados y nadie se entera. customer_id no es un cliente. Olist crea uno por cada pedido; la persona real es customer_unique_id . Contar mal aquí te cambia el KPI: hay 99.441 cuentas frente a 96.096 personas. El CSV de productos trae una errata en la cabecera ( product_name_lenght , con "lenght"). Si tu esquema la escribe bien y cargas por interfaz gráfica (que empareja por nombre ), esas columnas se quedan vacías sin que nadie avise. El proceso Monté una arquitectura en capas: CSV → staging → modelo dimensional → vistas → análisis , todo en cuatro scripts ejecutables en orden y idempotentes (el esquema se recrea desde cero, se puede relanzar mil veces). El modelo es un star schema : una tabla de hechos fact_sales al grano de línea de producto dentro de un pedido , y cinco dimensiones (cliente, producto, vendedor, pago y fecha), con claves sustitutas,

2026-07-13 原文 →
AI 资讯

Losing PostgreSQL Gains? Blame Inline JSONB!!

Losing PostgreSQL Gains? Blame Inline JSONB!! PostgreSQL's jsonb is a favorite among developers for its flexibility - but it hides a dark side. When used carelessly, especially in-line within rows under 2KB, it can silently destroy performance, even if you're using indexes. Here's why. 🔍 The Hidden Cost of JSONB (Inline Storage) PostgreSQL stores table rows in 8KB pages, packing as many tuples as possible. For a typical row with 10–12 columns, and small text/integers, 40–100 rows can easily fit per page. Typically row count = Page Size(8kb) / row size + row metadata (30-50 bytes approx.) But the game changes when you add jsonb. Example CREATE TABLE events ( id serial PRIMARY KEY, user_id int, action text, metadata jsonb ); Suppose metadata which is a jsonb column contains: { "ip": "127.0.0.1", "device": "Android", "country": "IN" } This JSON might be just 100–500 bytes, so PostgreSQL stores it in-line inside the same page (no TOASTing). Result Each row size jumps from ~80 bytes → ~200–400 bytes Row count per page drops from 100 → 20–40 Index scan still needs to read each page for matching rows More pages = more I/O, slower performance 🔢 Real Benchmark Insight Performance comparisonEven with a GIN or B-tree index on the JSONB column, PostgreSQL still needs to scan all matching pages to retrieve the full tuple. 🧠 Why Index Doesn't Save You Say you index a JSONB key like: CREATE INDEX ON events ((metadata->>'ip')); And query: SELECT * FROM events WHERE metadata->>'ip' = '127.0.0.1'; PostgreSQL will: Use the index to find matching tuples Still need to fetch the row from disk Because JSONB is in-line, many pages are touched More page fetches = more IO = slower queries 🩹 What You Can Do ✅ Force TOAST: Add padding to make JSONB exceed 2KB: UPDATE events SET metadata = metadata || jsonb_build_object('padding', repeat('x', 2000)); ✅ Split into separate table: If JSONB is rarely queried ✅ Stick to well defined schema and avoid using jsonb unless absolutely necessary. 🧾 TL;DR

2026-07-12 原文 →
AI 资讯

Your Postgres Is Quietly Rotting — Here Are the Queries That Show It

It's Friday evening. An endpoint that normally answers in 200 milliseconds is suddenly taking eight seconds. You open Grafana. Every graph is green. CPU is calm, memory is fine, the disk isn't full. By every dashboard you have, the database is healthy. It is not healthy. This is the failure mode monitoring is worst at: the server is unmistakably alive , so nothing alerts, while inside the database something is slowly rotting. A table has bloated. An index nobody uses is dragging down every INSERT . A forgotten transaction is sitting open, holding a lock and quietly making everything worse. None of it crashes. It just degrades, a little at a time, until one Friday evening it tips over. The good news is that Postgres will tell you all of this — you just have to ask. The queries below run on bare PostgreSQL (13 or newer; one version note along the way), need no agent and no paid monitoring, and use an extension in exactly one place where it genuinely earns it. Open psql and check your own database as you read. 1. The cheapest signal: dead rows Start here, because it costs nothing and catches the most. Postgres never deletes a row in place. An UPDATE or DELETE leaves behind a dead tuple — an old version of the row — and autovacuum cleans those up later. Until it does (or if it can't keep up), the dead rows sit in the table, taking space and forcing every scan to page past them. The fastest look is pg_stat_user_tables , always available, no extension: SELECT schemaname , relname AS table , n_live_tup , n_dead_tup , round ( n_dead_tup * 100 . 0 / nullif ( n_live_tup + n_dead_tup , 0 ), 1 ) AS dead_ratio , last_autovacuum FROM pg_stat_user_tables WHERE n_dead_tup > 0 ORDER BY n_dead_tup DESC LIMIT 20 ; A dead_ratio above ~20% on a large table is worth investigating. And watch for a table where the ratio is high and last_autovacuum is empty — that means autovacuum has never successfully run on it, which is its own red flag (we'll see why in section 5; the whole story conver

2026-07-10 原文 →
AI 资讯

Cómo hablar con tu base de datos usando IA y construir un extractor SQL seguro con Streamlit

Abstract Cada vez más equipos quieren consultar datos sin escribir SQL a mano. El problema es que un sistema Text-to-SQL no solo debe “traducir preguntas”, sino también entender el esquema, restringir permisos, validar consultas y explicar por qué una consulta es rápida o lenta. Ese enfoque coincide con la ruta propuesta por el tutorial oficial de LangChain para agentes SQL: listar tablas, inspeccionar esquemas, generar la consulta, revisarla, ejecutarla y corregir errores hasta obtener una respuesta; y el propio tutorial advierte que ejecutar SQL generado por modelos tiene riesgos y exige permisos mínimos. En paralelo, la documentación oficial de Python recomienda usar placeholders en sqlite3 para enlazar parámetros y evitar inyección SQL, mientras que la documentación de SQLite explica que EXPLAIN QUERY PLAN permite inspeccionar si una consulta hace SCAN, SEARCH y si usa índices. manueldongo23 / sql_ai_sales_assistant_demo SQL AI Sales Assistant A safe Text-to-SQL demo that converts natural language business questions into SQL queries, executes them on a local SQLite retail database, and shows the generated SQL plus EXPLAIN QUERY PLAN . This project was created as evidence for an article about SQL AI Database Solutions . Topic Talk to your database with AI: build a safe SQL query extractor with Streamlit and SQLite. Features Natural language prompts such as sales by month , top customers , sales in Lima . Rule-assisted NL→SQL generation, designed to be transparent and auditable. SQLite demo database with customers, products, orders and order items. Read-only SQL validator that blocks destructive commands. Parameterized queries for user-provided filters. Streamlit interface. CLI demo for quick testing. Query plan inspection with EXPLAIN QUERY PLAN . Architecture User question ↓ NL → SQL interpreter ↓ Read-only SQL validator ↓ SQLite execution ↓ Results + EXPLAIN QUERY … View on GitHub Cuerpo del artículo La promesa de SQL + IA suena sencilla: le haces una pregunta

2026-07-06 原文 →
AI 资讯

PostgreSQL query planner parameters and prepared statements

PostgreSQL provides several planner configuration parameters, such as enable_seqscan and enable_indexscan , that influence how execution plans are generated. These settings affect planning, not the execution of an already-generated plan. With prepared statements, this raises an interesting question. Should planner settings be applied before PREPARE, before EXECUTE, or both? Let's look at a simple example: a "tasks" table with a due date and a "done" status: \ c drop table if exists tasks ; -- a table of tasks with status (done or not) and due date create table tasks ( id bigint generated always as identity primary key , due timestamptz , done boolean ); -- insert 500 tasks, with 1% not done insert into tasks ( due , done ) select now () + interval '1 day' * n , 42 != n % 100 from generate_series ( 1 , 500 ) n ; -- index the todo (partial index) create index on tasks ( due , id ) where done = false ; vacuum analyze tasks ; With a partial index, I indexed only the tasks that are not yet done ( done = false ) because that's my most frequent query pattern: postgres =# explain select id , due , done from tasks where done = false and id > 0 order by due limit 1 ; QUERY PLAN --------------------------------------------------------------------------------------- Limit ( cost = 0 . 13 .. 3 . 60 rows = 1 width = 17 ) -> Index Scan using tasks_due_id_idx1 on tasks ( cost = 0 . 13 .. 17 . 47 rows = 5 width = 17 ) Index Cond : ( id > 0 ) ( 3 rows ) With partial indexes, the condition covered by the index is not even visible in the execution plan because the index itself enforces the condition. Prepared statement I decided to use a prepared statement with all values as parameters. It is probably not a good idea in this case. When a parameter can have only a few different values and you expect different cardinalities for each, you should probably define one query per value, using literals. I'm doing this to illustrate what can happen, with a simple, extreme example: postgres =# pr

2026-07-06 原文 →
开发者

SQLite Internals, Postgres 19 Checksums, & PL/CBMBASIC Extension

SQLite Internals, Postgres 19 Checksums, & PL/CBMBASIC Extension Today's Highlights This week, we delve into SQLite's secure deletion and blob updates, explore upcoming data integrity features in PostgreSQL 19, and discover a unique PostgreSQL extension bringing Commodore 64 BASIC to your database. These updates offer insights into database internals, future resilience, and creative extensibility for the SQLite ecosystem. Secure Delete and BLOB Updates in SQLite (SQLite Forum) Source: https://sqlite.org/forum/info/6f3e886a1149c97e0ede9a243281efb05a043705393ea94437ed7c0556315972 This SQLite forum discussion delves into the nuances of secure data deletion and efficient BLOB updates within SQLite databases. Secure deletion is a critical concern for applications handling sensitive data, where simply deleting a row might not zero-out the underlying storage, leaving recoverable remnants. The thread explores methods and implications for ensuring data is truly eradicated when removed, potentially touching on PRAGMA settings or specific file system interactions. Understanding these mechanisms is crucial for developers building secure, embedded applications with SQLite. The conversation also extends to optimizing updates for BLOB (Binary Large Object) data. Efficiently handling large binary data, such as images or documents, in an embedded database like SQLite requires careful consideration to avoid performance bottlenecks and excessive disk I/O. The discussion likely covers strategies for in-place updates, managing free space, and the internal workings of SQLite's storage engine when dealing with variable-length BLOBs. This insight helps developers make informed decisions on schema design and update patterns for improved application performance and data integrity. Comment: This thread offers valuable insights into SQLite's low-level data management, essential for anyone needing to implement robust security or optimize BLOB storage. PostgreSQL 19 to Feature Checksums For All

2026-07-05 原文 →
AI 资讯

Database Indexing and Query Optimization for Python Developers

Introduction Fixing N+1 queries with select_related / prefetch_related or selectinload (see the previous post ) gets you down to a small, sane number of queries per request. The next bottleneck is what each query costs once the table has millions of rows — and that is almost always about indexing. An index turns "scan every row" into "look it up directly." Skip it, and a query that's instant in development takes seconds once real data volume shows up in production. How Indexes Work: The B-Tree Intuition Without an index, a WHERE clause forces a sequential scan : the database reads every row and checks the condition — O(n) , cost grows linearly with table size. An index is a separate, sorted structure (almost always a B-tree ) mapping column values to row locations. Because it's sorted and balanced, finding a value is a tree walk: O(log n) . On a 10-million-row table, that's the difference between reading 10 million rows and roughly 23 tree nodes. This isn't free: Writes get slower — every INSERT / UPDATE / DELETE on an indexed column also updates the index. Storage grows — each index is a sorted copy of (part of) the data. An index trades write cost and storage for read speed. Indexing a column you rarely filter or sort on is pure cost, no benefit. Reading Query Plans: EXPLAIN ANALYZE Postgres' EXPLAIN ANALYZE shows what the planner actually did, not an estimate. Before an index , filtering orders by customer_id : EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 48291 ; Seq Scan on orders (cost=0.00..21453.00 rows=42 width=96) (actual time=0.021..118.442 rows=41 loops=1) Filter: (customer_id = 48291) Rows Removed by Filter: 1199959 Planning Time: 0.112 ms Execution Time: 118.471 ms Seq Scan means Postgres read all ~1.2 million rows and discarded all but 41. actual time is real elapsed time — 118ms for one lookup. After CREATE INDEX idx_orders_customer_id ON orders (customer_id); : Index Scan using idx_orders_customer_id on orders (cost=0.42..8.53 rows=42 wid

2026-07-04 原文 →
AI 资讯

Database Indexing and Query Optimization for Java Developers

Introduction Fixing N+1 queries (see the previous post ) gets your Hibernate app down to a handful of queries per request. The next bottleneck is what each of those queries costs once your tables have millions of rows — and that is almost always a question of indexing. An index turns "scan every row" into "look it up directly." Get the index wrong — or skip it — and a query that took 2ms in development takes 4 seconds in production once real data volume shows up. How Indexes Work: The B-Tree Intuition Without an index, a WHERE clause forces a sequential scan : the database reads every row and checks the condition. That's O(n) — cost grows linearly with table size. An index is a separate, sorted data structure (almost always a B-tree ) that maps column values to row locations. Because it's sorted and balanced, finding a value is a tree walk: O(log n) . On a 10-million-row table, that's the difference between reading 10 million rows and reading roughly 23 tree nodes. The cost is not free: Writes get slower. Every INSERT / UPDATE / DELETE on an indexed column must also update the index structure. Storage grows. Each index is a copy of (part of) the data, sorted differently. An index is a trade: you pay on every write so that specific reads become fast. Indexing a column you rarely filter or sort on is pure cost with no benefit. Reading Query Plans: EXPLAIN ANALYZE Postgres' EXPLAIN ANALYZE shows what the planner actually did — not what you hope it did. Before an index , filtering orders by customer_id : EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 48291 ; Seq Scan on orders (cost=0.00..21453.00 rows=42 width=96) (actual time=0.021..118.442 rows=41 loops=1) Filter: (customer_id = 48291) Rows Removed by Filter: 1199959 Planning Time: 0.112 ms Execution Time: 118.471 ms Seq Scan means Postgres read all ~1.2 million rows and threw away all but 41 of them. actual time is the real elapsed time, not an estimate — 118ms for one lookup. After CREATE INDEX idx_orders

2026-07-04 原文 →
AI 资讯

Shifting Left: How TDD Became the Foundation of SokoFlow's Core Engine

SokoFlow Build Log — Month 1 of 4 Last semester I set out on a new strategic plan to level up my software development skills through deliberate, project-based learning. That work produced one of the most ambitious things I've built so far: Sim-Pesa , a local-first transactional appliance that lets developers working in the M-Pesa ecosystem test and simulate STK Push workflows entirely on their own machines, without depending on the Daraja sandbox. I documented that build in 16 weekly posts, which you can find here . This semester, the focus shifts — from fintech foundations to cloud-native integration and real-world systems. The flagship project is SokoFlow , a conversational ERP for small Kenyan shopkeepers to track inventory and record sales entirely through WhatsApp chat. No app to download, no training session required — just natural language. Where Sim-Pesa lived in a controlled, predictable transactional world, SokoFlow steps into the mess of cloud-native reality: third-party API failures, webhook signature verification, the statelessness of HTTP, and container orchestration. The target audience shifts too — Kenyan SMEs operating on infrastructure that is often unreliable by design, not by exception. It's an ambitious project, but the goal was always to learn as much as possible from it. With the plan in place, I got to work. 1. The Vision of a Headless ERP The first real question I had to answer before writing a line of code: what does "headless" actually mean? Headless architecture decouples the frontend — the "head," or user interface — from the backend, the "body" that holds the data and business logic. A conventional ERP bundles both: backend plus a dashboard or UI on top. A headless ERP, by contrast, is just the engine. The brain. There's no built-in screen. So how do users interact with a system that has no interface of its own? SokoFlow doesn't actually care. It could be: WhatsApp SMS A web app A mobile app A voice assistant In this case, the "frontend

2026-06-30 原文 →
AI 资讯

Day 89 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 89 of my 100-day full-stack engineering run! 🎯 Yesterday, I kicked off my competitive solving streak on HackerRank. Today, I advanced from standard linear filters into the powerful world of textual pattern recognition by mastering: SQL Regular Expressions (REGEXP) and String Anchors! 🔍🛡️ When processing real-world data pipelines—like validating structured phone inputs, email domains, or parsing specific text queries—standard LIKE operators can make your code messy and repetitive. Today, I solved these constraints elegantly. 🧠 Shifting from Bulky LIKE Statements to Sleek REGEXP As tracked inside my workspace files across "Screenshot (193).png" and "Screenshot (195).png" , I solved two distinct core challenges from the HackerRank series: 1. Match from the Start: Weather Observation Station 6 The Goal: Query the list of CITY names from STATION that start with vowels ( a , e , i , o , u ), ensuring no duplicates are returned. The Evolution: Instead of chaining multiple LIKE queries or cutting sub-strings with LEFT() , I utilized the caret anchor ( ^ ) inside a regular expression array to verify the string's starting boundary instantly: sql SELECT DISTINCT CITY FROM STATION WHERE CITY REGEXP "^(A|E|I|O|U)";

2026-06-30 原文 →
AI 资讯

Building a Denim Collection API: A Practical Guide to Handling Product Variants

If you've ever worked with e-commerce data, you know that "a pair of jeans" is never just one product. A single style might come in 5 washes, 8 sizes, and 3 inseam lengths. That's 120 potential SKUs. Handling this correctly in an API can be tricky, so let me share a pattern I've used for structuring product variants. The core problem is balancing flexibility with performance. You want customers to filter by size, color, and fit without making dozens of API calls. Here's a simple but effective approach using a normalized database schema with a flat query layer: -- Products table (the "parent") CREATE TABLE products ( id UUID PRIMARY KEY , name TEXT NOT NULL , description TEXT , base_price DECIMAL ( 10 , 2 ), category TEXT ); -- Variants table (the actual sellable items) CREATE TABLE variants ( id UUID PRIMARY KEY , product_id UUID REFERENCES products ( id ), sku TEXT UNIQUE NOT NULL , size TEXT , color TEXT , wash TEXT , inseam TEXT , price DECIMAL ( 10 , 2 ), -- can override base price stock_quantity INT , image_url TEXT ); The key insight? Keep the product metadata (description, care instructions, brand story) in the products table, but put all the sellable attributes in variants. This lets you run queries like: -- Find all size 28 jeans in "mid wash" under $80 SELECT p . name , v . color , v . wash , v . price , v . stock_quantity FROM products p JOIN variants v ON p . id = v . product_id WHERE p . category = &# 039 ; women - jeans &# 039 ; AND v . size = &# 039 ; 28 &# 039 ; AND v . wash LIKE &# 039 ; % mid %&# 039 ; AND v . price & lt ; 80 AND v . stock_quantity & gt ; 0 ORDER BY v . price ; For the frontend, I usually return a flattened structure: { "product": { "id": "abc -123 " , "name": "Classic Straight Leg Jean" , "description": "High-rise fit in stretch denim..." , "availableSizes": [ " 24 " , " 25 " , " 26 " , " 27 "

2026-06-30 原文 →
AI 资讯

When to denormalize, when to join: A ClickHouse guide (2026)

Denormalization has been the standard approach to analytical data modeling for good reason. Moving joins, lookups, and business rules out of query time and into ingestion gives you the fastest possible reads for a known access pattern. For most of the past decade, it was often the practical default for latency-sensitive analytics. Earlier columnar engines and distributed query processors could execute joins, but many workloads paid for them through higher latency, higher compute cost, spill-to-disk, or distributed coordination overhead. That constraint has loosened. Modern columnar databases with advanced join algorithms have reduced the cost of runtime joins enough that normalization is now a genuinely viable option for many analytical workloads. Denormalization still delivers faster reads, but normalization can bring operational benefits: simpler pipelines, flexible schemas, and cleaner governance. Engineers can now make the decision based on their actual workload characteristics, rather than being forced into one approach by engine limitations. This guide is a decision framework for making that choice in ClickHouse. It starts with why denormalization became the default, explains what has changed in join performance, then compares the tradeoffs on both sides so you can decide where to denormalize, where to join, and where to use ClickHouse primitives that bridge the gap. For a broader evaluation framework covering latency, concurrency, ingest throughput, SQL flexibility, and cost across real-time OLAP options, see our guide to choosing a database for real-time analytics in 2026 . For a deeper comparison of how ClickHouse executes star schema joins against Druid, Pinot, and cloud DWHs, see our star schema and fast joins guide . TL;DR Denormalization and normalization are both valid modeling strategies. The right choice depends on your workload. Denormalization's tradeoffs are primarily operational : pipeline complexity, write-path overhead, data freshness lag, back

2026-06-29 原文 →
AI 资讯

Connecting the Dots: Understanding Database Relationships and SQL Joins

Have you ever wondered how apps like university portals know which courses a student is enrolled in, or how they pull up an instructor's full schedule in seconds? The answer lies in database relationships - one of the most important concepts in backend development. In this article, we'll explore: What database relationships are and why they matter The three types of relationships: One-to-One, One-to-Many, and Many-to-Many How relationship schemas work (primary keys, foreign keys) How SQL Joins let you pull connected data from multiple tables To keep things grounded, we'll use one running example throughout: a University Management System . By the end, you won't just understand the theory, you'll see exactly how these concepts connect in a real-world scenario. What Are Database Relationships? A database relationship defines how data in one table connects to data in another. Instead of storing the same information repeatedly, relational databases organize data into separate tables and link them using keys . Think about our university system. We have a table for students and another for courses . A student can enroll in multiple courses, and each course can have many students. Rather than storing a student's full details on every course record, we store the student's info once and create a relationship between the two tables. This keeps data clean, reduces duplication, and makes updates easy. If a student's email changes? Update it in one place - done. Here's a simple visual of what that looks like: +------------------+ +------------------+ | Students | | Courses | +------------------+ +------------------+ | student_id (PK) | | course_id (PK) | | name | | title | | email | | credits | +------------------+ +------------------+ \ / \ / \ / Enrollments (links students ↔ courses) Now let's look at the three types of relationships you'll encounter. Types of Database Relationships 1. One-to-One (1:1) Each record in Table A matches exactly one record in Table B and vice versa

2026-06-29 原文 →
AI 资讯

Day 76 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 76 of my 100-day full-stack engineering streak! For the past several weeks, I have been heavily immersed in NoSQL databases, using MongoDB documents to back my full-stack clones. Today, I decided to broaden my database engineering skill set by taking a deep dive into Relational Databases (SQL) ! 📊⚡ Stepping out of flexible JSON-like structures and adjusting to rigid, highly optimized tables is an essential step for any well-rounded backend developer. 🧠 What I Learned Today: SQL vs. NoSQL Before writing code, I mapped out the core architectural differences between the two paradigms: Feature NoSQL (e.g., MongoDB) SQL (e.g., MySQL / PostgreSQL) Data Model Flexible, schema-less collections & documents. Strict table-based structures with rows & columns. Relationships Typically nested embedded sub-documents or references. Explicit Relational Mapping via Primary & Foreign Keys. Scaling Horizontally scalable (distributed sharding across nodes). Vertically scalable (requires increasing horsepower on one machine). Transactions Great for high-write, unstructured or dynamic data shapes. Strict ACID compliance, making it excellent for financial or tabular data. 🛠️ Analyzing My First Query Block on Day 76 As showcased in "Screenshot (174).png" , I configured an entire relational lifecycle inside an independent database script: 1. Database Provisioning & Focus Selection I initialized the data cluster safely using standard syntax constraints to ensure execution safety and loaded the working context into the active engine: sql CREATE DATABASE IF NOT EXISTS XYZ_Company; USE XYZ_Company;CREATE TABLE employee_info ( id INT PRIMARY KEY, name VARCHAR(30), SALARY INT );

2026-06-27 原文 →