Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of newlines in a cell value in PostgreSQL

Tags:

sql

postgresql

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.

like image 710
vegas red Avatar asked May 29 '13 08:05

vegas red


People also ask

How to find new line character in PostgreSQL?

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.

What is CHR 10 in Postgres?

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.

What is count (*) in PostgreSQL?

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)

How do I count rows in PostgreSQL?

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.


1 Answers

You can compare the length of the string with newline and with out.

SELECT (LENGTH(description) - LENGTH(REPLACE(description, '\n', '')) FROM `bookinfo`

Trimmed count

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`
like image 108
David Boho Avatar answered Oct 06 '22 14:10

David Boho