Lets assume I have an imaginary table named bookInfo
, which contains the following values:
|id |book_name |description |
-----------------------------------
|1 |book 1 |dummy |
|2 |book 2 |harry |
| | |potter |
| | |Part 2 |
|3 |...
The cell value for the description
column of the second record (id = 2
) contains multiple newline character sequences between the "harry" and "potter" keywords like so:
harry \n potter \n part 2
Is there a way to count the number of newline characters in the description
column, e.g. do something like the following:
SELECT (count new line)description FROM bookInfo WHERE id=2;
The prior query should return an integer value of 2
.
And it's much simpler: UPDATE problems SET name = trim(regexp_replace(name, E'\n', ' ', 'g')); regexp_replace(..., 'g') finds all occurances of \n and does the replacing.
The PostgreSQL chr function is used to return the corresponding character against the given code within the argument. Syntax: chr(number) PostgreSQL Version: 9.3.
The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. Syntax: COUNT (* | [DISTINCT] ALL | column_name)
The basic SQL standard query to count the rows in a table is: SELECT count(*) FROM table_name; This can be rather slow because PostgreSQL has to check visibility for all rows, due to the MVCC model.
You can compare the length of the string with newline and with out.
SELECT (LENGTH(description) - LENGTH(REPLACE(description, '\n', '')) FROM `bookinfo`
If you want to count only the newlines in between (without leading and trailing newlines) you can trim them first
SELECT (LENGTH(TRIM(BOTH '\n' FROM description)) - LENGTH(REPLACE(TRIM(BOTH '\n' FROM description), '\n', ''))) FROM `bookinfo`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With