Basics
- How to Insert
- How to Update
- How to Delete
- How to Trim Strings
- How to Use substring()
- How to Use substring() with RegEx to Extract a String
- How to Replace Substrings
- How to Modify Arrays
- How to Compare Arrays
- How to Concatenate Strings
- How to Convert the Case of a String
- How to Create an Array
- How to Insert Data Into an Array
- How to Query Arrays
- How to Use string_agg()
Database Management
- How to Create a Table
- How to Drop a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Change a Column Name
- How to Add a Default Value
- How to Remove a Default Value From a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Add an Index
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Reset Sequence
- How to Drop a Column
Dates and Times
Analysis
- How to Use nullif()
- How to Use Lateral Joins
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Use generate_series to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV using Copy
- How to Compare Two Values When One Is Null
- How to Use Coalesce
- How to Write a Case Statement
- How to Use Filter to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
- How to Query a JSON Column
How to Do Type Casting in PostgreSQL
Type casting allows you to convert a value from one data type to another in PostgreSQL. This is useful when working with mixed data, performing calculations, or ensuring compatibility across queries.
1. Using the CAST
function
The most explicit way to cast types in PostgreSQL is with the CAST
function:
SELECT CAST('123' AS INTEGER);
This will convert the string '123'
into an integer.
2. Using the double colon (::
) shorthand
PostgreSQL also allows a more concise syntax using the ::
operator:
SELECT '123'::INTEGER;
This produces the same result as CAST()
and is widely used in PostgreSQL queries.
3. Casting in table queries
You can cast columns in your queries, for example:
SELECT price::NUMERIC FROM products;
This ensures the price
column is treated as a numeric value.
4. Common use cases
- Converting strings to numbers for calculations
- Converting timestamps to dates
- Casting JSON values to text or arrays
5. Tips and pitfalls
'abc'
to an integer.
To avoid errors:
- Validate data before casting
- Use
NULLIF()
orCOALESCE()
to handle unexpected values
6. Example with COALESCE
SELECT COALESCE(NULLIF(column, ''), '0')::INTEGER FROM my_table;
7. Summary
PostgreSQL provides powerful type casting tools that make your queries flexible and robust.
Use CAST()
or ::
as needed, but always check your data to prevent unexpected errors.