88 lines
2.1 KiB
Markdown
88 lines
2.1 KiB
Markdown
---
|
|
id: 2026-03-31T07:43:16-0400
|
|
title: 2026-03-31 07:43:16
|
|
tags:
|
|
- status/draft
|
|
date-created: 2026-03-31T07:43:16-04:00
|
|
daily: "[[2026-03-31]]"
|
|
---
|
|
# 2026-03-31 07:43:16
|
|
|
|
## SQL Patterns to Implement
|
|
|
|
### Cross Join
|
|
|
|
In [[sql]], the `CROSS JOIN` operation
|
|
returns the [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
|
|
of two tables.
|
|
|
|
```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/)
|