Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add SQL docs for the CAST and TRY_CAST functions #17214

Merged
merged 1 commit into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions py-polars/docs/source/reference/sql/functions/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,11 @@ SQL Functions
trigonometry

.. grid-item-card::

**Types**
^^^^^^^^^

.. toctree::
:maxdepth: 2

types
90 changes: 90 additions & 0 deletions py-polars/docs/source/reference/sql/functions/types.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
Types
=====

.. list-table::
:header-rows: 1
:widths: 20 60

* - Function
- Description
* - :ref:`CAST <cast>`
- Convert a value to a different datatype.
* - :ref:`TRY_CAST <try_cast>`
- Convert a value to a different datatype, returning NULL if the conversion fails.


.. _cast:

CAST
----
Convert a value to a different datatype.

Note that the more compact PostgreSQL `<expr>::type` syntax is also supported.

**Example:**

.. code-block:: python

df = pl.DataFrame(
{
"foo": [20, 10, 30],
"bar": ["1999-12-31", "2012-07-05", "2024-01-01"],
}
)
df.sql("""
SELECT
foo::float4,
bar::date
FROM self
""")
# shape: (3, 2)
# ┌──────┬────────────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ f32 ┆ date │
# ╞══════╪════════════╡
# │ 20.0 ┆ 1999-12-31 │
# │ 10.0 ┆ 2012-07-05 │
# │ 30.0 ┆ 2024-01-01 │
# └──────┴────────────┘


.. _try_cast:

TRY_CAST
--------
Convert a value to a different datatype, returning `NULL` if the conversion fails.

**Example:**

.. code-block:: python

df = pl.DataFrame(
{
"foo": [65432, 101010, -33333],
"bar": ["1999-12-31", "N/A", "2024-01-01"],
}
)
df.sql("""
SELECT
TRY_CAST(foo AS uint2),
TRY_CAST(bar AS date)
FROM self
""")
# shape: (3, 2)
# ┌───────┬────────────┐
# │ foo ┆ bar │
# │ --- ┆ --- │
# │ u16 ┆ date │
# ╞═══════╪════════════╡
# │ 65432 ┆ 1999-12-31 │
# │ 10101 ┆ null │
# │ null ┆ 2024-01-01 │
# └───────┴────────────┘

Note that with a regular `CAST` this would fail with the following error:

.. code-block::

InvalidOperationError:
conversion from `i64` to `u16` failed in column 'foo' for 1 out of 3 values: [-33333]