Return zero if no record is found

You could: SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1 INTO res; This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table. Plain queries without aggregate would return no row in such a case. COALESCE would never be … Read more

Return first element in array_agg()

It was actually a mistake from my part… the answer to my first question lies in that query itself. I just have to enclose the (array_agg(team_name))[1], earlier I tried it without the brackets. SELECT team_id, (array_agg(team_name))[1] AS teamname, array_agg(player_id||’##’||player_name) AS playerdetails FROM team INNER JOIN players ON team_id = player_team GROUP BY team_id

Remove only leading or trailing carriage returns

Find the first character that is not CHAR(13) or CHAR(10) and subtract its position from the string’s length. LTRIM() SELECT RIGHT(@MyString,LEN(@MyString)-PATINDEX(‘%[^’+CHAR(13)+CHAR(10)+’]%’,@MyString)+1) RTRIM() SELECT LEFT(@MyString,LEN(@MyString)-PATINDEX(‘%[^’+CHAR(13)+CHAR(10)+’]%’,REVERSE(@MyString))+1)

SQL – HINT to reference a column

When you imported this “Northwind” database column names were imported in CamelCase – your import must’ve added double quotes to column identifiers to create table queries. This is rather unfortunate, as this would cause that you’d have to quote them also in all queries, like: select “City” from customers; To remain sane I’d suggest you … Read more

Is SELECT or INSERT in a function prone to race conditions?

It’s the recurring problem of SELECT or INSERT under possible concurrent write load, related to (but different from) UPSERT (which is INSERT or UPDATE). This PL/pgSQL function uses UPSERT (INSERT … ON CONFLICT ..) to INSERT or SELECT a single row: CREATE OR REPLACE FUNCTION f_tag_id(_tag text, OUT _tag_id int) LANGUAGE plpgsql AS $func$ BEGIN … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)