2.2 KiB
2.2 KiB
id, aliases, title, tags, dg-publish, date-created, daily, weekly, monthly, quarterly, yearly
| id | aliases | title | tags | dg-publish | date-created | daily | weekly | monthly | quarterly | yearly | ||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2026-03-31T07:43:16-04:00 | 2026-03-31 07:43:16 |
|
true | 2026-03-31T07:43:16-04:00 | 2026-03-31 | 2026-W14 | 2026-03 | 2026-Q1 | 2026 |
2026-03-31 07:43:16
SQL Patterns to Implement
Cross Join
In sql, the CROSS JOIN operation
returns the cartesian product
of two tables.
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;
SELECT wire_size||' '||wire_material AS wire_type
FROM WireSizes, WireMaterials; -- implicit cross join
Create Table From Query
CREATE TABLE _ AS syntax is intuitive,
CREATE TABLE Wires AS
SELECT wire_size, wire_material
FROM WireSizes, WireMaterials;
but it excludes the ability to set constraints.
Use this pattern instead:
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
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;