PostgreSQL query for emails with Apostrophe - sql

I have a database table with email addresses with apostrophe such as "some.o'ne#somewhere.com".
I would like to:
Query this table, and check if this email address exist
insert this email address if it doesn't exist in the table
I tried:
SELECT *
FROM EMAILTABLE
WHERE emailaddress LIKE 'some.o''ne#somewhere.com'
it doesn't find "some.o'ne#somewhere.com", so it's treating it as it doesn't exist!

Double-quotes around some text indicates you are looking for an object name, unless you are embedding the double-quotes within single-quotes.
So:
DROP TABLE IF EXISTS emailtable;
CREATE TEMP TABLE emailtable (emailaddress text);
CREATE UNIQUE INDEX idx_emailtable_emailaddress ON emailtable (emailaddress);
INSERT INTO emailtable (emailaddress) VALUES ('some.o''ne#somewhere.com');
SELECT emailaddress
,(emailaddress = 'some.o''ne#somewhere.com')::bool as escaped_apostrophe_single_quotes --true because it matches the value in the table
--,(emailaddress = "some.o'ne#somewhere.com")::bool as double_quotes --ERROR: column "some.o'ne#somewhere.com" does not exist
,(emailaddress = '"some.o''ne#somewhere.com"')::bool as double_quotes --false because the value in the table doesn't include double-quotes
FROM emailtable;
In the second test, it's assuming that "some.o'ne#somewhere.com" is a column, because it's a name inside double-quotes.
You can see from the first and third tests that the presence of the double-quotes inside the string are saying that these strings are different. The first one is the same as the value in the table. The other one isn't.
Anyway, I think the simplest way to handle is with a unique index on the emailaddress. If you then try to insert the same value that already exists, it won't do anything.
INSERT INTO emailtable (emailaddress) VALUES ('some.o''ne#somewhere.com') ON CONFLICT DO NOTHING;

Thanks for the replies (just replacing single quote with two single quotes doesn't work for me as it stores the email addresses with two single quotes)
This query worked fine for me:
SELECT * FROM EMAILTABLE WHERE emailaddress = (E'some.o\'ne#somewhere.com')::text;

Related

DB2 error: SQL subselect error not recognized

I think I just found an error in DB2 itself. When I run this code I expect it to throw an error when executing the delete statement (the subselect wrongly uses A_NAME instead of NAME). But: it acts as if there was no where clause and deletes all the rows in table NAMES!
CREATE TABLE NAMES (A_NAME VARCHAR(20));
CREATE TABLE OLDNAMES (NAME VARCHAR(20));
INSERT INTO NAMES VALUES ('ANNA'), ('ELLA'), ('JOHN'), ('EARL');
INSERT INTO OLDNAMES VALUES ('ELLA'), ('EARL');
-- this should throw an error message:
DELETE FROM NAMES WHERE A_NAME IN (SELECT A_NAME FROM OLDNAMES);
-- this should show ANNA & JOHN if the subselect
-- was correct, but shows nothing
SELECT * FROM NAMES;
-- cleanup
DROP TABLE NAMES;
DROP TABLE OLDNAMES;
I ran it on a DB2/LINUXX8664 10.5.9
Or is "not a bug, but a feature"?!
You are wrong. SQL has scoping rules for resolving column references in subqueries. If the column reference is not resolved in the inner query, then it looks to the outer query.
These are the rules of SQL, not specific to DB2.
That is SQL interprets your logic as:
DELETE FROM NAMES
WHERE NAMES.A_NAME IN (SELECT NAMES.A_NAME FROM OLDNAMES ON);
And this is valid -- if meaningless -- SQL.
This is why qualifying ALL column references is recommended. The better way to write this query is:
DELETE FROM NAMES
WHERE NAMES.A_NAME IN (SELECT ON.A_NAME FROM OLDNAMES ON);

Cloned Snowflake table, why is every column in quotes?

I have a table of varchar values, when I copy this table by cloning the entire table has quotation marks around every varchar value.
For example 12/8/2017 becomes "12/8/2017", Finance becomes "Finance".
Wondering A, why did this happen. B is there any way to fix this?
So I tried to think of a senario where this might happen and I found this:
CREATE OR REPLACE TABLE demo_db.public.employees
(emp_id number,
first_name varchar,
last_name varchar
);
-- Populate the table with some seed records.
Insert into demo_db.public.employees
values(100,'"John"','"Smith"')
(200,'Sam','White'),
(300,'Bob','Jones'),
(400,'Linda','Carter');
SELECT * FROM demo_db.public.employees;
CREATE OR REPLACE TABLE demo_db.public.employees_clone
CLONE employees;
From demo: https://community.snowflake.com/s/article/cloning-in-snowflake
You may notice that I had to use ' ' in order for the INSERT statement to accept the data. I did the same INSERT to the cloned table below and received an error.
INSERT INTO demo_db.public.employees_clone VALUES(500,""'Mike'"",'Jones');
However this worked:
INSERT INTO demo_db.public.employees_clone VALUES(500,'"Mike"','Jones');
The results of the select * of the clone:
desc table demo_db.public.employees_clone;
So the type was still varchar, it just had ' " ' a quote in the string.
Try DESC to see what happened. I am going to guess that the original table loaded the strings with "" or from where you are reading it is putting it in quotes. Either way, please share the original data, or a sample of it with support. If you are in the community portal, please see: https://support.snowflake.net/s/article/How-to-Get-Access-to-the-Case-Console-in-the-Lodge-Community

Copying values / columns from one table to another existing tabler in SQL Server Management Studio

I want to copy all columns from dbo.die to dbo.technology.
Both tables exist! In dbo.technology, the primary key is idTechnology
In dbo.die, the primary key is idDie and we have a foreign key, which is Technology_idTechnology in it, which connects the die table with the technology table.
How could I do that, so that the values got copied to the right rows, which match the same idTechnology?
I tried this:
INSERT INTO dbo.die
(Technology_idTechnology, Technology_D, Technology_Type, Technology_Manufacturer, Technology_SOI, Technology_Node, Technology_Name, Technology_Number_Metal, Technology_Number_Poly, Technology_Power_Cu, Technology_FEComplexity, Technology_FEComplexity_Sec, Technology_Trench, Technology_IMID, Technology_Remarks)
SELECT *
FROM dbo.technology tech
WHERE tech.idTechnology = idTechnology;
but I'm always getting an error!
Cannot insert duplicate key row in object 'dbo.die' with unique index 'ui_dieIdsample'. The duplicate key value is ().
Don't know what I should do.. I thought it's easy & simple
If a column is declared as NOT NULL (and has no default value), a value for the column must be specified in the INSERT statement.
In this specific case you should add Table2_Feld to the insert column list, and specify a value in the SELECT for it!
You will need to change your column list (lets say that its acceptable to insert a default value of 0 into column Table2_Feld)
INSERT INTO dbo.table2
(Table1_idTech, Tech_D, Techn_Type, Tech_Man,
Techn_Node, Tech_Name, Technology_Numb, Tech_Po,
Tech_FEC, Techn_Comp_Sec,
Tech_R,Table2_Feld)
select *,0 from table1 tech

SQL How to insert null value

I want to insert data into one table from another table. In some of the columns I don't have data, so I want to set column to null. I don't know how I should do this?
This is the SQL:
INSERT INTO _21Appoint(
PCUCODE,PID,SEQ,
DATE_SERV,APDATE,
APTYPE,APDIAG,D_UPDATE,CID
) SELECT (
NULL,NULL,NULL,
treatment_date,appointment_date,
typeap_id,appointment_id,NULL,patient_id
) FROM cmu_treatment,cmu_appointment
WHERE cmu_treatment.treatment_id LIKE cmu_appointment.treatment_id;
Your insert is essentially correct. Just don't put the column list in parentheses:
INSERT INTO _21Appoint
(PCUCODE,PID,SEQ,DATE_SERV,APDATE,APTYPE,APDIAG,D_UPDATE,CID)
SELECT NULL,NULL,NULL,treatment_date,appointment_date,typeap_id,appointment_id,NULL,patient_id
FROM cmu_treatment,cmu_appointment
WHERE cmu_treatment.treatment_id LIKE cmu_appointment.treatment_id;
In Postgres (unlike other DBMS) putting a column list in parentheses makes the result a single "record", rather then individual columns. And therefore the select only returns a single column, not multiples and thus it doesn't match the column list for the insert
another option is to simply leave out the columns completely:
INSERT INTO _21Appoint
(DATE_SERV,APDATE,APTYPE,APDIAG,CID)
SELECT treatment_date,appointment_date,typeap_id,appointment_id,patient_id
FROM cmu_treatment,cmu_appointment
WHERE cmu_treatment.treatment_id LIKE cmu_appointment.treatment_id;

SQL: I need to take two fields I get as a result of a SELECT COUNT statement and populate a temp table with them

So I have a table which has a bunch of information and a bunch of records. But there will be one field in particular I care about, in this case #BegAttField# where only a subset of records have it populated. Many of them have the same value as one another as well.
What I need to do is get a count (minus 1) of all duplicates, then populate the first record in the bunch with that count value in a new field. I have another field I call BegProd that will match #BegAttField# for each "first" record.
I'm just stuck as to how to make this happen. I may have been on the right path, but who knows. The SELECT statement gets me two fields and as many records as their are unique #BegAttField#'s. But once I have them, I haven't been able to work with them.
Here's my whole set of code, trying to use a temporary table and SELECT INTO to try and populate it. (Note: the fields with # around the names are variables for this 3rd party app)
CREATE TABLE #temp (AttCount int, BegProd varchar(255))
SELECT COUNT(d.[#BegAttField#])-1 AS AttCount, d.[#BegAttField#] AS BegProd
INTO [#temp] FROM [Document] d
WHERE d.[#BegAttField#] IS NOT NULL GROUP BY [#BegAttField#]
UPDATE [Document] d SET d.[#NumAttach#] =
SELECT t.[AttCount] FROM [#temp] t INNER JOIN [Document] d1
WHERE t.[BegProd] = d1.[#BegAttField#]
DROP TABLE #temp
Unfortunately I'm running this script through a 3rd party database application that uses SQL as its back-end. So the errors I get are simply: "There is already an object named '#temp' in the database. Incorrect syntax near the keyword 'WHERE'. "
Comment out the CREATE TABLE statement. The SELECT INTO creates that #temp table.