…
…
SQL and Database Fundamentals · Lesson 25 / 41 · Type, text, and date conversions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The department head asked for the ECTS-to-credits ratio of every course. You wrote the query, but a course with 5 ECTS and 3 credits shows a ratio of 1 instead of 1.67. The data is fine, and the problem is the type of the numbers.
This is the first lesson of a new unit. In the earlier units you learned to filter data, summarize it, join tables, and split long queries into steps. You can write reports now. In real work, though, data has to pass a check before it goes into a report. The shared rule of this unit is: report data is not used until it is cleaned. The next three lessons are three cleaning jobs on the same report: numbers in this lesson, text in the next one, then dates.
Let's look at the query from the case. It did not fail. It ran and returned a result. The result was just wrong:
| Course | ECTS | Credits | Expected ratio | What the query returned |
|---|---|---|---|---|
| CPR103 | 5 | 3 | 1.67 | 1 |
| CPR101 | 6 | 4 | 1.5 | 1 |
A query that fails at least warns you. A query that returns a wrong number silently ends up in the report, lands on the department head's desk, and turns into a decision. That is why the most important skill in this lesson is to look at a number and ask: "Can this result be right?"
In this lesson you will:
CAST or ::, and put the conversion in the right place.Every column in a table has a data type, and every value in the column is of that type. The type decides two things: which values can be stored in the column and which operations you can do with them. You can subtract one date from another, but you cannot divide a string by a string. You can round a number, but you cannot round a true/false value. These are the types you will use most often in PostgreSQL:
| Type | What it stores | Example from the case |
|---|---|---|
INTEGER (SMALLINT, BIGINT) | Integer | year, credits, ects, midterm |
NUMERIC(p, s) | Exact decimal number; p digits in total, s after the decimal point | gpa NUMERIC(3,2) |
REAL, DOUBLE PRECISION | Approximate (floating-point) number | Not in the case |
VARCHAR(n), TEXT | String; VARCHAR holds at most n characters | student_no VARCHAR(9), |
You do not have to open the table definition to learn the type of a column. The pg_typeof() function tells you the type of any value as text.
Example 1 (case): Five columns of the student table
SELECT pg_typeof(year), pg_typeof(gpa), pg_typeof(first_name), pg_typeof(birth_date), pg_typeof(has_scholarship) FROM student LIMIT 1;
| pg_typeof | pg_typeof | pg_typeof | pg_typeof | pg_typeof |
|---|---|---|---|---|
| integer | numeric | character varying | date | boolean |
(1 row)
character varying is the long name of VARCHAR. You can also guess which type a column should have. Do not look at what the value looks like. Look at what you will do with it.
Which type fits each column best?
For each row, pick its match from the list, then check.
There is one more difference between number types. NUMERIC stores a value exactly. REAL and DOUBLE PRECISION store a number approximately in binary. They are very fast, but they make small errors. You will see this in section 6. A type also has a limit: INTEGER holds numbers between about minus and plus 2.1 billion, and SELECT 2147483647 + 1; gives an integer out of range error. BIGINT exists for larger numbers. You will use these limits in lesson 28, when you create tables.
Division is the place where types surprise people most. The rule is short: the quotient of two integers is again an integer, and everything after the decimal point is dropped. It is not rounded, it is dropped. 7 / 2 gives 3, not 3.5. So where did the other half go? The % (remainder) operator gives it: 7 % 2 gives 1, which means 2 fits into 7 three times and 1 is left over.
Think of it as pizza: 3 people share 8 slices. If you do not cut the slices, everyone gets 2 slices and 2 slices are left over. Integer division is exactly this: the answer to "how many whole slices per person?" If you are willing to cut the slices too, each person gets 2.67 slices. For that, one side of the division must be a decimal number.
Example 2 (not the case): Pizza and 7 / 2
SELECT 7 / 2 AS whole_division, 7 / 2.0 AS decimal_division, 7 % 2 AS remainder, CAST(7 AS NUMERIC) / 2 AS with_cast;
| whole_division | decimal_division | remainder | with_cast |
|---|---|---|---|
| 3 | 3.5 | 1 | 3.5 |
(1 row)
The pizza math follows the same rule: SELECT 8 / 3 AS per_person, 8 % 3 AS left_over, ROUND(8 / 3.0, 2) AS exact_share; gives 2 · 2 · 2.67. When you write 2.0 or 3.0, the number becomes decimal (NUMERIC) and the division is done as decimal division. It is enough if one of the two sides is decimal. PostgreSQL adjusts the other side to match.
What does this query return?
SELECT 7 / 2;This rule is not the same in every language. A calculator and many programming languages give 3.5 for 7 / 2. In PostgreSQL, if the columns are integers, the quotient is an integer too. This is also the cause of the problem in the case: ects and credits are INTEGER, so 5 / 3 returned 1.
Turning a value into another type is called a type cast. There are two ways to write it. The standard SQL way is CAST(value AS type). The short PostgreSQL way is value::type. They do the same job: CAST(ects AS NUMERIC) and ects::numeric are the same thing. The short form is more common. The standard form also works in other databases.
A cast can go in any direction: '42'::integer turns a string into a number, and '42'::integer + 1 gives 43. year::text turns a number into a string, and '2026-11-24'::date turns a string into a date. To fix the ratio in the case, it is enough to cast one side to NUMERIC before the division.
Example 3 (case): ECTS-to-credits ratio
SELECT code, ects, credits, ects / credits AS wrong_ratio, ROUND(ects::numeric / credits, 2) AS ratio FROM course;
| code | ects | credits | wrong_ratio | ratio |
|---|---|---|---|---|
| CPR101 | 6 | 4 | 1 | 1.5 |
| CPR102 | 6 | 4 | 1 | 1.5 |
| CPR103 | 5 | 3 | 1 | 1.67 |
| CPR104 | 5 | 3 | 1 | 1.67 |
| CPR205 | 5 | 3 | 1 | 1.67 |
(first 5 of 33 rows)
ROUND(number, 2) rounds the result to two decimal places. The result table on this site does not show trailing zeros. In another PostgreSQL tool you may see the same value as 1.50. Now break the query yourself and fix it.
Try it now· not graded; doesn't affect progress
When you delete ::numeric, the ratio column goes back to 1: two integers were divided again. When you write credits::numeric, the result does not change, because it is enough for one side to be decimal. It does not matter which one you cast. What matters is that you cast before the division. The next section tests exactly this.
Many people who notice integer division try the same thing: "I'll make the result NUMERIC and that's it." They put the result in parentheses and add ::numeric at the end. The query does not fail, but it is not fixed either.
SELECT code, ROUND((ects / credits)::numeric, 2) AS ratio FROM course LIMIT 3;
| code | ratio |
|---|---|
| CPR101 | 1 |
| CPR102 | 1 |
| CPR103 | 1 |
(3 rows)
What does this query return for CPR103 (5 ECTS, 3 credits)?
SELECT code, ROUND((ects / credits)::numeric, 2) AS ratio FROM course WHERE code = 'CPR103';
Think of it as a measurement: if you cut a piece of fabric with scissors and then measure with a more precise ruler, the piece you cut off does not come back. Integer division cuts off the fraction and throws it away. A cast after that only puts what is left into a different box. The rule: write the cast inside the division, on one of the sides, not on the result of the division.
PostgreSQL is strict about types. Some databases silently convert one side when you compare text with a number. PostgreSQL does not do this in most cases, and it gives an error. Anika Park's student number is 202303001. Try to find her by her number:
OutputSELECT first_name, last_name FROM student WHERE student_no = 202303001;
ERROR: operator does not exist: character varying = integerThe message says that it cannot find an operation to compare the two types: character varying (string) on the left and integer (number) on the right. The student_no column is a string, so you must also write the value as a string, in single quotes: WHERE student_no = '202303001'. This query returns Anika Park.
Why is a student number a string and not a number? Because you never calculate with it: adding two student numbers or averaging them makes no sense. Also, some numbers start with a zero, and a number type removes the leading zero: '0532'::integer gives 532. Phone numbers, postal codes, national ID numbers, and course codes are stored as strings for the same reason. The rule: ask "Will I calculate with this?" If the answer is no, it is a string, even if it is made of digits.
There is one exception: when you join values with ||, PostgreSQL turns a number into a string by itself. first_name || ' (year ' || year || ')' gives Anika (year 4) for Anika Park. Here year is an integer, but it becomes a string during the join. There is no such convenience in a comparison.
Try it now· not graded; doesn't affect progress
Both ways return Anika Park. But the quoted version is more correct. When you cast the column, PostgreSQL has to convert the number of every row in the table one by one. If the column ever gets a value with letters in it, the query fails, and the leading zero of a number is lost again. Fitting the value to the type of the column is always safer than fitting the column to the value.
Not every cast is possible. 'abc'::integer gives this error: invalid input syntax for type integer: "abc". You will often meet this error in cleaning jobs: a column that should hold numbers has a string like "n/a" or "-" in it, and the cast stops at that row. The error message shows the problem value in quotes, which helps you find the row.
Casting a decimal number to an integer behaves differently from integer division: it does not drop the fraction, it rounds to the nearest integer. CAST(3.65 AS INTEGER) gives 4, and CAST(2.5 AS INTEGER) gives 3. Anika Park's grade point average is 3.65, and CAST(gpa AS INTEGER) writes 4 for her. If you want to round to a certain number of decimal places, use ROUND(number, places): ROUND(3.6549, 2) gives 3.65.
Match each expression with its result.
For each row, pick its match from the list, then check.
CAST(3.65 AS INTEGER)ROUND(3.6549, 2)'42'::integer + 1'abc'::integerThe difference between exact and approximate numbers matters when you work with money. The query SELECT 0.1::float + 0.2::float AS approximate, 0.1 + 0.2 AS exact; returns 0.30000000000000004 · 0.3. A float (DOUBLE PRECISION) cannot write 0.1 exactly in binary, so a tiny remainder is left over. This remainder does not matter in a single sum, but in a calculation with thousands of rows the cents drift. NUMERIC stores the value exactly. Use NUMERIC for values that must be exact, such as prices, balances, and grade point averages.
This difference has one more side effect. If you try to fix the ratio with float instead of NUMERIC, you get this error:
OutputSELECT ROUND(ects / credits::float, 2) FROM course;
ERROR: function round(double precision, integer) does not existROUND(number, places), which rounds to a number of decimal places, works only with NUMERIC. "function does not exist" in the message means that there is no such function for these types. The fix is NUMERIC again: ROUND(ects::numeric / credits, 2).
Integer division is most sneaky in grouped queries, because there both sides of the division are results of functions, not columns you wrote yourself. The department head also asked for the share of students with a scholarship in each department. As in lesson 8, you count the scholarship students with SUM(CASE ...) and divide by the number of students in the department.
Example 4 (case): Scholarship share per department
SELECT d.name AS department, SUM(CASE WHEN s.has_scholarship THEN 1 ELSE 0 END) / COUNT(*) AS ratio FROM student s JOIN department d ON d.id = s.department_id GROUP BY d.name;
Result: 7 rows, `ratio` is 0 in every department.
The query returned 0 for every department. What does this mean?
SELECT d.name AS department, SUM(CASE WHEN s.has_scholarship THEN 1 ELSE 0 END) / COUNT(*) AS ratio FROM student s JOIN department d ON d.id = s.department_id GROUP BY d.name;
If the result were read as "nobody has a scholarship", the report would say something completely wrong. If a ratio query gives 0 in every row, look at the types first. If you check with pg_typeof, you see bigint for COUNT(*) and SUM(ects), and numeric for AVG(ects): AVG does decimal division inside, while COUNT and SUM do not. To fix it, make the division decimal. If you want a percentage, multiplying by 100.0 both turns it into a percentage and makes the division decimal.
SELECT d.name AS department, ROUND(SUM(CASE WHEN s.has_scholarship THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) AS pct FROM student s JOIN department d ON d.id = s.department_id GROUP BY d.name ORDER BY pct DESC, department;
| department | pct |
|---|---|
| Software Engineering | 35 |
| Management Information Systems | 29.4 |
| Computer Programming | 28.6 |
| Psychology | 21.7 |
| Business Administration | 16.7 |
| Industrial Engineering | 16.7 |
| New Media and Communication | 10 |
(7 rows)
The place of the multiplication matters too: * 100.0 comes before the division. If you write SUM(...) / COUNT(*) * 100.0, the integer division happens first (0), then 0 is multiplied by 100.0, and you still get 0. The rule from section 4 applies here as well: once the fraction is lost, nothing you do afterward brings it back.
The same trap appears in every database. In the database of the Earbud music app (earbud.sql), which you will use in the last exercise of this lesson, songs are stored in this table:
Outputsong (id INTEGER, title VARCHAR(60), artist_id INTEGER, duration_sec INTEGER, release_year INTEGER)
play (id INTEGER, listener_id INTEGER, song_id INTEGER, played_on DATE, seconds_played INTEGER)The duration is stored in seconds, as an integer. You want to show the duration in minutes in the app.
Example 5 (not the case): From seconds to minutes
SELECT title, duration_sec, duration_sec / 60 AS whole_minutes, ROUND(duration_sec / 60.0, 1) AS minutes FROM song WHERE title = 'Morning Train';
| title | duration_sec | whole_minutes | minutes |
|---|---|---|---|
| Morning Train | 216 | 3 | 3.6 |
(1 row)
216 seconds is 3 minutes and 36 seconds. duration_sec / 60 gives 3 and drops the 36 seconds. When you write 60.0, you get 3.6 minutes. The team of the app also wants to know what percentage of a song was played in each play: play.seconds_played is the time played, and song.duration_sec is the length of the song. If you wrote seconds_played / duration_sec * 100 here, every play that was stopped halfway would show 0. Put the lines of the correct query in order.
Put the query in order: it gives the number of each play, the title of the song, and what percentage of the song was played.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Type errors come in two forms. The first is loud: PostgreSQL gives an error message (operator does not exist, invalid input syntax, function ... does not exist) and the query does not run. These are annoying but harmless, because they do not produce a wrong result. The second is silent: the query runs, the result looks like a nice table, but the numbers are wrong. Integer division is of this second kind, and it is the dangerous one.
Build a few habits to catch the silent error. When you calculate a ratio or a percentage, look at the result column: is it all 0, all 1, or all integers? If so, suspect the types. Calculate one row by hand: you know that 5 / 3 is 1.67, so if the table says 1, the query is wrong. Check the types of both sides of the division with pg_typeof. And calculate every average, ratio, and percentage that goes into a report with NUMERIC, casting before the division.
An average is the sum divided by the count. But when the types differ, the result differs too.
SELECT SUM(ects) AS total, COUNT(*) AS course_count, SUM(ects) / COUNT(*) AS division, ROUND(AVG(ects), 2) AS average FROM course;
| total | course_count | division | average |
|---|---|---|---|
| 167 | 33 | 5 | 5.06 |
(1 row)
167 / 33 is 5 in integer division. AVG returns NUMERIC, so it gives 5.06. If you calculate the average yourself, write SUM(ects)::numeric / COUNT(*).
SELECT first_name, last_name, gpa, CAST(gpa AS INTEGER) AS whole FROM student WHERE student_no = ;
Comparing a string column with a number. Writing the number without quotes when you look up a student by number:
OutputSELECT first_name FROM student WHERE student_no = 202303001;
ERROR: operator does not exist: character varying = integerThe error says that the types of the two sides do not match: student_no is a string (character varying), and 202303001 is a number (integer). Write the value in single quotes: '202303001'. When you see "operator does not exist" in an error message, first look at the types of the two sides you are comparing; the message already tells you both types.
pg_typeof shows it. A value that you never calculate with (student number, phone number) is a string, even if it is made of digits, and it is compared with quotes.7 / 2 = 3); COUNT and SUM also return integers. If a ratio is 0 or 1 in every row, look at the type before you look at the data.CAST(x AS type) or x::type converts a value; write the cast before the division, on one of the sides (ects::numeric / credits). Use NUMERIC for money and grades; ROUND(x, n) works only with NUMERIC.Next lesson: Numbers are done; dirty strings come next. You will clean email addresses with mixed uppercase and lowercase letters and extra spaces.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
first_nameDATE, TIMESTAMP | Date; date and time | birth_date, enrollment_date |
BOOLEAN | true / false | has_scholarship |
| first_name | last_name | gpa | whole |
|---|---|---|---|
| Anika | Park | 3.65 | 4 |
(1 row)
Casting a decimal number to an integer rounds it: 3.65 → 4. It does not cut it off to 3 like integer division.