Build a World Cup Database - Syntax Error

Why am I getting a syntax error when I try to add the winner_id and the opponent_id?

Here’s my insert_data.sh


if [[ $1 == "test" ]]
then
  PSQL="psql --username=postgres --dbname=worldcuptest -t --no-align -c"
else
  PSQL="psql --username=freecodecamp --dbname=worldcup -t --no-align -c"
fi

# Do not change code above this line. Use the PSQL variable above to query your database.

echo $($PSQL "TRUNCATE TABLE games, teams")

cat games.csv | while IFS="," read YEAR ROUND WINNER OPPONENT WG OG
do

  if [[ $WINNER != "winner" ]]
  then 
  WINNER_ID=$($PSQL "SELECT team_id FROM teams WHERE name LIKE '$WINNER'")
      
    if [[ -z $WINNER_ID ]]
    then
    RESULT_INSERT_WINNER=$($PSQL "INSERT INTO teams (name) VALUES ('$WINNER')")
    fi

  fi        

  if [[ $OPPONENT != "opponent" ]]
  then 
  OPPONENT_ID=$($PSQL "SELECT team_id FROM teams WHERE name LIKE '$OPPONENT'")
      
    if [[ -z $OPPONENT_ID ]]
    then
    RESULT_INSERT_OPPONENT=$($PSQL "INSERT INTO teams (name) VALUES ('$OPPONENT')")
    fi
    
  fi

  if [[ $YEAR != "year" ]]
  then
    ADD_DATA=$($PSQL "INSERT INTO games(year, round, winner_id, opponent_id, winner_goals, opponent_goals) VALUES($YEAR, '$ROUND', $WINNER_ID, $OPPONENT_ID, $WG, $OG)")
  fi
done  

Here’s the error I’m getting in the Bash terminal

ERROR:  syntax error at or near ","
LINE 1: ...inner_goals, opponent_goals) VALUES(2018, 'Final', , , 4, 2)
                                                              ^
ERROR:  syntax error at or near ","
LINE 1: ...goals, opponent_goals) VALUES(2018, 'Third Place', , , 2, 0)

There’s more of the same.

Beacuse your wınner_id and opponent_id null when your trying to insert your teams to games table.

Why?
Beacuse your query returns null when you searched for a match from teams table. Thats how can you can test your variable with if { { -z $WINNER_ID ]]. İf it is null, insert the result. If not, pass it.

And winner and opponent id not going to change again beacuse you assaign it before insert to table. Steps going to be like this:

null scenario = search for match —> assaign result to winner_id variable —> it’s null so insert to team → one more time for opponent → insert teams to games table with id → YEAR, ROUND, WINNER_ID (null), OPPONENT_ID (null) , winner_goals, opponent_goals ----> Error beacuse table has not null constraints.

You need to find a way to reassaign these , ı am not going to say it. Good luck :smile: