Update table with multiple fields from another table - postgresql

I am trying to update a field in a table in Postgres called certificate_name by concatenating 3 fields from another table (first_name, middle_name, and last_name). I have tried several statements, but they all throw errors; my most recent attempt was the following:
update candidate_attributes ca
inner join "user" u on u.id=ca.candidate_user_id
set ca.certificate_name = concat(u.first_name, u.middle_name, u.last_name);
I'm getting an error that says:
syntax error at or near "inner"....
What am I doing wrong?

Your syntax isn't valid in Postgres. Resembles SQL Server syntax.
Read the manual on UPDATE and use instead:
UPDATE candidate_attributes ca
SET certificate_name = concat_ws(' ', u.first_name,u.middle_name,u.last_name)
FROM "user" u
WHERE u.id = ca.candidate_user_id;
I also threw in concat_ws() instead of concat(), assuming you want a space between each part of the name.

Related

Trying to select all rows in this column with a certain value, and failing [duplicate]

I'm writing a Java application to automatically build and run SQL queries. For many tables my code works fine but on a certain table it gets stuck by throwing the following exception:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: column "continent" does not exist
Hint: Perhaps you meant to reference the column "countries.Continent".
Position: 8
The query that has been run is the following:
SELECT Continent
FROM network.countries
WHERE Continent IS NOT NULL
AND Continent <> ''
LIMIT 5
This essentially returns 5 non-empty values from the column.
I don't understand why I'm getting the "column does not exist" error when it clearly does in pgAdmin 4. I can see that there is a schema with the name Network which contains the table countries and that table has a column called Continent just as expected.
Since all column, schema and table names are retrieved by the application itself I don't think there has been a spelling or semantical error so why does PostgreSQL cause problems regardless? Running the query in pgAdmin4 nor using the suggested countries.Continent is working.
My PostgreSQL version is the newest as of now:
$ psql --version
psql (PostgreSQL) 9.6.1
How can I successfully run the query?
Try to take it into double quotes - like "Continent" in the query:
SELECT "Continent"
FROM network.countries
...
In working with SQLAlchemy environment, i have got this error with the SQL like this,
db.session.execute(
text('SELECT name,type,ST_Area(geom) FROM buildings WHERE type == "plaza" '))
ERROR: column "plaza" does not exist
Well, i changed == by = , Error still persists, then i interchanged the quotes, like follows. It worked. Weird!
....
text("SELECT name,type,ST_Area(geom) FROM buildings WHERE type = 'plaza' "))
This problem occurs in postgres because the table name is not tablename instead it is "tablename".
for eg.
If it shows user as table name,
than table name is "user".
See this:
Such an error can appear when you add a space in the name of a column by mistake (for example "users ").
QUICK FIX (TRICK)
If you have recently added a field which you have already deleted before and now trying to add the same field back then let me share you this simple trick! i did this and the problem was gone!!
so, now just delete the migration folder entirely on the app,then instead of adding that field you need to now add a field but with the name of which you have never declared on this app before, example if you are trying to add title field then create it by the name of heading and now do the migration process separately on the app and runserver, now go to admin page and look for that model and delete all the objects and come to models back and rename the field that you recently made and name it to which you were wishing it with earlier and do the migrations again and now your problem must have been gone!!
this occurs when the objects are there in the db but you added a field which wasn't there when the earlier objs were made, so by this we can delete those objs and make fresh ones again!
I got the same error when I do PIVOT in RedShift.
My code is similar to
SELECT *
INTO output_table
FROM (
SELECT name, year_month, sales
FROM input_table
)
PIVOT
(
SUM(sales)
FOR year_month IN ('nov_2020', 'dec_2020', 'jan_2021', 'feb_2021', 'mar_2021', 'apr_2021', 'may_2021', 'jun_2021', 'jul_2021', 'aug_2021',
'sep_2021', 'oct_2021', 'nov_2021', 'dec_2021', 'jan_2022', 'feb_2022', 'mar_2022', 'apr_2022', 'may_2022', 'jun_2022',
'jul_2022', 'aug_2022', 'sep_2022', 'oct_2022', 'nov_2022')
)
I tried year_month without any quote (got the error), year_month with double quote (got the error), and finally year_month with single quote (it works this time). This may help if someone in the same situation like my example.

I am not able to create view in PostgreSQL

I am trying to create a view in Postgres. I am using Dbeaver to do so.
my query is as follows:
CREATE VIEW customer_master as
(
select *
from survey_info
full join survey_responses on survey_info.submissionid =survey_responses.submissionid
);
It's throwing an error :
CREATE VIEW customer_master as
SQL Error [42701]: ERROR: column "submissionid" specified more than once.
Anyone faced such an issue?
If you have common columns between joined table, it is required to specify all the columns required using proper aliases.
CREATE VIEW customer_master as
select info.submissionid as submissionid_1,
resp.submissionid as submissionid_2, --Keep one or use
--coalesce if one is null
--i.e coalesce(info.submissionid,resp.submissionid)
info.col2,
info.col3,
resp.col2,
resp.col3
--other columns with aliases
from survey_info info
full join survey_responses resp
on info.submissionid =resp.submissionid

execute multiple DB2 statements with MyBatis

i have searched for some posts related to executing multiple SQL statements with Mybatis. but that didnt work. i need to execute multiple DB2 statements in MyBatis . consider i have to run 3 DELETE statements
i have referred below link . in this post they have given example for Mybatis with ORACLE.
MyBatis executing multiple sql statements in one go, is that possible?
Query syntax :
<delete id="clearTable" parameterType="test">
DELETE FROM tableA WHERE key = #{key}
DELETE FROM tableb WHERE key = #{key} and param = #{param}
DELETE FROM tablec WHERE key = #{key} and param = #{param}
<delete>
error log :
Translating SQLException with SQL state '42601', error code '-199', message [[SQL0199] Keyword DELETE not expected. Valid tokens: OR USE SKIP WAIT WITH.]; SQL was [] for task [
Error updating database. Cause: java.sql.SQLException: [SQL0199] Keyword DELETE not expected. Valid tokens: OR USE SKIP WAIT WITH.
SQL: DELETE FROM tableA WHERE key = ? DELETE FROM tableb WHERE key = ? and param = ? DELETE FROM tablec WHERE key = ? and param = ?
Cause: java.sql.SQLException: [SQL0199] Keyword DELETE not expected. Valid tokens: OR USE SKIP WAIT WITH.
Thanks in Advance
MyBatis appears to expect a single line for its SQL statements. I don't use MyBatis, but I use DB2. Try either calling a stored procedure (and pass it the key-values of items to delete), or try an anonymous block.
begin atomic
DELETE FROM tableA WHERE key = 1 ;
DELETE FROM tableb WHERE key = 2 and param = 1 ;
DELETE FROM tablec WHERE key = 3 and param = 1 ;
end#
The above syntax is valid for DB2 Linux/Unix/Windows current versions (v10.5 or v11.1 ) - you would replace the literal values with the MyBatis (or whatever) parameter-markers.
One detail is that the syntax above has two delimiters, one is the statement delimiter (which in my example is #), the other is the intra-statement delimiter (which in my example is ;) and DB2 lets you configure both of these delimiters , so you might need to give at least one of those details to DB2 somehow when opening the connection from MyBatis.

Update table with value from another table

I try to update value from one table with another table by use IP_ID to compare 2 table by following sybtax
UPDATE EDWID02.CUSTOMER_MOBILE t1
SET T1.MOBILE = (
SELECT T2.MOBILE
FROM EDWID02.NEW_MOBILE t2
WHERE T1.IP_ID=T2.IP_ID)
The error I found was DB2 Database Error:
ERROR [21000] [IBM][DB2/AIX64] SQL0811N The result of a scalar fullselect,
SELECT INTO statement, or VALUES INTO statement is more than one row.
SQLSTATE=21000
even I change = to in it's told me another error DB2 Database Error:
ERROR [42601] [IBM][DB2/AIX64] SQL0104N An unexpected token "in" was found
following "t1 SET T1.MOBILE". Expected tokens may include: "=".
SQLSTATE=42601
I am coding in DB2.
your misunderstanding
'UPDATE t1 SET value=onevalue'
onevalue needs to be a single value. You may achieve this by (SELECT value FROM t2 WHERE t1.id = t2.id FETCH FIRST 1 ROW ONLY)

Nested query as PostGIS function parameter

I have a PostGIS query where I really need to have nested queries inside PostGIS function calls:
UPDATE raw.geocoding
SET the_geom = ST_Centroid(
ST_Collect(
SELECT the_geom
FROM raw.geocoding
WHERE hash = ((E'0101000020090C000081610F9CC5DC3341EE672E6E723B3241')::varchar),
SELECT the_geom
FROM raw.geocoding
WHERE hash = ((E'0101000020090C00002CF887E0C5DC3341C9E5B2DF2A383241')::varchar)
)
)
WHERE hash = ((E'3e638a27c6c38f05026252f4a0b57b2e')::varchar)
Unfortunately, this doesn't work. I get a syntax error at the beginning of the nested query:
ERROR: syntax error at or near "SELECT"
LINE 4: SELECT the_geom
^
********** Error **********
ERROR: syntax error at or near "SELECT"
SQL state: 42601
Character: 86
Looks like I cannot have a nested query as a PostGIS function parameter?
I've perused through the PostGIS documentation and cannot find any clear guidance for dealing with this.
It appears Postgres has a way of doing variables in pgSQL, but it's unclear to me how this would be pulled off in a standard query. This is a query that will be run tens or hundreds of thousands of times from a C# program. That aside, I could do a pgSQL stored procedure if required; just wanted to make sure there wasn't a simpler alternative first.
In case you were wondering, the query looks messy because it's the result of a npgsql-generated parameterized query. I think it's fair to say that npgsql is being extra-cautious with redundant typing and escaping.
I am running PostGIS 2.0.1, Postgres 9.1.5, and npgsql 2.0.12.
It sounds like you want a scalar subquery, an expression written like (SELECT ....) (note enclosing parentheses) that contains a query returning either zero rows (NULL result) or one field from one row.
You were most of the way there, you just needed the parens:
UPDATE raw.geocoding
SET the_geom = ST_Centroid(
ST_Collect(
(SELECT the_geom
FROM raw.geocoding
WHERE hash = ((E'0101000020090C000081610F9CC5DC3341EE672E6E723B3241')::varchar)),
(SELECT the_geom
FROM raw.geocoding
WHERE hash = ((E'0101000020090C00002CF887E0C5DC3341C9E5B2DF2A383241')::varchar))
)
)
WHERE hash = ((E'3e638a27c6c38f05026252f4a0b57b2e')::varchar)
Note that subqueries can be used in other places too - table returning subqueries can appear in FROM, for example. The PostgreSQL manual teaches about all this, and is well worth a cover-to-cover read.
If you're doing a lot of these updates, you may find it more efficient to formulate the UPDATE as a join using the PostgreSQL extension UPDATE ... FROM ... WHERE rather than running lots of individual UPDATEs over and over. I just wanted to raise the possibility. See from-list in UPDATE