{"skills":[{"name":"Check row counts before joining tables","description":"Predict the size of a left join and pinpoint keys that would multiply records or leave a lookup empty.","content":"# Check row counts before joining tables\n\nPredict the size of a left join and pinpoint keys that would multiply records or leave a lookup empty.\n\n## When to use this skill\n\n- Someone is about to join two tables, merge two spreadsheets or add a lookup table and wants to know the output row count.\n- A join returned more rows than the left table and someone wants to know why.\n- Keys may be duplicated or blank on either side.\n\n## When not to use it\n\n- Checking a single spreadsheet lookup formula. Use the lookup table skill.\n- Inner, right or full outer joins without restating the method. The counts here are for a left join, which keeps every left row.\n\n## What you need\n\n- Left and right key columns, including duplicates and blanks.\n- Join type, match policy for null keys and expected relationship.\n\n## Ask before you start\n\nIf any of these are missing or unclear, ask before doing the work.\n\n- Which columns are the join keys on each side, and are they stored as the same type?\n- Which join type and engine will run it, such as SQL, pandas or Power Query? They treat blank keys differently.\n- Should a blank key ever match another blank key?\n- What relationship do you expect, such as one customer to many orders? It shows which duplicates are legitimate.\n\n## Method\n\n1. Count how often each key occurs on each side. Keep key values in their declared type and treat blank as missing when the contract says so.\n2. Look for differences the engine treats as distinct keys, such as text versus number, trailing spaces or case, and report them rather than silently fixing them.\n3. Confirm the null policy. SQL equality never matches a null to a null, because NULL = NULL is unknown rather than true; pandas merge matches null keys to each other. State the policy before giving a row count.\n4. For each key present on both sides, multiply the left count by the right count. Add one row for each unmatched left record, including blanks when nulls do not match. The sum is the expected output.\n5. List each left key once where a right-hand duplicate creates extra rows, and count the left records without a match.\n6. After the join, compare the actual row count with the prediction. In pandas, validate='many_to_one' stops a merge whose right-hand keys are not unique.\n\n## Checks before you deliver\n\n- Using the number of distinct keys hides multiplication, especially where both tables contain repeated keys.\n- Removing duplicates to force a desired row count can discard legitimate records. Trace the relationship first.\n- Assuming pandas and SQL agree. pandas matches null keys to each other; SQL equality does not, so unmatched counts can differ even when the row count is the same.\n- Joining a key stored as text on one side to numbers on the other. Depending on the engine the keys fail to match or the join raises an error.\n\n## How to present the result\n\nLead with the predicted output row count beside the left table's row count. Then list each key that multiplies rows with its count on each side and the extra rows it adds, followed by the unmatched left records and the null-key rule assumed. End with the check to run after the join.\n\n## Worked example\n\n**Request:** Predict a left join on id. Blanks never match.\n\n**Supplied material:**\n\n```text\nleft.id: A, A, B, C, <blank>\nright.id: A, A, B, <blank>\n```\n\n**Answer:** Expect seven output rows from four left rows. The two A contacts each produce two matches. C and the blank key each remain as one unmatched row. Check whether both right-hand A records are legitimate before joining.\n\n## Structured output for tests\n\nFor an ordinary job, answer in the format above and point back to the supplied evidence. Use this structure only for the test cases published with this skill, or when someone asks for structured JSON.\n\nReturn left_rows, joined_rows and unmatched_left_rows as integers, plus multiplied_keys as sorted strings. Represent a matched null key as null, after all strings. Calculate a left join with the null policy specified by the user.\n\n## Sources\n\n- [pandas: merge](https:\/\/pandas.pydata.org\/docs\/reference\/api\/pandas.merge.html): The reference describes a left join as keeping keys from the left frame, offers validate checks such as many_to_one, and warns that rows with null keys on both sides are matched to each other, unlike usual SQL join behaviour.\n- [PostgreSQL: comparison functions and operators](https:\/\/www.postgresql.org\/docs\/current\/functions-comparison.html): PostgreSQL documents that ordinary comparison with a null yields null rather than true, so NULL is not equal to NULL, while IS NOT DISTINCT FROM treats two nulls as equal. A SQLite check of the first case gave the same seven rows with two unmatched.\n\nTest cases and an answer checker for this skill: https:\/\/skills.raq.com\/skills\/predict-rows-before-joining-tables\n","scope":"contextual","trigger_keywords":["Check row counts before joining tables","predict-rows-before-joining-tables","predict rows before joining tables","How many rows will I get if I join these two tables?","How many rows will I get if I join these two tables","row count after the join","rows will this join","how many rows after joining"],"is_private":true,"is_active":true,"scripts":[{"name":"predict-rows-before-joining-tables-check","description":"Compare a saved JSON answer with a published test. Pass tests\/case-1\/expected.json (or another case) and the path to your answer.","language":"python","filename":"predict-rows-before-joining-tables-check.py","content":"from pathlib import Path\nimport runpy\n\nrunpy.run_path(str(Path(__file__).parent \/ 'tests' \/ 'check.py'), run_name='__main__')\n","supporting_files":[{"path":"SKILL.md","content":"---\nname: predict-rows-before-joining-tables\ndescription: \"Predict how many rows a left join will return before running it, find the keys that multiply rows and the records left unmatched, and state the null-key rule used. Use when joining tables, merging spreadsheets or running a SQL or pandas join that might duplicate or drop rows.\"\nlicense: CC-BY-4.0\nmetadata:\n  author: Raq.com\n  version: \"2026-11-22\"\n  homepage: https:\/\/skills.raq.com\/skills\/predict-rows-before-joining-tables\n---\n\n# Check row counts before joining tables\n\nPredict the size of a left join and pinpoint keys that would multiply records or leave a lookup empty.\n\n## When to use this skill\n\n- Someone is about to join two tables, merge two spreadsheets or add a lookup table and wants to know the output row count.\n- A join returned more rows than the left table and someone wants to know why.\n- Keys may be duplicated or blank on either side.\n\n## When not to use it\n\n- Checking a single spreadsheet lookup formula. Use the lookup table skill.\n- Inner, right or full outer joins without restating the method. The counts here are for a left join, which keeps every left row.\n\n## What you need\n\n- Left and right key columns, including duplicates and blanks.\n- Join type, match policy for null keys and expected relationship.\n\n## Ask before you start\n\nIf any of these are missing or unclear, ask before doing the work.\n\n- Which columns are the join keys on each side, and are they stored as the same type?\n- Which join type and engine will run it, such as SQL, pandas or Power Query? They treat blank keys differently.\n- Should a blank key ever match another blank key?\n- What relationship do you expect, such as one customer to many orders? It shows which duplicates are legitimate.\n\n## Method\n\n1. Count how often each key occurs on each side. Keep key values in their declared type and treat blank as missing when the contract says so.\n2. Look for differences the engine treats as distinct keys, such as text versus number, trailing spaces or case, and report them rather than silently fixing them.\n3. Confirm the null policy. SQL equality never matches a null to a null, because NULL = NULL is unknown rather than true; pandas merge matches null keys to each other. State the policy before giving a row count.\n4. For each key present on both sides, multiply the left count by the right count. Add one row for each unmatched left record, including blanks when nulls do not match. The sum is the expected output.\n5. List each left key once where a right-hand duplicate creates extra rows, and count the left records without a match.\n6. After the join, compare the actual row count with the prediction. In pandas, validate='many_to_one' stops a merge whose right-hand keys are not unique.\n\n## Checks before you deliver\n\n- Using the number of distinct keys hides multiplication, especially where both tables contain repeated keys.\n- Removing duplicates to force a desired row count can discard legitimate records. Trace the relationship first.\n- Assuming pandas and SQL agree. pandas matches null keys to each other; SQL equality does not, so unmatched counts can differ even when the row count is the same.\n- Joining a key stored as text on one side to numbers on the other. Depending on the engine the keys fail to match or the join raises an error.\n\n## How to present the result\n\nLead with the predicted output row count beside the left table's row count. Then list each key that multiplies rows with its count on each side and the extra rows it adds, followed by the unmatched left records and the null-key rule assumed. End with the check to run after the join.\n\n## Worked example\n\n**Request:** Predict a left join on id. Blanks never match.\n\n**Supplied material:**\n\n```text\nleft.id: A, A, B, C, <blank>\nright.id: A, A, B, <blank>\n```\n\n**Answer:** Expect seven output rows from four left rows. The two A contacts each produce two matches. C and the blank key each remain as one unmatched row. Check whether both right-hand A records are legitimate before joining.\n\n## Structured output for tests\n\nFor an ordinary job, answer in the format above and point back to the supplied evidence. Use this structure only for the test cases published with this skill, or when someone asks for structured JSON.\n\nReturn left_rows, joined_rows and unmatched_left_rows as integers, plus multiplied_keys as sorted strings. Represent a matched null key as null, after all strings. Calculate a left join with the null policy specified by the user.\n\n## Sources\n\n- [pandas: merge](https:\/\/pandas.pydata.org\/docs\/reference\/api\/pandas.merge.html): The reference describes a left join as keeping keys from the left frame, offers validate checks such as many_to_one, and warns that rows with null keys on both sides are matched to each other, unlike usual SQL join behaviour.\n- [PostgreSQL: comparison functions and operators](https:\/\/www.postgresql.org\/docs\/current\/functions-comparison.html): PostgreSQL documents that ordinary comparison with a null yields null rather than true, so NULL is not equal to NULL, while IS NOT DISTINCT FROM treats two nulls as equal. A SQLite check of the first case gave the same seven rows with two unmatched.\n\nTest cases and an answer checker for this skill: https:\/\/skills.raq.com\/skills\/predict-rows-before-joining-tables\n"},{"path":"LICENSE.txt","content":"Original Raq.com instructions and synthetic examples: CC BY 4.0.\nhttps:\/\/creativecommons.org\/licenses\/by\/4.0\/\nAttribution: Raq.com, https:\/\/skills.raq.com\/skills\/predict-rows-before-joining-tables\nReferenced third-party materials retain their own terms.\n"},{"path":"examples\/worked-example.md","content":"# Two contact records per account\n\nPredict a left join on id. Blanks never match.\n\n## Supplied material\n\nleft.id: A, A, B, C, <blank>\nright.id: A, A, B, <blank>\n\n## Worked answer\n\nExpect seven output rows from four left rows. The two A contacts each produce two matches. C and the blank key each remain as one unmatched row. Check whether both right-hand A records are legitimate before joining.\n\n## Reasoning\n\nTwo left A records each match twice. The C and blank records are retained unmatched.\n"},{"path":"tests\/check.py","content":"\"\"\"Check a saved agent answer locally with Python 3 (standard library only).\"\"\"\nimport json\nimport math\nimport sys\nfrom pathlib import Path\n\n\ndef compare(expected, actual, path=\"$\", accepted=None):\n    if isinstance(expected, bool) or isinstance(actual, bool):\n        if expected is not actual:\n            yield path\n    elif isinstance(expected, (int, float)) and isinstance(actual, (int, float)):\n        if not math.isclose(expected, actual, rel_tol=0, abs_tol=1e-8):\n            yield path\n    elif isinstance(expected, dict) and isinstance(actual, dict):\n        for key in sorted(set(expected) | set(actual)):\n            if key not in expected or key not in actual:\n                yield f\"{path}.{key}\"\n            elif not any(\n                not list(compare(option, actual[key]))\n                for option in (accepted or {}).get(key, [])\n            ):\n                yield from compare(expected[key], actual[key], f\"{path}.{key}\")\n    elif isinstance(expected, list) and isinstance(actual, list):\n        if len(expected) != len(actual):\n            yield f\"{path} (length)\"\n        for i, (left, right) in enumerate(zip(expected, actual)):\n            yield from compare(left, right, f\"{path}[{i}]\")\n    elif type(expected) != type(actual) or expected != actual:\n        yield path\n\n\ndef main():\n    if len(sys.argv) != 3:\n        raise SystemExit(\"Usage: python3 check.py expected.json answer.json\")\n    try:\n        expected, actual = [json.loads(Path(p).read_text(encoding=\"utf-8\")) for p in sys.argv[1:]]\n        alternatives = Path(sys.argv[1]).with_name(\"accepted.json\")\n        accepted = json.loads(alternatives.read_text(encoding=\"utf-8\")) if alternatives.is_file() else {}\n    except (ValueError, OSError) as error:\n        raise SystemExit(str(error))\n    differences = list(compare(expected, actual, accepted=accepted))\n    if differences:\n        raise SystemExit(\"Different fields: \" + \", \".join(differences))\n    print(\"Pass\")\n\n\nif __name__ == \"__main__\":\n    main()\n"},{"path":"tests\/README.md","content":"Give your agent SKILL.md and one request.txt in a fresh session. Keep the expected answer aside. Save the reply as answer.json, then run this from the tests folder:\n\n    python3 check.py case-1\/expected.json answer.json\n\nEach case also has an explanation. Where accepted.json exists, the checker accepts the alternatives listed there.\n"},{"path":"tests\/case-1\/request.txt","content":"Predict a left join on id. Blanks never match.\nReturn only the JSON specified in SKILL.md for this test.\n\nleft.id: A, A, B, C, <blank>\nright.id: A, A, B, <blank>\n"},{"path":"tests\/case-1\/expected.json","content":"{\n    \"left_rows\": 5,\n    \"joined_rows\": 7,\n    \"unmatched_left_rows\": 2,\n    \"multiplied_keys\": [\n        \"A\"\n    ]\n}\n"},{"path":"tests\/case-1\/explanation.txt","content":"Two left A records each match twice. The C and blank records are retained unmatched.\n"},{"path":"tests\/case-2\/request.txt","content":"Predict a left join using pandas null matching. <blank> is a null value.\nReturn only the JSON specified in SKILL.md for this test.\n\nleft.id: <blank>, D\nright.id: <blank>, <blank>, D\n"},{"path":"tests\/case-2\/expected.json","content":"{\n    \"left_rows\": 2,\n    \"joined_rows\": 3,\n    \"unmatched_left_rows\": 0,\n    \"multiplied_keys\": [\n        null\n    ]\n}\n"},{"path":"tests\/case-2\/explanation.txt","content":"Here the null matches two right-hand records under the requested merge policy.\n"}],"is_active":true,"is_approved":false}]}]}