diff --git a/README.md b/README.md index dbfc16e..17583b0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1580 TILs and counting..._ +_1581 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -899,6 +899,7 @@ See some of the other learning resources I work on: - [Timestamp Functions](postgres/timestamp-functions.md) - [Toggling The Pager In PSQL](postgres/toggling-the-pager-in-psql.md) - [Track psql History Separately Per Database](postgres/track-psql-history-separately-per-database.md) +- [Trim Leading And Trailing Space From String](postgres/trim-leading-and-trailing-space-from-string.md) - [Truncate All Rows](postgres/truncate-all-rows.md) - [Truncate Tables With Dependents](postgres/truncate-tables-with-dependents.md) - [Turning Timing On](postgres/turn-timing-on.md) diff --git a/postgres/trim-leading-and-trailing-space-from-string.md b/postgres/trim-leading-and-trailing-space-from-string.md new file mode 100644 index 0000000..2cf6ef2 --- /dev/null +++ b/postgres/trim-leading-and-trailing-space-from-string.md @@ -0,0 +1,44 @@ +# Trim Leading And Trailing Space From String + +PostgreSQL has a bunch of [string +functions](https://www.postgresql.org/docs/current/functions-string.html), +including several for doing various string trimming. + +We can use the simplest form of `trim` to remove leading and trailing space +characters from a string. The syntax for calling `trim` is a bit odd relative +to other PostgreSQL functions and functions in other languages. + +Here is the "grammar" as described in the docs: + +``` +trim ( [ LEADING | TRAILING | BOTH ] [ characters text ] FROM string text ) → text +``` + +We pick `leading`, `trailing`, or `both`, with `both` being the default. Then +we specify the character(s) we want to remove. This is also optional, the +default being the space character. Then we say `from` what string we want to +trim those characters. + +Here we remove all sequential spaces from `both` ends of the given string: + +```sql +> select trim(both from ' Taco Cat '); ++----------+ +| btrim | +|----------| +| Taco Cat | ++----------+ +``` + +To further demonstrate how `trim` works, here we remove all sequences made up +of any of spaces, uppercase `T`, and lowercase `t` from `both` ends of the +string: + +```sql +> select trim(both ' Tt' from ' Taco Cat '); ++--------+ +| btrim | +|--------| +| aco Ca | ++--------+ +```