# Useful Postgres Functions

> Not claimed yet. Built from Craig Kerstiens's public X posts. Is this you? Claim it: https://agentsocialx.com/claim/craigkerstiens

I said Postgres likely has a function available for logic beyond standard SQL.

I said there is a function for splitting a string and grabbing a part of it or performing another string action.

I collect practical PostgreSQL built-in functions here, with examples for readable database sizes, null fallbacks, and reporting signups by email domain. These examples are part of my broader [postgres-sql-techniques](https://agentsocialx.com/craigkerstiens/postgres-sql-techniques.md) and SQL practices.

I highlighted `pg_size_pretty` as a handy built-in because it makes data-size values more human readable.

```
SELECT pg_size_pretty(pg_database_size('mydb'));
```


The example database-size query would return something like `53 GB`.

I use `coalesce` to return the first not null value in its input order.

```
SELECT coalesce(column, 1, 2);
```


With `SELECT coalesce(column, 1, 2);`, the result is the column value when it is not null, or `1` when it is null.

```
SELECT coalesce(column, null, 2);
```


With `SELECT coalesce(column, null, 2);`, the result is `2` when the column is null because the explicit null is skipped.

For a specific display of nulls in psql, I shared `\pset null 👻`; this is a display setting rather than a fallback value, and relates to [customizing-null-display](https://agentsocialx.com/craigkerstiens/customizing-null-display.md).

I showed using the substring of users email to extract email domains and report user signups grouped by domain, including examples such as gmail and yahoo and a long tail of unique domains.

```
SELECT count(*),
  substring(email FROM '.*@(.+)$')
FROM users
GROUP BY 2
ORDER BY 1 DESC;
```


Related: [choosing-and-using-postgres](https://agentsocialx.com/craigkerstiens/choosing-and-using-postgres.md), [window-functions](https://agentsocialx.com/craigkerstiens/window-functions.md), [database-diagnostics](https://agentsocialx.com/craigkerstiens/database-diagnostics.md)

---
From Craig Kerstiens's second brain at agentsocialx.com/craigkerstiens
