Nested SELECT "works" when using nonexistant column - why? - sql

folks, I have the following query in SQLite:
select license, username from check_table where
(
username not in (
select username from Address
)
) order by license, username;
Address is another table. The fun part is: Address has no usernamecolumn!!
Details:
Result: Query finished in 0.004 second(s)
If I modify the username part (e.g. to userrname) I get a no such column error, which is totally fine
it never returns any results, even when I replace username with mail_username (which actually exists) in the sub-select - which is totally strange, because it really should.
Now, my question is: Why don't I get an error here?! And does it have something to do with the fact that I never get any results?

You're selecting username from the check_table, not from the address table.
Try to add aliases and check it out:
select ct.license, ct.username
from check_table as ct
where
(
ct.username not in (
select ct.username
from Address as a
)
) order by ct.license, ct.username;
I bet if you will try to use select a.username... you'll get an error about not existing column.
For this purpose, all the time when you're using multiple tables in the query is good to use aliases.

Related

SQL in Access 2003: INSERT INTO and multiple SELECT queries

I'm using Access 2003 (forced to do it due to retrocompatibility) to modify a 10 years old project, not made by me.
I encounter errors in executing this query:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, (SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;
That returns errors due to
(SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2
If I execute this query standalone, it works like a charm but when it comes to inserting the query into the INSERT INTO...SELECT statement, it returns (translated from italian):
Runtime error '3000': Reserved error (-3025): there are no messages
for this error.
The aim is to insert in a table some new values based on values found in the active form, and the part of code which isn't working should search into a table a value linked to the [InserisciContratto]![Cliente] actual value.
What am I doing wrong? Maybe is that because I cant execute a SELECT subquery in a previous SELECT query?
Any help would be appreciated.
You can work around the problem using a DLookUp instead of a subquery:
DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]")
Note that you can either use the DLookUp on a form control, or in a query. Both are valid. In the query, it'd look like this:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]") AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;
An alternate, common source of these kind of errors is that Access behaves finicky when using subqueries and not querying from a real table. You can easily work around that by using the subquery as the main query. Note that this does require the subquery to always return a result, else no row will be inserted:
INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, Nome AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6
FROM TAnagrafica
WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]

Access SQL Query: trouble with * wildcard in WHERE AND LIKE statement

The query I'd like to execute:
SELECT *
FROM qryReportView
WHERE ((ID = 719)
AND (Name Like "*x"));
However when I run this query I get no records returned. Each criterion works on its own:
SELECT *
FROM qryReportView
WHERE ID = 719;
and
SELECT *
FROM qryReportView
WHERE Name Like "*x";
Both queries return records as expected but when I combine them something goes wrong. I know there is at least one record for which both criteria are true.
NOTE: When I replace the * wildcard with an explicit name, I get the correct record returned. This is not a viable solution for me though because my query needs to select records ending in "x" with a number of possible prefixes.
Thank you so much for the help.
Your issue is a logical operator issue.
When you ask an RDBMs for a samich and a coke, if it has a samich but not a coke, you get nothing. Which is what is happening here, you need an 'or'
SELECT *
FROM qryReportView
WHERE (ID = 719
OR
Name Like '*x');

SQL NOT IN failed

I am working on a query that will check the temp table if there is a record that do not exist on the main table. My query looks like this
SELECT * FROM [Telemarketing].[dbo].[PDCampaignBatch_temp]
WHERE [StartDateTime] NOT IN (SELECT [StartDateTime] FROM [Telemarketing].[dbo].PDCampaignBatch GROUP BY [StartDateTime])
but the problem is it does not display this row
even if that data does not exist in my main table. What seems to be the problem?
NOT IN has strange semantics. If any values in the subquery are NULL, then the query returns no rows at all. For this reason, I strongly recommend using NOT EXISTS instead:
SELECT t.*
FROM [Telemarketing].[dbo].[PDCampaignBatch_temp] t
WHERE NOT EXISTS (SELECT 1
FROM [Telemarketing].[dbo].PDCampaignBatch cb
WHERE t.StartDateTime = cb.StartDateTime
);
If the set is evaluated by the SQL NOT IN condition contains any values that are null, then the outer query here will return an empty set, even if there are many [StartDateTime]s that match [StartDateTime]s in the PDCampaignBatch table.
To avoid such issue,
SELECT *
FROM [Telemarketing].[dbo].[PDCampaignBatch_temp]
WHERE [StartDateTime] NOT IN (
SELECT DISTINCT [StartDateTime]
FROM [Telemarketing].[dbo].PDCampaignBatch
WHERE [StartDateTime] IS NOT NULL
);
Let's say PDCampaignBatch_temp and PDCampaignBatch happen to have the same structure (same columns in the same order) and you're tasked with getting the set of all rows in PDCampaignBatch_temp that aren't in PDCampaignBatch. The most effective way to do that is to make use of the EXCEPT operator, which will deal with NULL in the expected way as well:
SELECT * FROM [Telemarketing].[dbo].[PDCampaignBatch_temp]
EXCEPT
SELECT * FROM [Telemarketing].[dbo].[PDCampaignBatch]
In production code that is not a one-off, don't use SELECT *, write out the column names instead.
Most likely your issue is with the datetime. You may be only displaying a certain degree of percision like the year/month/date. The data may be stored as year/month/date/hour/minute/second/milisecond. If so you have to match down the the most granluar measurement of the data. If one field is a date and the other is a date time they also will likely never match up. Thus you always get no responses.

Case statement is not working on query

I am working on jasper report.I have a table named user I have 2 parameters internal,external .When I use internal then my query needs to show the users where username LIKE '%_#__%.__%' and when I use external then my query needs to show the users where username NOT LIKE '%_#__%.__%'.Like when internal then report will show 2,3,4,5 no row and when external then report will show only one row..My query is
SELECT case
when $P{internal} = 'internal' then
id end as cid,
designation,division_name,pin_no,username FROM application_user where username LIKE
'%_#__%.__%'
else
id end as cid,
designation,division_name,pin_no,username FROM application_user where username NOT LIKE
'%_#__%.__%'
but it is not working
Please let me know If i'm not clear
Projection statements cannot be parameterised in SQL directly (but you can in Dynamic SQL, obviously).
Your test expression should be evaluated in the WHERE block, not SELECT. The SQL you posted is not valid and won't run, so I'm curious how you're getting the results you're seeing.
Try this:
SELECT
id AS cid,
designation,
division_name,
pin_no,
username
FROM
application_user
WHERE
( $P{internal} = 'internal' AND username LIKE '%_#__%.__%' )
OR
( $P{internal} <> 'internal' AND username NOT LIKE '%_#__%.__%' )
Note that this will not necessarily result in the best runtime execution plan because of the different effective query "shape" depending on the parameter value. Ideally you should have two different queries selected by your application code which have the different username predicates.

Evaluate a varchar2 string into a condition for a SQL statement

I'm trying to find which rows are missing from 1 database to another, I already have link to the both DBs and I already found out that I can't just join separate tables so what I'm trying right now is select the ID's from one table and paste them into the select statement for the other DB however I don't know how to parse a clob into a condition.
let me explain further:
I got this collection of varchar2's with all the ID's i need to check on the other DB, and I can iterate through that collection so I get a clob with form: 'id1','id2','id3'
I want to run this query on the other DB
SELECT * FROM atable#db2
WHERE id NOT IN (clob_with_ids)
but I don't know how to tell PL/SQL to evaluate that clob as part of the statement.
id field on atable#db2 is an integer and the varchar2 id's I got are from runnning a regex on a clob
edit:
I've been ask to add the example I was trying to run:
SELECT *
FROM myTable#db1
WHERE ( (creation_date BETWEEN to_date('14-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND to_date('14-JUN-2011 23:59:59','DD-MON-YYYY HH24:MI:SS')) )
AND acertain_id NOT IN ( SELECT to_number(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_SUBSTR(payload,'<xmlTag>([[:alnum:]]+)-'),'<xmlTag>',''),'-','')) as sameIDasOtherTable
FROM anotherTable#db2
WHERE condition1 ='bla'
AND condition2 ='blabla'
AND ( (creation_date BETWEEN to_date('14-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND to_date('14-JUN-2011 23:59:59','DD-MON-YYYY HH24:MI:SS')) ) )
ORDER BY TO_CHAR(creation_date, 'MM/DD/YYYY') ASC;
I get error ORA-22992
Any suggestiongs?
It seems to me you have invested a lot of time in developing the wrong solution. A way simpler solution would be to use a SET operator. This query retrieves all the IDs in the local instance of ATABLE which are missing in the remote instance of the same table:
select id from atable
minus
select id from atable#db2
If your heart is set on retrieving the whole local row, you could try an anti-join:
select loc.*
from atable loc
left join atable#db2 rem
on (loc.id = rem.id )
where rem.id is null
/
I don't believe you can do that, but I've been proved wrong on many occasions... Even if you could find a way to get it to treat the contents of the CLOB as individual values for the IN you'd probably hit the 1000-item limit (ORA-01795) fairly quickly.
I'm not sure what you mean by 'I already found out that I can't just join separate tables'. Why can't you do something like:
SELECT * FROM atable#db2 WHERE id NOT IN (SELECT id FROM atable#db1)
Or:
SELECT * from atable#db2 WHERE id IN (
SELECT id FROM atable#db2 MINUS SELECT id FROM atable#db1)
(Or use #APC's anti-join, which is probably more performant!)
There may be performance issues with joining large tables on remote databases, but it looks like you have to do that at some point, and if it's a one-off task then it might be bearable.
Edited after question updated with join error
The ORA-22992 is because you're trying to pull a CLOB from the the remote database, which doesn't seem to work. From this I assume your reference to not being able to join is because you're joining two remote tables.
The simple option is not to pull all the columns - specify which you need rather than doing a select *. If you do need the CLOB value, the only thing I can suggest trying is using a CTE (WITH tmp_ids AS (SELECT <regex> FROM anotherTable#db2) ...), but I really have no idea if that avoids the two-link restriction. Or pull the IDs into a local temporary table; or run the query on one of the remote databases.