惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LINUX DO - 最新话题
G
Google Developers Blog
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
F
Full Disclosure
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
Help Net Security
Help Net Security
The Hacker News
The Hacker News
IT之家
IT之家
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V
Visual Studio Blog
博客园 - 聂微东
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
Google DeepMind News
Google DeepMind News
Cloudbric
Cloudbric
N
News | PayPal Newsroom
A
About on SuperTechFans
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hugging Face - Blog
Hugging Face - Blog
M
MIT News - Artificial intelligence
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
罗磊的独立博客
K
Kaspersky official blog
The Cloudflare Blog
I
Intezer

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Joins: Combining Tables Without Losing Your Mind
Akhilesh · 2026-05-01 · via DEV Community

You have two tables.

The customers table knows who people are. Name, city, contact details.

The orders table knows what they bought. Product, amount, date.

Neither table alone answers the question: which customers in Mumbai spent more than 50,000 rupees last month?

You need both tables combined through their shared key. That combination is a join.

Joins are where SQL becomes genuinely powerful. The ability to link tables that were designed separately and query them as if they were one is what makes relational databases so useful for data analysis.


The Setup

import sqlite3
import pandas as pd

conn = sqlite3.connect("joins_practice.db")

conn.executescript("""
    DROP TABLE IF EXISTS customers;
    DROP TABLE IF EXISTS orders;
    DROP TABLE IF EXISTS products;

    CREATE TABLE customers (
        customer_id  INTEGER PRIMARY KEY,
        name         TEXT,
        city         TEXT,
        tier         TEXT
    );

    CREATE TABLE orders (
        order_id     INTEGER PRIMARY KEY,
        customer_id  INTEGER,
        product_id   INTEGER,
        amount       REAL,
        order_date   TEXT,
        status       TEXT
    );

    CREATE TABLE products (
        product_id   INTEGER PRIMARY KEY,
        product_name TEXT,
        category     TEXT,
        cost_price   REAL
    );

    INSERT INTO customers VALUES
        (1, 'Alex',   'Mumbai',    'Gold'),
        (2, 'Priya',  'Delhi',     'Silver'),
        (3, 'Sam',    'Bangalore', 'Bronze'),
        (4, 'Jordan', 'Mumbai',    'Gold'),
        (5, 'Lisa',   'Chennai',   'Silver'),
        (6, 'Ravi',   'Delhi',     'Bronze');

    INSERT INTO products VALUES
        (101, 'Laptop',     'Electronics', 50000),
        (102, 'Phone',      'Electronics', 28000),
        (103, 'Headphones', 'Electronics',  1800),
        (104, 'Shirt',      'Clothing',      400),
        (105, 'Watch',      'Accessories',  6000);

    INSERT INTO orders VALUES
        (1,  1,   101, 75000, '2024-01-05', 'completed'),
        (2,  2,   102, 45000, '2024-01-08', 'completed'),
        (3,  1,   103,  3500, '2024-01-12', 'completed'),
        (4,  3,   104,   800, '2024-01-15', 'completed'),
        (5,  4,   101, 75000, '2024-01-18', 'completed'),
        (6,  2,   104,  1500, '2024-01-20', 'completed'),
        (7,  1,   105, 12000, '2024-02-01', 'completed'),
        (8,  7,   102, 45000, '2024-02-05', 'completed'),
        (9,  3,   105, 12000, '2024-02-08', 'completed'),
        (10, 4,   104,   800, '2024-02-10', 'completed');
""")
conn.commit()

def q(sql):
    return pd.read_sql_query(sql, conn)

print("Three tables created.")
print(q("SELECT * FROM customers"))
print(q("SELECT * FROM orders"))

Enter fullscreen mode Exit fullscreen mode

Notice order 8 has customer_id = 7 which does not exist in the customers table. Customer 5 (Lisa) and customer 6 (Ravi) have no orders. These edge cases will show you exactly how different join types behave.


INNER JOIN: Only the Matches

Inner join returns rows that have a matching key in both tables. Unmatched rows from either side are dropped.

result = q("""
    SELECT
        c.name,
        c.city,
        o.order_id,
        o.amount,
        o.order_date
    FROM orders o
    INNER JOIN customers c ON o.customer_id = c.customer_id
    ORDER BY o.order_date;
""")
print(result)
print(f"\nRows: {len(result)}")

Enter fullscreen mode Exit fullscreen mode

Output:

     name       city  order_id   amount  order_date
0    Alex     Mumbai         1  75000.0  2024-01-05
1   Priya      Delhi         2  45000.0  2024-01-08
2    Alex     Mumbai         3   3500.0  2024-01-12
3     Sam  Bangalore         4    800.0  2024-01-15
4  Jordan     Mumbai         5  75000.0  2024-01-18
5   Priya      Delhi         6   1500.0  2024-01-20
6    Alex     Mumbai         7  12000.0  2024-02-01
7     Sam  Bangalore         9  12000.0  2024-02-08
8  Jordan     Mumbai        10    800.0  2024-02-10

Rows: 9

Enter fullscreen mode Exit fullscreen mode

Order 8 (customer_id 7, no matching customer) is gone. Lisa and Ravi who have no orders are gone. Only the nine orders with valid matching customers appear.

The ON o.customer_id = c.customer_id clause is the join condition. It tells SQL which columns to use as the connecting key.

Aliases o and c shorten the table names. Without aliases, you write orders.customer_id = customers.customer_id. With aliases, o.customer_id = c.customer_id. Always use aliases. Long table names in every column reference make queries unreadable.


LEFT JOIN: Keep Everything From the Left

Left join keeps all rows from the left table. If a row from the left has no match in the right, it still appears but with NULLs for the right table's columns.

result = q("""
    SELECT
        c.customer_id,
        c.name,
        c.city,
        COUNT(o.order_id)  AS total_orders,
        SUM(o.amount)      AS total_spent
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id, c.name, c.city
    ORDER BY total_spent DESC;
""")
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

   customer_id    name       city  total_orders  total_spent
0            1    Alex     Mumbai             3     90500.0
1            4  Jordan     Mumbai             2     75800.0
2            2   Priya      Delhi             2     46500.0
3            3     Sam  Bangalore             2     12800.0
4            5    Lisa    Chennai             0         NaN
5            6    Ravi      Delhi             0         NaN

Enter fullscreen mode Exit fullscreen mode

All six customers appear. Lisa and Ravi have zero orders and NaN for total_spent. An inner join would have removed them entirely.

Left join is the right choice when you need a complete list of one entity (customers) and want to attach related data when it exists, while still showing entities with no related data.

Use this for finding customers who have never ordered, users who have not logged in, products with no sales.


Finding Rows With No Match

Left join combined with a WHERE NULL check finds the rows that had no match.

result = q("""
    SELECT
        c.customer_id,
        c.name,
        c.city,
        c.tier
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    WHERE o.order_id IS NULL;
""")
print("Customers with no orders:")
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

Customers with no orders:
   customer_id  name     city    tier
0            5  Lisa  Chennai  Silver
1            6  Ravi    Delhi  Bronze

Enter fullscreen mode Exit fullscreen mode

This pattern is used constantly. Find users who signed up but never bought. Find products that were added but never ordered. Find employees assigned to no projects. The technique is always the same: LEFT JOIN then WHERE right_table.key IS NULL.


RIGHT JOIN: Keep Everything From the Right

Right join is the mirror of left join. All rows from the right table survive regardless of whether they match the left.

result = q("""
    SELECT
        c.name,
        c.city,
        o.order_id,
        o.amount,
        o.customer_id AS order_customer_id
    FROM customers c
    RIGHT JOIN orders o ON c.customer_id = o.customer_id
    ORDER BY o.order_id;
""")
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

     name       city  order_id   amount  order_customer_id
0    Alex     Mumbai         1  75000.0                  1
1   Priya      Delhi         2  45000.0                  2
...
8     NaN        NaN         8  45000.0                  7
...

Enter fullscreen mode Exit fullscreen mode

Order 8 appears with NaN for name and city because customer_id 7 does not exist in customers. Right join kept all orders. Lisa and Ravi are gone because they have no orders.

Most developers prefer left joins over right joins. The same result can always be achieved by swapping the table order and using a left join. Consistency matters for readability.


FULL OUTER JOIN: Keep Everything

SQLite does not support FULL OUTER JOIN natively but you can simulate it.

result = q("""
    SELECT c.customer_id, c.name, o.order_id, o.amount
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id

    UNION ALL

    SELECT c.customer_id, c.name, o.order_id, o.amount
    FROM orders o
    LEFT JOIN customers c ON o.customer_id = c.customer_id
    WHERE c.customer_id IS NULL;
""")
print(result)
print(f"\nRows: {len(result)}")

Enter fullscreen mode Exit fullscreen mode

Output includes all customers (even with no orders) and all orders (even with no matching customer). Full outer join shows you every row from both tables and flags the ones that could not find a match.


Joining Three Tables

Real queries often span three or more tables.

result = q("""
    SELECT
        c.name                           AS customer,
        c.city,
        p.product_name                   AS product,
        p.category,
        o.amount                         AS sale_price,
        p.cost_price,
        ROUND(o.amount - p.cost_price, 0) AS profit
    FROM orders o
    INNER JOIN customers c ON o.customer_id = c.customer_id
    INNER JOIN products  p ON o.product_id  = p.product_id
    WHERE o.status = 'completed'
    ORDER BY profit DESC;
""")
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

   customer       city  product         category  sale_price  cost_price   profit
0      Alex     Mumbai   Laptop      Electronics     75000.0     50000.0  25000.0
1    Jordan     Mumbai   Laptop      Electronics     75000.0     50000.0  25000.0
2     Priya      Delhi    Phone      Electronics     45000.0     28000.0  17000.0
...

Enter fullscreen mode Exit fullscreen mode

Three tables. Two joins. One clean result showing customer, product, and profit per transaction. This is the kind of query that lives in every business intelligence tool.

Each new table gets its own JOIN clause. The ON condition connects it to one of the tables already in the query.


Self Join: A Table Joining Itself

Sometimes a table references itself. An employees table where each employee has a manager_id that points to another row in the same table.

conn.executescript("""
    DROP TABLE IF EXISTS employees_hier;
    CREATE TABLE employees_hier (
        emp_id     INTEGER PRIMARY KEY,
        name       TEXT,
        manager_id INTEGER
    );
    INSERT INTO employees_hier VALUES
        (1, 'Director', NULL),
        (2, 'Manager A', 1),
        (3, 'Manager B', 1),
        (4, 'Alex',      2),
        (5, 'Priya',     2),
        (6, 'Sam',       3);
""")
conn.commit()

result = q("""
    SELECT
        e.name        AS employee,
        m.name        AS manager
    FROM employees_hier e
    LEFT JOIN employees_hier m ON e.manager_id = m.emp_id
    ORDER BY e.emp_id;
""")
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

    employee   manager
0   Director      None
1  Manager A  Director
2  Manager B  Director
3       Alex Manager A
4      Priya Manager A
5        Sam Manager B

Enter fullscreen mode Exit fullscreen mode

The same table joined to itself with two different aliases. e for the employee, m for the manager. Each employee now shows who they report to. The Director has NULL because they report to nobody.


Join Performance: The Rule You Need to Know

Joins are fast when you join on indexed columns. The primary key is always indexed. Foreign keys often are not by default.

If you join on a column that is not indexed and the tables are large, the query can become very slow. Always check what columns your joins use and whether those columns have indexes.

CREATE INDEX idx_orders_customer ON orders(customer_id);
CREATE INDEX idx_orders_product  ON orders(product_id);

Enter fullscreen mode Exit fullscreen mode

Two lines. These make the joins in this post dramatically faster on large tables. In real production databases, this is part of database design. But when you are writing queries against existing databases, knowing to ask "is this column indexed?" can save you from writing queries that take minutes instead of milliseconds.


A Resource Worth Knowing

Joins Visualizer at joins.spathon.com lets you click on different join types and see animated, interactive visualizations of exactly which rows survive each join. Visual, interactive, takes two minutes. Bookmark it. Every time you are uncertain which join type to use, check it.

Jeff Atwood wrote a short classic piece called "A Visual Explanation of SQL Joins" on his blog Coding Horror (codinghorror.com) using Venn diagrams that became the standard way people teach this topic. It is ten years old and still the clearest explanation of join types available. Search "Jeff Atwood visual explanation SQL joins Coding Horror."


Try This

Create sql_joins_practice.py. Use the database from this post.

Write a query that shows each product, how many times it was ordered, total revenue, and the profit margin (sale price minus cost price). Include products that were never ordered, showing zero for orders and revenue.

Find customers who have ordered in both January and February 2024. Use a self-join or subquery approach.

Show the city-level summary: city, number of customers, number of completed orders, total revenue, and average order value per customer. Only include cities with at least two customers.

Using a left join with a NULL check, find any orders where the customer_id does not exist in the customers table. These are data integrity problems.

Write a three-table join that shows customer name, product name, category, amount paid, and whether the customer is Gold, Silver, or Bronze tier. Sort by amount descending.


What's Next

One table queries. Multi-table joins. Both covered. Next is subqueries and CTEs, which let you use the result of one query as the input to another. They make complex multi-step logic readable and maintainable instead of nested and impossible to debug.