Repository navigation
Expand file tree
/
Copy pathsql_set_operators_interactive.html
More file actions
33 lines (33 loc) · 20 KB
/
Copy pathsql_set_operators_interactive.html
File metadata and controls
33 lines (33 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>SQL SET Operators — Interactive Study Guide</title><style>
:root{color-scheme:light;--bg:#f3f6fa;--paper:#fff;--ink:#17283b;--muted:#506477;--line:#dce4ec;--accent:#175d9c;--a:#dcecff;--b:#d9f3e8;--r:#d8e9ff;--warn:#fff2d7}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.6 system-ui,-apple-system,Segoe UI,sans-serif}main{max-width:1100px;margin:auto;padding:24px}header{padding:32px;background:#173653;color:white;border-radius:18px}header p{color:#dce8f3;margin-bottom:0}h1{font-size:clamp(26px,4vw,39px);line-height:1.15;margin:8px 0}h2{font-size:23px;margin:0 0 15px}h3{font-size:18px;margin:0 0 8px}.eyebrow{font-size:12px;text-transform:uppercase;letter-spacing:2px;font-weight:700}nav{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0}nav a{color:var(--accent);text-decoration:none;background:var(--paper);padding:8px 12px;border:1px solid var(--line);border-radius:8px}section{background:var(--paper);border:1px solid var(--line);border-radius:14px;padding:24px;margin:18px 0;scroll-margin-top:12px}p{margin:8px 0 14px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.panel{border:1px solid var(--line);border-radius:10px;padding:16px;min-width:0}.scroll{overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:14px}th,td{padding:12px;text-align:left;border-bottom:1px solid var(--line);vertical-align:top}th{background:#edf3f9;font-weight:700}tr:last-child td{border-bottom:0}code,pre{font-family:Consolas,monospace}pre{background:#142b40;color:#e9f4ff;border-radius:9px;padding:15px;white-space:pre-wrap;overflow-wrap:anywhere;margin:10px 0}button{font:inherit;font-weight:650;cursor:pointer;padding:9px 13px;border-radius:8px;border:1px solid var(--line);color:var(--ink);background:var(--paper)}button:hover{border-color:var(--accent)}button[aria-pressed=true],button.primary{background:var(--accent);color:white;border-color:var(--accent)}button:focus-visible,input:focus-visible,a:focus-visible{outline:3px solid #e7a63a;outline-offset:3px}.toolbar{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0}label{display:block;font-weight:650}input{width:100%;border:1px solid #9eafbf;border-radius:8px;padding:10px;font:inherit;color:var(--ink);background:var(--paper);margin:6px 0}.hint{color:var(--muted);font-size:14px}.tokens{display:flex;flex-wrap:wrap;gap:7px;min-height:42px;align-items:center}.token{min-width:36px;padding:5px 10px;text-align:center;border-radius:7px;border:1px solid #a8bad0;font-weight:700;background:var(--r)}.token.a{background:var(--a)}.token.b{background:var(--b);border-color:#a3cfbe}.token.dup{border:2px dashed #ae7918}.legend{font-size:13px;color:var(--muted)}.result{background:#edf5ff;border-radius:10px;padding:16px;margin:14px 0}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:12px 0}.stat{padding:12px;background:var(--paper);border:1px solid var(--line);border-radius:9px}.stat strong{display:block;font-size:24px}.stat span{font-size:13px;color:var(--muted)}.error{color:#a12121;font-weight:650}.note{background:var(--warn);padding:12px 15px;border-radius:8px}.diagram{display:block;width:100%;max-width:320px;margin:10px auto;height:auto}.diagram text{font-family:system-ui;fill:var(--ink);font-size:12px;text-anchor:middle}.chip{display:inline-block;background:#e9f0f8;padding:2px 8px;border-radius:5px;font-size:13px;font-weight:700}details{border-top:1px solid var(--line);padding:12px 0}summary{cursor:pointer;font-weight:650}footer{color:var(--muted);font-size:13px;text-align:center;padding:12px}ul{padding-left:22px}li{margin:5px 0}@media(max-width:650px){main{padding:12px}section,header{padding:17px}.grid{grid-template-columns:1fr}.stats{grid-template-columns:repeat(3,minmax(0,1fr))}.stat{padding:8px}.stat span{font-size:11px}th,td{padding:9px}table{min-width:490px}}@media print{body{background:white}nav,.toolbar,.no-print{display:none}section{break-inside:avoid}header{color:#17283b;background:white;border:1px solid #bbb}header p{color:#506477}}
</style></head><body><main><header><div class="eyebrow">Java developer · SQL notes</div><h1>SQL SET Operators</h1><p>Understand UNION, UNION ALL, INTERSECT and EXCEPT / MINUS with simple examples, duplicate records and live results.</p></header><nav aria-label="Sections"><a href="#difference">JOIN vs SET</a><a href="#comparison">Comparison</a><a href="#simulator">Live simulator</a><a href="#examples">SQL examples</a><a href="#rules">Rules</a><a href="#quiz">Interview revision</a></nav>
<section id="difference"><h2>1. JOIN vs SET operators</h2><div class="grid"><div class="panel"><h3>JOIN — side by side</h3><p>Combines related rows, usually to retrieve columns from different tables.</p><svg class="diagram" viewBox="0 0 300 128" role="img" aria-label="Two tables combined side by side"><g stroke="#9eafbf"><rect x="35" y="10" width="95" height="38" rx="5" fill="#dcecff"/><rect x="170" y="10" width="95" height="38" rx="5" fill="#d9f3e8"/><path d="M82 48V60H217V48 M150 60V75" fill="none"/><rect x="55" y="78" width="95" height="38" fill="#dcecff"/><rect x="150" y="78" width="95" height="38" fill="#d9f3e8"/></g><text x="82" y="33">Employee</text><text x="217" y="33">Salary</text><text x="102" y="101">Name</text><text x="198" y="101">Salary</text></svg></div><div class="panel"><h3>SET — one below another</h3><p>Combines or compares rows returned by separate SELECT queries.</p><svg class="diagram" viewBox="0 0 300 128" role="img" aria-label="Two query results combined vertically"><g stroke="#9eafbf"><rect x="35" y="6" width="95" height="30" rx="5" fill="#dcecff"/><rect x="170" y="6" width="95" height="30" rx="5" fill="#d9f3e8"/><path d="M82 36V47H217V36 M150 47V58" fill="none"/><rect x="100" y="60" width="100" height="30" fill="#dcecff"/><rect x="100" y="90" width="100" height="30" fill="#d9f3e8"/></g><text x="82" y="25">Query A</text><text x="217" y="25">Query B</text><text x="150" y="79">Rows A</text><text x="150" y="109">Rows B</text></svg></div></div><p class="hint">The SET diagram illustrates UNION ALL. Other SET operators filter or remove duplicate rows.</p></section>
<section id="comparison"><h2>2. SET operators — single and duplicate records</h2><div class="scroll"><table><thead><tr><th>SET operator</th><th>Purpose</th><th>Records found in only one query</th><th>Common records and duplicates</th></tr></thead><tbody><tr><td><strong>UNION</strong></td><td>Combines both results.</td><td>Keeps one copy of each.</td><td>Keeps one copy of each distinct row, including common rows.</td></tr><tr><td><strong>UNION ALL</strong></td><td>Combines all rows.</td><td>Keeps every occurrence.</td><td>Keeps all copies, both within and across queries.</td></tr><tr><td><strong>INTERSECT</strong></td><td>Returns common rows.</td><td>Excludes all.</td><td>Keeps one copy of each row present in both queries.</td></tr><tr><td><strong>EXCEPT / MINUS</strong></td><td>Returns A minus B.</td><td>Keeps one copy of A-only rows; excludes B-only rows.</td><td>Removes every row found in B; removes duplicates among remaining A rows.</td></tr></tbody></table></div><p class="hint">Single records may mean rows appearing exactly once or rows exclusive to one query. These are different concepts: a row may occur twice in A and still be exclusive to A.</p></section>
<section id="simulator"><h2>3. Interactive SET operator simulator</h2><p>Edit both tables, select an operator and see the output immediately. Use comma-separated whole numbers as sample IDs.</p><div class="grid"><div class="panel"><label for="a">Table A</label><input id="a" value="1, 1, 2, 3" maxlength="300" autocomplete="off" spellcheck="false"><div id="aRows" class="tokens"></div></div><div class="panel"><label for="b">Table B</label><input id="b" value="2, 3, 3, 4" maxlength="300" autocomplete="off" spellcheck="false"><div id="bRows" class="tokens"></div></div></div><p class="legend">Dashed outline = a repeated occurrence after the first appearance within that table or output.</p><div class="toolbar" id="ops" aria-label="Choose SET operator"><button data-op="UNION" aria-pressed="true">UNION</button><button data-op="UNION ALL" aria-pressed="false">UNION ALL</button><button data-op="INTERSECT" aria-pressed="false">INTERSECT</button><button data-op="EXCEPT" aria-pressed="false">EXCEPT (A − B)</button><button data-op="REVERSE" aria-pressed="false">EXCEPT (B − A)</button></div><div id="error" role="alert" class="error"></div><div class="result" id="result" aria-live="polite"><h3 id="resultTitle">Output</h3><div class="tokens" id="output"></div><div class="stats"><div class="stat"><strong id="total">0</strong><span>Output rows</span></div><div class="stat"><strong id="distinct">0</strong><span>Distinct rows</span></div><div class="stat"><strong id="duplicates">0</strong><span>Extra copies</span></div></div><p id="explanation"></p></div><pre id="query"></pre><div class="toolbar no-print"><button id="reset">Reset example</button><button id="swap">Swap A and B</button><button id="disjoint">No common records</button><button id="same">Same records</button><button id="copy">Copy SQL</button><span id="copyStatus" role="status" class="hint"></span></div><h3>Record-by-record breakdown</h3><div class="scroll"><table><thead><tr><th>ID</th><th>Occurrences in A</th><th>Occurrences in B</th><th>Occurrences in output</th><th>Reason</th></tr></thead><tbody id="breakdown"></tbody></table></div><p class="hint">The simulator uses one numeric column and preserves example order for readability. SQL output order is not guaranteed unless ORDER BY is specified.</p></section>
<section id="examples"><h2>4. SQL examples and real-time use cases</h2><p>Using the default values: <strong>A = 1, 1, 2, 3</strong> and <strong>B = 2, 3, 3, 4</strong>.</p><div class="grid">
<article class="panel"><h3>UNION</h3><p>Combines all distinct records. The repeated 1, 2 and 3 appear only once.</p><svg class="diagram" viewBox="0 0 300 115" role="img" aria-label="Distinct set membership diagram for UNION"><circle cx="112" cy="57" r="45" fill="#9ccaff"/><circle cx="178" cy="57" r="45" fill="#9ccaff"/><g fill="none" stroke="#71869b"><circle cx="112" cy="57" r="45"/><circle cx="178" cy="57" r="45"/></g><text x="90" y="25">A</text><text x="200" y="25">B</text><text x="96" y="62">1</text><text x="145" y="62">2, 3</text><text x="195" y="62">4</text></svg><pre>SELECT id FROM A
UNION
SELECT id FROM B;</pre><p><strong>Output:</strong> 1, 2, 3, 4</p><p><strong>Use case:</strong> Combine current and historical customer lists without duplicate IDs.</p></article><article class="panel"><h3>UNION ALL</h3><p>Keeps every occurrence, including repeated records within and across tables.</p><svg class="diagram" viewBox="0 0 300 100" role="img" aria-label="All occurrences from both tables are retained"><rect x="20" y="10" width="130" height="32" rx="5" fill="#dcecff"/><rect x="150" y="10" width="130" height="32" rx="5" fill="#d9f3e8"/><text x="85" y="30">1, 1, 2, 3</text><text x="215" y="30">2, 3, 3, 4</text><path d="M150 42V56" stroke="#506477"/><rect x="20" y="60" width="260" height="30" rx="5" fill="#d8e9ff"/><text x="150" y="79">1, 1, 2, 3, 2, 3, 3, 4</text></svg><pre>SELECT id FROM A
UNION ALL
SELECT id FROM B;</pre><p><strong>Output:</strong> 1, 1, 2, 3, 2, 3, 3, 4</p><p><strong>Use case:</strong> Combine monthly transaction logs without dropping any rows.</p></article><article class="panel"><h3>INTERSECT</h3><p>Only 2 and 3 are common. Each is returned once; 1 and 4 are excluded.</p><svg class="diagram" viewBox="0 0 300 115" role="img" aria-label="Distinct set membership diagram for INTERSECT"><path d="M145 26.4 A45 45 0 0 1 145 87.6 A45 45 0 0 1 145 26.4" fill="#9ccaff"/><g fill="none" stroke="#71869b"><circle cx="112" cy="57" r="45"/><circle cx="178" cy="57" r="45"/></g><text x="90" y="25">A</text><text x="200" y="25">B</text><text x="96" y="62">1</text><text x="145" y="62">2, 3</text><text x="195" y="62">4</text></svg><pre>SELECT id FROM A
INTERSECT
SELECT id FROM B;</pre><p><strong>Output:</strong> 2, 3</p><p><strong>Use case:</strong> Find customers who purchased in both months.</p></article><article class="panel"><h3>EXCEPT / MINUS</h3><p>1 is exclusive to A, so it appears once. Common rows 2 and 3 are excluded completely.</p><svg class="diagram" viewBox="0 0 300 115" role="img" aria-label="Distinct set membership diagram for EXCEPT / MINUS"><path d="M145 26.4 A45 45 0 1 0 145 87.6 A45 45 0 0 1 145 26.4" fill="#9ccaff"/><g fill="none" stroke="#71869b"><circle cx="112" cy="57" r="45"/><circle cx="178" cy="57" r="45"/></g><text x="90" y="25">A</text><text x="200" y="25">B</text><text x="96" y="62">1</text><text x="145" y="62">2, 3</text><text x="195" y="62">4</text></svg><pre>SELECT id FROM A
EXCEPT
SELECT id FROM B;</pre><p><strong>Output:</strong> 1</p><p><strong>Use case:</strong> Find registered customers who have never placed an order.</p><p class="hint">Oracle traditionally uses MINUS. EXCEPT / MINUS is directional: B minus A returns 4.</p></article></div><p class="hint">Venn diagrams show distinct membership, not the number of duplicate occurrences.</p></section>
<section id="rules"><h2>5. Important rules</h2><ul><li>Each SELECT must return the same number of columns.</li><li>Corresponding columns must have compatible data types.</li><li>Columns are matched by position, not by name.</li><li>Result column names generally come from the first SELECT.</li><li>A common primary key or JOIN condition is not required.</li><li>Duplicate removal compares the complete selected row, not just the ID.</li><li>Use ORDER BY at the end to sort the combined result.</li><li>Operator availability and ALL variants depend on your database. Oracle traditionally uses MINUS for set difference.</li></ul><div class="note"><strong>Performance:</strong> UNION ALL is generally faster than UNION because it does not need to remove duplicates. Use it only when retaining duplicates is correct for the requirement.</div><h3 style="margin-top:18px">Complete-row comparison</h3><p>If A contains (1, Rahul) and B contains (1, Amit), UNION returns both rows when selecting id and name, because their names differ. Selecting only id would return one row with ID 1.</p></section>
<section id="quiz"><h2>6. Interview revision</h2><p>Try answering each question before expanding it.</p><details><summary>What is the difference between JOIN and SET?</summary><p>JOIN usually combines columns from related rows. SET operators combine or compare rows from SELECT results.</p></details><details><summary>What is the difference between UNION and UNION ALL?</summary><p>UNION returns distinct rows. UNION ALL retains all occurrences, including duplicates.</p></details><details><summary>Does INTERSECT keep duplicate common records?</summary><p>No. Plain INTERSECT returns each common row once. Some databases also support INTERSECT ALL, which retains the minimum occurrence count across inputs.</p></details><details><summary>Does EXCEPT remove just one matching copy?</summary><p>No. Plain EXCEPT removes a row entirely if it appears in the second query, regardless of its frequency in the first query. Some databases support EXCEPT ALL, which subtracts occurrence counts.</p></details><details><summary>Is A EXCEPT B the same as B EXCEPT A?</summary><p>No. Direction matters. For the default example, A EXCEPT B returns 1, while B EXCEPT A returns 4.</p></details><details><summary>Can I combine queries with different column names?</summary><p>Yes, provided the number of columns matches and corresponding data types are compatible.</p></details><details><summary>Which operator is generally faster: UNION or UNION ALL?</summary><p>UNION ALL, because it avoids duplicate elimination. Actual performance depends on the execution plan and data.</p></details></section><footer>SQL SET Operators · Offline interactive study guide · <button class="no-print" onclick="window.print()">Print notes</button></footer></main>
<script>
'use strict';
const $=id=>document.getElementById(id);let op='UNION';
function parse(s){if(!s.trim())return [];return s.split(',').map(x=>{x=x.trim();if(!/^[+-]?\d+$/.test(x)||!Number.isSafeInteger(Number(x)))throw new Error('Enter comma-separated whole numbers (for example: 1, 1, 2, 3). Empty input represents an empty table.');return Number(x);});}
const unique=x=>[...new Set(x)];
function evaluate(a,b,o){switch(o){case 'UNION':return unique([...a,...b]);case 'UNION ALL':return [...a,...b];case 'INTERSECT':return unique(a.filter(n=>b.includes(n)));case 'EXCEPT':return unique(a.filter(n=>!b.includes(n)));case 'REVERSE':return unique(b.filter(n=>!a.includes(n)));}}
function renderTokens(el,values,cls){el.replaceChildren();let seen=new Set();if(!values.length){let span=document.createElement('span');span.className='hint';span.textContent='No rows';el.append(span);}for(const n of values){let span=document.createElement('span');span.className='token '+cls+(seen.has(n)?' dup':'');span.textContent=n;el.append(span);seen.add(n);}}
const explanations={'UNION':'Combines both tables and keeps one copy of each distinct record.','UNION ALL':'Returns every occurrence from A and B. No duplicate removal is performed.','INTERSECT':'Keeps only records present in both tables, with one copy of each.','EXCEPT':'Keeps only records present in A but absent from B, with one copy of each.','REVERSE':'Keeps only records present in B but absent from A, with one copy of each.'};
function count(arr,n){return arr.filter(x=>x===n).length;}
function update(){let a,b;try{a=parse($('a').value);b=parse($('b').value);}catch(e){$('error').textContent=e.message;for(const id of ['aRows','bRows','output','breakdown'])$(id).replaceChildren();$('resultTitle').textContent='Output unavailable';for(const id of ['total','distinct','duplicates'])$(id).textContent='—';$('explanation').textContent='Correct the inputs to see results.';$('query').textContent='';$('copy').disabled=true;return;}$('error').textContent='';$('copy').disabled=false;let out=evaluate(a,b,op);renderTokens($('aRows'),a,'a');renderTokens($('bRows'),b,'b');renderTokens($('output'),out,'');$('resultTitle').textContent='Output — '+(op==='REVERSE'?'EXCEPT (B − A)':op);$('total').textContent=out.length;$('distinct').textContent=unique(out).length;$('duplicates').textContent=out.length-unique(out).length;$('explanation').textContent=explanations[op];$('query').textContent=op==='REVERSE'?'SELECT id FROM B\nEXCEPT\nSELECT id FROM A;':`SELECT id FROM A\n${op}\nSELECT id FROM B;`;let tbody=$('breakdown');tbody.replaceChildren();for(const n of unique([...a,...b]).sort((x,y)=>x-y)){let ca=count(a,n),cb=count(b,n),co=count(out,n),reason;if(op==='UNION ALL')reason='All occurrences retained';else if(op==='UNION')reason='One distinct copy';else if(op==='INTERSECT')reason=co?'Present in both':'Not present in both';else reason=co?'Exclusive to '+(op==='REVERSE'?'B':'A'):ca&&cb?'Present in both; excluded':'Not in first query';let tr=document.createElement('tr');for(const v of [n,ca,cb,co,reason]){let td=document.createElement('td');td.textContent=v;tr.append(td);}tbody.append(tr);}if(!tbody.children.length){let tr=document.createElement('tr'),td=document.createElement('td');td.colSpan=5;td.textContent='Both tables are empty.';tr.append(td);tbody.append(tr);}}
function choose(o){op=o;document.querySelectorAll('[data-op]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.op===op)));update();}
function setInputs(a,b){$('a').value=a;$('b').value=b;update();}
$('a').addEventListener('input',update);$('b').addEventListener('input',update);document.querySelectorAll('[data-op]').forEach(b=>b.addEventListener('click',()=>choose(b.dataset.op)));$('reset').onclick=()=>{setInputs('1, 1, 2, 3','2, 3, 3, 4');choose('UNION');};$('swap').onclick=()=>setInputs($('b').value,$('a').value);$('disjoint').onclick=()=>setInputs('1, 1, 2','3, 4, 4');$('same').onclick=()=>setInputs('1, 1, 2','1, 2, 2');$('copy').onclick=async()=>{try{if(!navigator.clipboard)throw Error();await navigator.clipboard.writeText($('query').textContent);$('copyStatus').textContent='SQL copied.';}catch(e){let range=document.createRange();range.selectNodeContents($('query'));let sel=window.getSelection();sel.removeAllRanges();sel.addRange(range);$('copyStatus').textContent='SQL selected. Press Ctrl+C or Command+C to copy.';}};update();
</script></body></html>