Converting data types

Reporting in SQL

Tyler Pernes

Learning & Development Consultant

Chapter goal

Reporting in SQL

"Messy" data types

Reporting in SQL

Issue 1: Type-specific functions

Reporting in SQL

Issue 1: Type-specific functions

Reporting in SQL

Issue 1: Type-specific functions

Reporting in SQL

Issue 2: Combining tables (JOIN)

Reporting in SQL

Issue 2: Combining tables (JOIN)

Reporting in SQL

Issue 2: Combining tables (JOIN)

Reporting in SQL

Issue 2: Combining tables (UNION)

Reporting in SQL

Issue 2: Combining tables (UNION)

Reporting in SQL

Interpreting errors

Type-Specific Function Error:

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

JOIN Error:

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
Reporting in SQL

Solution: Wrap it in a CAST()

Syntax:

CAST(field AS type)

Examples:

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

CASTing for functions

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  |
+-----+

Reporting in SQL

CASTing for 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!

Reporting in SQL

Planning for data type issues

  • Fix as they come up
  • Read error messages!
Reporting in SQL

Planning for data type issues

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  |
+--------------+--------------------+
Reporting in SQL

Data type documentation

Reporting in SQL

Practice time!

Reporting in SQL

Preparing Video For Download...