Syntax error in where clause in postgresql - postgresql

fl=s.executeUpdate("
insert into demi(rno,subcode,subname,intm,extm,crd,resultdate)
values(
'13JG1A05A0',
'RT22058',
' FREE OPEN SOURCE SOFTWARE(FOSS) LAB ',
'20',
'70',
'2',
'MAY 2015'
)
end where not exists(SELECT * FROM demi WHERE rn0 ='13JG105A0' AND subcode='RT22058')
");
I'm working in jsp with postgresql as backend, my IDE shows error in this statement.
i want to insert a record into db after checking and making sure that no such record already exists
Is this statement correct, or am I trying a garbage code?
Please help, thanks in advance

The reason for your error message is that an INSERT statement does not allow a WHERE clause.
You can only add a where clause to a SELECT statement (or a DELETE or UPDATE statement)
So you would need to get rid of the VALUES clause and use the insert into .. select ... syntax:
insert into demi(rno,subcode,subname,intm,extm,crd,resultdate)
select '13JG1A05A0',
'RT22058',
' FREE OPEN SOURCE SOFTWARE(FOSS) LAB ',
'20',
'70',
'2',
'MAY 2015'
where not exists (SELECT *
FROM demi
WHERE rn0='13JG105A0'
AND subcode='RT22058');
However for the intended use case:
I'm trying to insert a particular record into db if and only if there exists no other record with same rno and subject code columns
there is a better alternative if you have a unique constraint on (rno, subcode) (which you should) - use the on conflict clause:
insert into demi (rno, subcode, subname, intm, extm, crd, resultdate)
values
(
'13JG1A05A0',
'RT22058',
' FREE OPEN SOURCE SOFTWARE(FOSS) LAB ',
'20',
'70',
'2',
'MAY 2015'
)
on conflict (rno, subcode) do nothing;
Again: the on conflict will only work if you have a unique constraint (or index) on those two columns.
Unrelated, but:
you should specify each constant value with a literal matching the underlying data type. '20' is a character constant, 20 would be a number. Ìf intm, extm and crd re numbers, don't provide character values. Also if resultdate is a date column 'MAY 2015' won't work either.

Not sure how
end where not exists(SELECT * FROM demi WHERE rn0 ='13JG105A0' AND subcode='RT22058')
got into your code, but the whole thing is suspicious what do you even want that to do?

Related

How do I use the Class::DBI->sequence() method to fill 'id' field automatically in perl?

I'm following the example Class::DBI.
I create the cd table like that in my MariaDB database:
CREATE TABLE cd (
cdid INTEGER PRIMARY KEY,
artist INTEGER, # references 'artist'
title VARCHAR(255),
year CHAR(4)
);
The primary key cdid is not set to auto-incremental. I want to use a sequence in MariaDB. So, I configured the sequence:
mysql> CREATE SEQUENCE cd_seq START WITH 100 INCREMENT BY 10;
Query OK, 0 rows affected (0.01 sec)
mysql> SELECT NEXTVAL(cd_seq);
+-----------------+
| NEXTVAL(cd_seq) |
+-----------------+
| 100 |
+-----------------+
1 row in set (0.00 sec)
And set-up the Music::CD class to use it:
Music::CD->columns(Primary => qw/cdid/);
Music::CD->sequence('cd_seq');
Music::CD->columns(Others => qw/artist title year/);
After that, I try this inserts:
# NORMAL INSERT
my $cd = Music::CD->insert({
cdid => 4,
artist => 2,
title => 'October',
year => 1980,
});
# SEQUENCE INSERT
my $cd = Music::CD->insert({
artist => 2,
title => 'October',
year => 1980,
});
The "normal insert" succeed, but the "sequence insert" give me this error:
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use near ''cd_seq')' at line
1 [for Statement "SELECT NEXTVAL ('cd_seq')
"] at /usr/local/share/perl5/site_perl/DBIx/ContextualFetch.pm line 52.
I think the quotation marks ('') are provoking the error, because when I put the command "SELECT NEXTVAL (cd_seq)" (without quotations) in mysql client it works (see above). I proved all combinations (', ", `, no quotation), but still...
Any idea?
My versions: perl 5.30.3, 10.5.4-MariaDB
The documentation for sequence() says this:
If you are using a database with AUTO_INCREMENT (e.g. MySQL) then you do not need this, and any call to insert() without a primary key specified will fill this in automagically.
MariaDB is based on MySQL. Therefore you do not need the call to sequence(). Use the AUTO_INCREMENT keyword in your table definition instead.

TSQL: Special (National) char detection (SQL Server2016)

I found a lot of techniques to detect aka special chars($%##) avail on English keyboard, however I see that some national char like á works differently, though my LIKE condition should get it, as it should select anything but a-z1-9, what is the trick here: In sample below I'm missing my special á. I'm on TSQL 2016 with default settings in US.
;WITH cte AS (SELECT 'Euro a€' St UNION SELECT 'adgkjb$' St UNION SELECT 'Bravo Endá' St)
SELECT * FROM cte WHERE St LIKE '%[^a-zA-Z0-9 ]%'
St
adgkjb$
Euro a€
SELECT CAST(N'€' AS VARBINARY(8)) --0xAC20
SELECT CAST(N'á' AS VARBINARY(8)) --0xE100
SQL Server appears to be helping with ranges of characters due to the default collation. If you explicitly list all of the valid characters it will work as desired. Alternatively, you can force a collation on the pattern match that won't interpret the pattern a containing non-ASCII characters.
-- Explicit pattern for "bad" characters.
declare #InvalidCharactersPattern as VarChar(100) = '%[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ]%';
-- Query some sample data with the explicit pattern and an explicitly specified collation.
select Sample,
case when Sample like #InvalidCharactersPattern then 'Bad Character' else 'Okay' end as ExplicitStatus,
case when Sample like '%[^a-zA-Z0-9 ]%' collate Latin1_General_100_BIN
then 'Bad Character' else 'Okay' end as CollationStatus
from ( values ( 'a' ), ( 'A' ), ( 'á' ), ( 'Foo' ), ( 'F&o' ), ( '$%^&' ) ) as Samples( Sample );
-- Server collation.
select ServerProperty( 'collation' ) as ServerCollation;
-- Available collations.
select name, description
from sys.fn_helpcollations()
order by name;

updating multiple rows of 2 columns with different values (db2 sql)

I have a table in which I need to change the values of a couple of columns in multiple rows.
The table with values to be changed is like:
The code I have tried containing updated values, with no success, is:
UPDATE <table_name>
SET (IDENTIFIER_1, IDENTIFIER_2)
VALUES (1635, 1755),
(2024, 2199),
(1868, 1692),
(3577, 4825)
WHERE ID
IN ('1',
'23',
'54',
'21');
To be honest, I am not sure if this is even supported in db2 SQL. The error is:
[Error Code: -104, SQL State: 42601] DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=update *
I should also advise that I am a db2 newbie.
You can always use Merge
MERGE INTO TABLE1
USING (
VALUES (1,1635, 1755),
(23,2024, 2199),
(54,1868, 1692) ) dummytable(ID_T, INF1,INF2)
on table1.id_table = dummytable.id_t
when matched
then UPDATE set TABLE1.IDENTIFIER_1 = dummytable.INF1
, TABLE1.IDENTIFIER_2 = dummytable.INF2
else ignore

How can I combine these two statements?

I'm currently trying to insert data into a database from a text boxes, $enter / $enter2 being where the text is being written.
The database consists of three columns ID, name and nametwo
ID is auto incrementing and works fine
Both statements work fine on their own, but because they are being issued separately the first leaves nametwo blank and the second leaves name blank.
I've tried combining both but haven't had much luck, hope someone can help.
$dbh->do("INSERT INTO $table(name) VALUES ('".$enter."')");
$dbh->do("INSERT INTO $table(nametwo) VALUES ('".$enter2."')");
To paraphrase what others have said:
my $sth = $dbh->prepare("INSERT INTO $table(name,nametwo) values (?,?)");
$sth->execute($enter, $enter2);
So you don't have to worry about quoting.
You should read database manual.
The query should be:
$dbh->do("INSERT INTO $table(name,nametwo) VALUES ('".$enter."', '".$enter2."')");
The SQL syntax is
INSERT INTO MyTable (
name_one,
name_two
) VALUES (
"value_one",
"value_two"
)
Your way of generating SQL statements is very fragile. For example, it will fail if the table name is Values or the value is Jester's.
Solution 1:
$dbh->do("
INSERT INTO ".$dbh->quote_identifier($table_name)."
name_one,
name_two
) VALUES (
".$dbh->quote($value_one).",
".$dbh->quote($value_two)."
)
");
Solution 2: Placeholders
$dbh->do(
" INSERT INTO ".$dbh->quote_identifier($table_name)."
name_one,
name_two
) VALUES (
?, ?
)
",
undef,
$value_one,
$value_two,
);

PostgreSQL ERROR: INSERT has more target columns than expressions, when it doesn't

So I'm starting with this...
SELECT * FROM parts_finishing;
...I get this...
id, id_part, id_finish, id_metal, id_description, date,
inside_hours_k, inside_rate, outside_material
(0 rows)
...so everything looks fine so far so I do this...
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES (
('1013', '6', '30', '1', NOW(), '0', '0', '22.43'),
('1013', '6', '30', '2', NOW(), '0', '0', '32.45'));
...and I get...
ERROR: INSERT has more target columns than expressions
Now I've done a few things like ensuring numbers aren't in quotes, are in quotes (would love a table guide to that in regards to integers, numeric types, etc) after I obviously counted the number of column names and values being inserted. I also tried making sure that all the commas are commas...really at a loss here. There are no other columns except for id which is the bigserial primary key.
Remove the extra () :
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES
('1013', '6', '30', '1', NOW(), '0', '0', '22.43')
, ('1013', '6', '30', '2', NOW(), '0', '0', '32.45')
;
the (..., ...) in Postgres is the syntax for a tuple literal; The extra set of ( ) would create a tuple of tuples, which makes no sense.
Also: for numeric literals you don't want the quotes:
(1013, 6, 30, 1, NOW(), 0, 0, 22.43)
, ...
, assuming all these types are numerical.
I had a similar problem when using SQL string composition with psycopg2 in Python, but the problem was slightly different. I was missing a comma after one of the fields.
INSERT INTO parts_finishing
(id_part, id_finish, id_metal)
VALUES (
%(id_part)s <-------------------- missing comma
%(id_finish)s,
%(id_metal)s
);
This caused psycopg2 to yield this error:
ERROR: INSERT has more target columns than expressions.
This happened to me in a large insert, everything was ok (comma-wise), it took me a while to notice I was inserting in the wrong table of course the DB does not know your intentions.
Copy-paste is the root of all evil ... :-)
I faced the same issue as well.It will be raised, when the count of columns given and column values given is mismatched.
I have the same error on express js with PostgreSQL
I Solved it. This is my answer.
error fire at the time of inserting record.
error occurred due to invalid column name with values passing
error: INSERT has more target columns than expressions
ERROR : error: INSERT has more target columns than expressions
name: 'error',
length: 116,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '294',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'analyze.c',
line: '945',
here is my code dome
INSERT INTO student(
first_name, last_name, email, phone
)
VALUES
($1, $2, $3, $4),
values
: [ first_name,
last_name,
email,
phone ]
IN my case there was syntax error in sub query.