skip to Main Content

I’m encountering an issue with the SQL COUNT function that I need assistance with. Here’s the scenario:

In my database, I have two records with values ‘-try’ and ‘-try2.’ However, when I use the COUNT function in my SQL query, it returns 1 instead of the expected 2.

I’ve attempted to modify the query using the expression VALUES (‘text1’ || ‘ ‘ || ‘text2’);, but it doesn’t seem to affect the count as intended.

This is the example in fiddle

CREATE TABLE example_table (
id SERIAL PRIMARY KEY,
value_column VARCHAR(50)
);

INSERT INTO example_table (value_column) VALUES
('-try'),
('-try2');

SELECT COUNT(*) FROM example_table;

This example works like i wanted to.

its says two in one column

but in my column ist like this

<p>-try</p> <p>-try2</p>

idk how in the example works

CREATE TABLE example_table (
id SERIAL PRIMARY KEY,
value_column VARCHAR(50)
);

INSERT INTO example_table (value_column) VALUES
('<p>-try</p>''<p>-try2</p>');

SELECT COUNT(*) FROM example_table;

2

Answers


  1. This INSERT statement creates one record:

    INSERT INTO example_table (value_column) 
    VALUES ('<p>-try</p>''<p>-try2</p>');
    

    The content of this record is this: <p>-try</p>'<p>-try2</p>

    If you want to insert two records, you need ( and ) and a comma , :

    INSERT INTO example_table (value_column) 
    VALUES ('<p>-try</p>')
          ,('<p>-try2</p>');
    
    Login or Signup to reply.
  2. If you want to store multiple values in a column, use an array type.
    To get the count of things in the array, sum the length of those arrays:

    CREATE TABLE example_table (
      id SERIAL PRIMARY KEY,
      value_column text[] -- define column as an array
    );
    
    INSERT INTO example_table (value_column) VALUES
    ('{<p>-try</p>, <p>-try2</p>}');
    
    SELECT sum(array_length(value_column, 1)) FROM example_table; // outputs 2 
    

    See live demo.

    p.s. the 1 parameter in array_length specifies the depth to traverse (for nested arrays)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search