vault backup: 2026-03-31 16:53:06

This commit is contained in:
2026-03-31 16:53:06 -04:00
parent 61d9d5ae39
commit d82948d3f8
14 changed files with 2235 additions and 2069 deletions
+70 -2
View File
@@ -21,8 +21,76 @@ yearly: "[[2026]]"
### Cross Join
[](https://www.sqlshack.com/sql-cross-join-with-examples/)
In [[sql]], the `CROSS JOIN` operation
returns the [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
of two tables.
### ~~add column, update by key~~
```sqlite
CREATE TABLE WireSizes (wire_size TEXT NOT NULL);
INSERT INTO WireSizes VALUES ('#12'), ('#10'), ('#8'), ('#6'), ('#4'), ('#2'), ('#1'), ('#1/0'), ('#2/0');
CREATE TABLE WireMaterials (wire_material TEXT NOT NULL);
INSERT INTO WireMaterials VALUES ('CU'), ('AL');
SELECT wire_size, wire_material
FROM WireSizes
CROSS JOIN WireMaterials;
```
```sqlite
SELECT wire_size||' '||wire_material AS wire_type
FROM WireSizes, WireMaterials; -- implicit cross join
```
### Create Table From Query
`CREATE TABLE _ AS` syntax is intuitive,
```sqlite
CREATE TABLE Wires AS
SELECT wire_size, wire_material
FROM WireSizes, WireMaterials;
```
but it excludes the ability to set constraints.
Use this pattern instead:
```sqlite
CREATE TABLE Wires (
wire_size TEXT NOT NULL,
wire_material TEXT NOT NULL,
PRIMARY KEY (wire_size, wire_material),
FOREIGN KEY (wire_size) REFERENCES WireSizes(wire_size),
FOREIGN KEY (wire_material) REFERENCES WireMaterials(wire_material)
);
INSERT INTO Wires (wire_size, wire_material)
SELECT wire_size, wire_material
FROM WireSizes, WireMaterials;
```
You'd think you could just throw an `AS` after the constraints
and omit the `INSERT` statement, but no.
### Add Columns to Table
for adding data after creating new tables with [[#Cross Join]]
```sqlite
ALTER TABLE Wires
ADD length_specific_dc_resistance_in_milliohms_per_foot FLOAT;
UPDATE Wires
SET length_specific_dc_resistance_in_milliohms_per_foot = CASE
WHEN wire_size = '#8' AND wire_material = 'CU' THEN 0.778
WHEN wire_size = '#6' AND wire_material = 'CU' THEN 0.491
WHEN wire_size = '#4' AND wire_material = 'CU' THEN 0.308
-- ...
ELSE NULL
END;
```
### Resources
* [sqlshack.com](https://www.sqlshack.com/)