CAST e ::

Converte un valore in un altro tipo di dato.

Sintassi

CAST(value AS type)
value::type
  • La forma :: è solo di PostgreSQL. CAST funziona in ogni database.

Esempio

SELECT name, CAST(unit_price AS integer) AS whole_price FROM products ORDER BY product_id;

Prezzi arrotondati a numeri interi.

Tabelle usate: products. Provalo in una lezione qui sotto.

Errori comuni

  • Convertire un decimale in intero arrotonda; non tronca.
  • In PostgreSQL, un intero diviso per un intero dà un intero: 7 / 2 dà 3. Converti un lato in numeric per ottenere 3.5.

Esercitati