Gegevenstypen converteren

Rapporteren in SQL

Tyler Pernes

Learning & Development Consultant

Hoofddoel

Rapporteren in SQL

‘Rommelig’ gegevenstypen

Rapporteren in SQL

Probleem 1: Type-specifieke functies

Rapporteren in SQL

Probleem 1: Type-specifieke functies

Rapporteren in SQL

Probleem 1: Type-specifieke functies

Rapporteren in SQL

Probleem 2: Tabellen combineren (JOIN)

Rapporteren in SQL

Probleem 2: Tabellen combineren (JOIN)

Rapporteren in SQL

Probleem 2: Tabellen combineren (JOIN)

Rapporteren in SQL

Probleem 2: Tabellen combineren (UNION)

Rapporteren in SQL

Probleem 2: Tabellen combineren (UNION)

Rapporteren in SQL

Fouten interpreteren

Fout: type-specifieke functie

SELECT AVG(first_name)
FROM athletes;
ERROR: Function avg(character varying) does not exist

JOIN-fout:

SELECT country, continent
FROM countries AS c1
JOIN continents AS c2
ON c1.continent_id = c2.id;
ERROR: Operator does not exist: integer = character varying
Rapporteren in SQL

Oplossing: wikkel in CAST()

Syntaxis:

CAST(field AS type)

Voorbeelden:

CAST(birthday AS date)
CAST(country_id AS int)
Rapporteren in SQL

CAST voor functies

SELECT DATE_PART('month',birthdate)
FROM birthdates;
ERROR: Can't run DATE_PART on string.
SELECT DATE_PART('month', 
       CAST(birthdate AS date)) 
FROM birthdates;
+-----+
| 04  |
| 05  |
+-----+

Rapporteren in SQL

CAST voor JOINs

SELECT a.id, b.id
FROM table_a AS a
JOIN table_b AS b
ON a.id = b.id;
ERROR: Cannot join ON varchar = int.
SELECT a.id, b.id
FROM table_a AS a
JOIN table_b AS b
ON a.id = CAST(b.id AS varchar);
Query Ran Successfully!

Rapporteren in SQL

Plannen voor typeproblemen

  • Los ze op zodra ze verschijnen
  • Lees foutmeldingen!
Rapporteren in SQL

Plannen voor typeproblemen

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'countries';
+--------------+--------------------+
| column_name  | data_type          |
|--------------|--------------------|
| id           | integer            |
| country      | character varying  |
| region       | character varying  |
+--------------+--------------------+
Rapporteren in SQL

Documentatie gegevenstypen

Rapporteren in SQL

Laten we oefenen!

Rapporteren in SQL

Preparing Video For Download...