Strings, Dates, and Types: Getting Data into Shape

Data Types and CAST: Telling the Database What It Has

44 min

Chapter 6 — “The Languages of Time”

The fifth clearance took you through the archive’s nested rooms. You learned how to choose a route: a , EXISTS, a , or set operations. But deeper inside Vault-9, you encounter a new obstacle.

Kotomarket’s logs speak different machine languages.

Time is stored as timestamps:

2024-03-17 09:42:11

Money is stored as fixed-precision numbers:

13.00

Product quantities are stored as integers:

5

Names, emails, and categories are stored as strings:

'Electronics'

To us, all of this is simply “data.” To PostgreSQL, every value follows the rules of its type.

QUERY: Archive physics, cadet. Every value has a type — the law it lives by. Mix up those laws, and the archive will answer honestly, just not the question you meant to ask.

A cadet at the archive console as capsules containing values of different types pass through a glowing type-casting prism
CAST is the archive’s built-in translator: the same value, under a different set of type rules.

Every value has a type

PostgreSQL always knows what kind of value it is working with: a number, a string, a date, a time, or another data type.

The type determines:

  • which operations are allowed;
  • how values are compared;
  • what kind of result a calculation returns;
  • whether an index can be used;
  • whether an explicit conversion is required.

In Kotomarket, you’ll keep running into types like these.

Numbers:

price NUMERIC(10,2)
stock INTEGER
quantity INTEGER

Strings:

full_name VARCHAR
email VARCHAR
category VARCHAR

Dates and times:

signup_date DATE
created_at TIMESTAMP

A type is more than a label. It defines how a value behaves.

For example, quantity is an INTEGER, so you can add it and divide it as a number. But you can’t compare an email stored as TEXT or VARCHAR with a number without making an explicit choice: the database should not have to guess what you mean.

What CAST is

Sometimes you need to convert a value from one type to another.

For example:

  • convert a price with decimal places to an integer type;
  • turn a number into text for a label;
  • turn the string '2024-03-17' into a date;
  • cast an integer to NUMERIC so division returns a fractional result.

This conversion is called a type cast, or CAST.

SQL has a standard form:

CAST(price AS INTEGER)

PostgreSQL also has a shorter form:

price::INTEGER

Both expressions cast the value in price to INTEGER.

For example:

SELECT
  name,
  price,
  CAST(price AS INTEGER) AS price_int_standard,
  price::INTEGER AS price_int_pg
FROM products
ORDER BY id
LIMIT 5;

CAST(...) is the more portable form. It follows the more closely and is a better choice when code may need to run on different DBMSs.

:: is PostgreSQL shorthand. It is common in analytical queries because it is compact and easy to read when you know the code will run in PostgreSQL.

CAST doesn’t always mean “round correctly”

Do not confuse type casting with business rules for rounding.

When you cast a NUMERIC value to INTEGER, PostgreSQL converts it to an integer. But if you need a specific rule — round up, round down, round to two decimal places, or drop the fractional part — use the functions designed for that job.

For example:

SELECT
  price,
  ROUND(price) AS rounded_price,
  FLOOR(price) AS floor_price,
  CEIL(price) AS ceil_price,
  TRUNC(price) AS trunc_price
FROM products
ORDER BY id
LIMIT 5;

CAST controls the type.

ROUND, FLOOR, CEIL, and TRUNC define how the value is rounded.

When you need CAST in a query

CAST commonly appears in three situations.

1. You need to change the result type

For example, show a price as an integer:

SELECT
  name,
  price,
  price::INTEGER AS price_int
FROM products;

2. You need to build a text label

For example, combine text with a number:

SELECT
  name,
  'Stock: ' || stock::TEXT AS stock_label
FROM products;

The || operator concatenates strings, so the numeric stock value needs to be cast to text first.

3. You need to fix division

A common practical case is calculating metrics.

If you divide one integer by another, PostgreSQL performs integer division.

SELECT 7 / 2 AS result;

The result is:

3

Not 3.5, but exactly 3.

The fractional part disappears because both operands are integers.

To get a fractional result, cast at least one operand to a type that supports fractional values:

SELECT 7::NUMERIC / 2 AS result;

Now the result is:

3.5000000000000000

This matters especially when you calculate real metrics.

Suppose you need the average number of items per order:

SELECT
  SUM(quantity) / COUNT(DISTINCT order_id) AS avg_items_per_order
FROM order_items;

If SUM(quantity) and COUNT(...) both return integers, the result can also be an integer, with the fractional part lost.

A better version explicitly casts one operand to NUMERIC:

SELECT
  SUM(quantity)::NUMERIC / COUNT(DISTINCT order_id) AS avg_items_per_order
FROM order_items;

SQL now calculates the metric as a fractional number.

Type changes the meaning of the result

Values that look similar can behave differently depending on their types.

SELECT 7 / 2;

This is integer division.

SELECT 7::NUMERIC / 2;

This is fractional division.

SELECT '7' || '2';

This is string concatenation, so the result is '72'.

PostgreSQL treats these as different kinds of data. Numbers are divided, strings are concatenated, and dates are compared by the calendar. If you use the wrong type, a query can be syntactically valid and still answer the wrong question.

DECIMAL59.90CASTINTEGER60::INTEGER — shorthand
One value, different types: CAST moves it between numbers, strings, and dates, changing the rules it follows.
SELECT
  name,
  price,
  CAST(price AS INTEGER) AS price_int,
  price::INTEGER AS price_int_short
FROM products
ORDER BY id
LIMIT 5;
Practice: write the query
Show cancelled orders without the time component: from orders, select rows where status = 'cancelled' and return id plus created_at cast to DATE with the alias order_date.
Column names and their order are not checked — the values are compared.
SELECT id, created_at
FROM orders;

Integer division cuts off the fractional part.

If you divide an INTEGER by an INTEGER, PostgreSQL returns an integer:

SELECT 591 / 120 AS result;

The result is 4, not 4.925.

This is dangerous in metrics because the query does not fail, but the answer is wrong.

To get a fractional result, cast one operand to a type that supports fractional values:

SELECT 591::NUMERIC / 120 AS result;

The same rule applies to :

SELECT
  SUM(quantity)::NUMERIC / COUNT(DISTINCT order_id) AS avg_items_per_order
FROM order_items;

Casting one operand is enough. PostgreSQL handles the other operand as needed for the calculation.

Implicit casts: a translator that works without being asked

Sometimes PostgreSQL chooses a suitable type on its own.

For example, you can add numbers of different types:

SELECT 1 + 1.5 AS result;

The integer 1 is converted to a more suitable numeric type, so the result is fractional.

This is a safe case because both values are still numbers.

A quoted literal isn’t always the same as a text column

You need to distinguish a string from a value stored in a TEXT column.

When you write:

WHERE id = '42'

PostgreSQL sees that id is a numeric column while '42' is a literal. That literal can be converted once to the column’s type, so the condition can work normally.

In effect, the database treats it as:

WHERE id = 42

Comparing an actual text value with a number is different.

SELECT '42'::TEXT = 42;

PostgreSQL will not do this. It has no comparison operator for text = integer.

This protects you from an ambiguous conversion: the database will not guess whether to turn the number into text or the text into a number.

Why PostgreSQL is stricter than MySQL

Some SQL dialects, especially MySQL, perform more implicit casts.

For example, suppose you compare the string column phone with a number:

WHERE phone = 89001234567

MySQL may try to convert values in the string column to numbers.

At first, that seems convenient because the query “works.”

But that convenience has a cost.

First, the conversion happens for every row.

Second, a regular index on phone may stop helping because the comparison is no longer against the raw column value but against an expression based on it.

Third, the result can be surprising. Strings that begin with digits may be converted to numbers in ways you would not expect, so a search can return extra matches.

PostgreSQL is more likely to raise an error in this situation. The error immediately shows that the types do not match.

The correct query for a phone number stored as text compares a string with a string:

WHERE phone = '89001234567'

The column stays a string, the condition expresses the intended meaning precisely, and an index on phone can be used.

The main cost of CAST depends on where you apply it

Not all casts are equally risky.

Casting a constant is usually fine:

WHERE created_at >= TIMESTAMP '2024-03-17 00:00:00'

The constant is converted once. The database does not need to recalculate it for every row in the table.

Casting a column is often a bad idea:

WHERE created_at::DATE = DATE '2024-03-17'

Here the database has to take created_at from each row, convert it to DATE, and then compare it with the date.

The query is easy to read, but a regular index on created_at may no longer be used efficiently because the column is no longer “clean.” The database sees the expression created_at::DATE, not created_at itself.

The archivist’s rule:

convert the constant, not the column.

Bad version:

WHERE created_at::DATE = DATE '2024-03-17'

Better version:

WHERE created_at >= TIMESTAMP '2024-03-17 00:00:00'
  AND created_at <  TIMESTAMP '2024-03-18 00:00:00'

Here the created_at column stays untouched. The range starts at midnight on March 17, inclusive, and ends at midnight on March 18, exclusive.

This filter usually works better with an index on created_at.

Why not BETWEEN

You may be tempted to write this:

WHERE created_at BETWEEN TIMESTAMP '2024-03-17 00:00:00'
                     AND TIMESTAMP '2024-03-17 23:59:59'

But with timestamps, this is less reliable.

First, timestamps can contain fractional seconds:

2024-03-17 23:59:59.500

That value is later than 23:59:59, even though it still falls on March 17.

Second, a range from “the start of the day, inclusive” to “the start of the next day, exclusive” is easier to extend and reuse:

WHERE created_at >= TIMESTAMP '2024-03-17 00:00:00'
  AND created_at <  TIMESTAMP '2024-03-18 00:00:00'

This is the standard safe pattern for filtering by day when a column stores both a date and a time.

CAST in SELECT and CAST in WHERE are not the same thing

A CAST in the SELECT list is usually used for output:

SELECT
  name,
  price::INTEGER AS price_int
FROM products;

It changes how the value appears in the result.

A CAST in WHERE affects which rows are found:

WHERE created_at::DATE = DATE '2024-03-17'

Be especially careful here because a function or cast applied to a column can make an index less useful.

For now, remember this rule: when you filter a table, try to leave the column on the left in its native type and cast the constants or range boundaries instead.

We’ll examine why this matters for indexes in the optimization chapter. For now, focus on building the right habit.

Find and fix the bug
You need the average number of items per order, but the result came out as a whole integer, so the fractional part was lost.
SELECT SUM(quantity) AS total_units,
       COUNT(DISTINCT order_id) AS orders_cnt,
       SUM(quantity) / COUNT(DISTINCT order_id) AS units_per_order
FROM order_items;
Interview question

Interview question: A query like WHERE phone = 89001234567 against a string column works in MySQL, but it’s slow and sometimes returns extra matches, while PostgreSQL raises an error. Why?

Strong answer: Because it compares different types: a string column and a number.

MySQL may perform an implicit cast by converting values from the string column phone to numbers and then comparing the numeric values. That means the conversion happens for every row, a regular index on phone may not be used efficiently, and the result can be surprising: strings that begin with digits may match in ways you would not expect.

PostgreSQL is stricter. It does not guess how to compare text and integer, so it raises an error. That prevents a search from silently returning the wrong results.

The correct approach is to compare the string column with a string:

WHERE phone = '89001234567'

The types now match, the column stays “clean,” and the index on phone can work normally.

Interview question: What’s the difference between CAST(x AS INT) and x::INT?

Strong answer: In PostgreSQL, they mean the same thing: both cast the value x to INT.

The difference is syntax. CAST(x AS INT) is the standard SQL form, so it is better for portable code that may need to run on different DBMSs. x::INT is PostgreSQL shorthand. It is compact and common in analytical queries, but it is specific to PostgreSQL.

Interview question: Why is it better to rewrite the condition created_at::DATE = DATE '2024-03-17'?

Strong answer: Because created_at::DATE applies a cast to the column. The database has to calculate that expression for rows in the table, and a regular index on created_at may be used less effectively.

It is better to keep the column in its original type and define a range:

WHERE created_at >= TIMESTAMP '2024-03-17 00:00:00'
  AND created_at <  TIMESTAMP '2024-03-18 00:00:00'

This finds all events from March 17 without losing timestamp precision and leaves the column suitable for index use.

Check yourself
What does 7 / 2 return if both operands are integers?