Reporting in SQL
Tyler Pernes
Learning & Development Consultant
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
Syntax:
CAST(field AS type)
Examples:
CAST(birthday AS date)
CAST(country_id AS int)
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 |
+-----+
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!
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