skip to Main Content

I am performing an SQL query in bash like this:

updated_records="select class, subject, teacher  from main_a where date(updated_at) = '2024-03-07';"

after running the query I am getting the results like this

class | subject | teacher -----------+-----------+--------- A123 | maths | John A234 | chemistry | matt goldberg  | bio chemistry  | Hannah  (3 rows)

Please help me to get the correct results, in the following format:

class      | subject   | teacher 
-----------+-----------+--------- 
A123       | maths     | John 
A234       | chemistry | matt goldberg 
           | biology   |  Hannah

2

Answers


  1. you include case statement to replace specific subject values:

    updated_records=$(sqlite database.db <<EOF
    SELECT class,
    CASE
    WHEN subject = ‘bio chemistry’ THEN ‘biology’
    ELSE subject
    END AS subject,
    teacher
    FROM main_a
    WHERE date(updated_at) = ‘2024-03-07’;
    EOF
    )

    Login or Signup to reply.
  2. I would set IFS empty to avoid losing the newlines:

    IFS=''
    result=$(psql -c "SELECT ...")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search