2025-07-01 20:57:56 +02:00

141 lines
5.2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## ER Modell
>**Chen** Notation:
>- Rechteck = Entity; Beziehung = Diamant; Kardinalität = {0, 1, N, M, 0..1} über der Verbindungslinie; Entities = Ovale (Unterstrichen = Primary-Key; )
- **How Foreign Keys Appear in Chen Notation** 
- **Entities** are drawn as rectangles.
- **Relationships** are drawn as diamonds.
- **Attributes** are ovals connected to their entity or relationship.
- **Primary keys** are underlined in the entitys attribute list.
- **Foreign keys** are not shown as a separate symbol. Instead, they are implied by the relationship between entities.
## SQL
```plsql
INSERT INTO a VALUES (1, 'A'), (2, 'B'), (3, 'C'), (40, 'D'), (50, 'E');
CREATE TABLE a ( id INTEGER PRIMARY KEY, comment CHARACTER VARYING NOT NULL );
```
```plsql
-- [Operators]
-- Comparison: =, <>, !=, <, >, <=, >=
-- Arithmetic: +, -, *, /, %, ^
-- Logical: AND, OR, NOT
-- Pattern Matching: LIKE, ILIKE, SIMILAR TO
-- Regular Expressions: ~ (case-sensitive), ~* (case-insensitive), !~ (not match), !~* (not match)
-- Range: <@ (contains), @> (is contained by), && (overlaps)
-- JSON/JSONB: ->, ->>, #>, #>>
-- Arrays: @>, <@, &&, ||
-- [Date/Time Literals and Functions]
-- Date literals: 'YYYY-MM-DD', 'YYYY-MM-DD HH:MI:SS'
-- Typed literals: DATE 'YYYY-MM-DD', TIMESTAMP 'YYYY-MM-DD HH:MI:SS'
-- to_date('DD.MM.YYYY', 'DD.MM.YYYY')
-- INTERVAL '1 day', '2 hours'
-- NOW(), CURRENT_DATE, CURRENT_TIMESTAMP, EXTRACT(field FROM source), AGE(source, reference)
-- [Aggregate Functions]
-- COUNT(expr), SUM(expr), AVG(expr), MIN(expr), MAX(expr)
-- STDDEV(expr), VARIANCE(expr)
-- STRING_AGG(expr, delimiter), ARRAY_AGG(expr), JSON_AGG(expr)
-- BOOL_AND(expr), BOOL_OR(expr), EVERY(expr)
-- 1. Haupt-Query
SELECT
-- OPTIONAL: UNIQUE / DISTINCT / DISTINCT ON
/* DISTINCT */ -- Einmalige Werte
/* DISTINCT ON (spalte1, spalte2) */
t.spalte1, -- einfache Spalte
t.spalte2 AS alias2, -- aliasierte Spalte
FROM
schema.tabelle1 AS t
-- OPTIONAL: Tabelle sampeln
/* TABLESAMPLE SYSTEM (10) */
-- Verschiedene JOIN-Typen
INNER JOIN schema.tabelle2 AS t2
ON t.fk = t2.id -- INNER JOIN
LEFT OUTER JOIN schema.tabelle3 AS t3
USING (gemeinsame_spalte) -- USING
RIGHT JOIN schema.tabelle4 AS t4
NATURAL LEFT JOIN schema.tabelle5 AS t5
CROSS JOIN schema.tabelle6 -- CROSS JOIN
FULL JOIN LATERAL (
SELECT ...
) AS sub ON true
-- 2. Filter
WHERE
t.spalte1 = 'Wert' -- Gleichheit
AND t.spalte2 LIKE '%muster%' -- Pattern-Matching
AND t.spalte3 IN (1,2,3) -- IN-Liste
AND t.spalte4 BETWEEN 10 AND 20 -- Bereich
AND (t.spalte5 IS NULL OR t.spalte6 IS NOT NULL)
AND t.datum >= DATE '2025-01-01'
AND t.beschreibung ~* 'regex' -- Regex-Operator (case-insensitive)
-- 3. Gruppierung für Aggregate
GROUP BY
t.spalte1,
t.spalte2
-- 4. Filter auf Gruppenebene
HAVING
COUNT(*) > 1
-- 6. Kombinieren mehrerer Queries
/* UNION [ALL] SELECT ... */
/* INTERSECT [ALL] SELECT ... */
/* EXCEPT [ALL] SELECT ... */
-- 7. Sortierung
ORDER BY
t.spalte1 DESC, -- auf- oder absteigend
alias2 ASC
-- OPTIONAL: NULLS FIRST/LAST
/* t.spalte2 NULLS LAST */
-- 8. Paging
LIMIT 10
OFFSET 20
/* FETCH FIRST 10 ROWS ONLY */
;
```
## Normalformen
Vorherige Normalformen sind immer Vorraussetzung
### 1NF Normalform - Zeilen und Spalten erweitern
> - Alle Attribute atomar sind, d.h. jedes Feld enthält nur einen Wert. Mehrere Attribute in einer Spalte werden zu neuen spalten. Mehrere Datensätze vom gleichen Attribut in der Zelle werden zu einer Neuen Zeile.
### 2NF
>Nicht-Schlüsselattribute (Spalten), die eigentlich einen anderen Primärschlüssel haben (sofern der in der Tabelle auch vorhanden), sollte dieser mitsamt diesem in eine eigene Tabelle verlegt werden.
## 3NF
>Gleiches Vorgehen wie bei der 2NF, einziger Unterschied ist, dass der Primärschlüssel ein bereits bestehender Foreign-Key ist.
## Integrität (Constraints)
- Nur erlaubte werte (hauptsächlich eine Zahlen Range) `CREATE TABLE ... price numeric CHECK (price > 0)` oder `... NOT NULL`
- Keine Doppelten Primary-Keys/Zeilen (i.e. Unique ) `CREATE TABLE ... id serial UNIQUE`
- Keine Null-Pointer auf Primary-Keys (Referentielle Integrität)
- **CASCADE** = Alles mit löschen, das darauf referenziert; **RESTRICT** = Nicht Löschen, wenn darauf referenziert.
`CREATE TABLE ... FOREIGN KEY (bestellung_id) REFERENCES <<table_name>> (<<id_column>>) ON UPDATE CASCADE ON DELETE <<CASCADE or RESTRICT>>`
## Konsistenz:
```plsql
BEGIN; <-- Anfang von Transaktion
...
COMMIT; <-- Abschluss von Transaktion
ROLLBACK; <- Abbruch von Transaktion
```
>1. **Atomarität:** Eine Transaktion wird entweder komplett durchgeführt, oder sie hinterlässt keine Spuren ihrer Wirkung auf die Datenbank.
>2. **Konsistenz:** Während der Transaktion können einzelne Konsistenzbedingungen zeitweise verletzt sein, bei Transaktionsende müssen jedoch alle wieder erfüllt sein.
>3. **Isolation:** Das Prinzip der Isolation verlangt, dass gleichzeitig ablaufende Transaktionen dieselben Resultate wie im Falle einer Einbenutzerumgebung erzeugen müssen.
>4. **Dauerhaftigkeit:** Datenbankzustände müssen so lange gültig sein und erhalten bleiben, bis sie von Transaktionen verändert werden.