SQLSQL

SQL: Basics – code examples

Contents

Hello World

Basics#select#hello#outputCompare in all languages
Use case: Check that the database connection works and a statement gets executed.
SELECT 'Hello World' AS gruss;

SQL has no print: output is result rows. A SELECT without FROM returns one row with the given expressions (not in Oracle, which needs FROM dual).

Constants via CTE and Type Conversion

Basics#cte#type#cast#constantCompare in all languages
Use case: Define recurring values such as tax rate or currency in one place instead of scattering them across the query.
WITH konstanten AS (
  SELECT 0.19 AS mwst, 'EUR' AS waehrung
),
ware AS (
  SELECT 'Laptop' AS name, 999.00 AS netto
)
SELECT name,
       netto,
       ROUND(netto * (1 + mwst), 2) AS brutto,
       CAST(netto AS INTEGER)       AS netto_ganzzahl,
       waehrung
FROM ware, konstanten;

SQL has no variables like programming languages; every column has a fixed type (INTEGER, TEXT, NUMERIC …). Values you need several times go into a CTE and are used via a cross product. CAST converts the type. Procedural variables exist only in dialect extensions (PL/pgSQL, MySQL SET @x).

Handling NULL Safely

Basics#null#coalesce#nullif
Use case: Replace missing values in reports with defaults and avoid division by zero.
SELECT name,
       COALESCE(stadt, 'unknown') AS stadt,
       stadt IS NULL                AS ohne_stadt
FROM kunden;

SELECT 10.0 / NULLIF(0, 0) AS sicher;   -- NULL instead of an error

COALESCE returns the first non-NULL value, NULLIF(a, b) turns a specific value into NULL. Always compare with NULL via IS NULL.