Use table in order by case when does not work - sql

I am running this query but I get an error
select *
from dog
order by case
when exists(
select 1 from dogfood where dog.dogid = dogfood.dogid)
then '1'
else '0' end;
So 2 tables, dog and dogfood which both have a dogid column. I get this error:
[42703][-206] "DOG.DOGID" is not valid in the context where
it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=4.26.14
[56098][-727] An error occurred during implicit system action type
"2". Information returned for the error includes SQLCODE "-206",
> SQLSTATE "42703" and message tokens "DOG.DOGID"..
> SQLCODE=-727, SQLSTATE=56098, DRIVER=4.26.14
I just want to order the dog by if it has a row in dogfood. A solution would be querying the result in the select clause and refer to it in the order by clause, but I want it in the order by clause for my application. I am curious why this query isn't working, I double checked for syntax errors but I could not find any. Am I missing something obvious? I would expect I could refer to a table in the order by which I queried in the select/from clauses.

See documentation
sort-key-expression
An expression that is not simply a column name or an unsigned integer constant. The query to which ordering is applied must be a
subselect to use this form of sort-key. The sort-key-expression cannot
include a correlated scalar fullselect (SQLSTATE 42703) or a function
with an external action (SQLSTATE 42845).
But since it is not correlated you can use IN with a fullselect
select *
from dog
order by
case when dog.dogid in (select dogid from dogfood)
then '1' else '0' end;

Related

Log errors into error table in insert statement

I came across an error invalid identifier in the error table even though the fields are present in the error table. The below is my test code for your reference. Any update absolutely appreciated.
Insert into test1
(a,b,e)
Select a,b,c||d e from
(Select c.a, d.b, d.c, c.d
From
(select e.a,e.b, f.c, d.d from
Test2 e, Test 2 f where
e.id = f.id) c ) v
Log errors into test1_err
(‘Batch :’
|| to_char(v.a)
|| to_char(v.b)
|| ‘;’
) Reject Limit Unlimited;
SQL Error: ORA:-00904: "v.a": invalid indentifier
Supposing you created the table with the dbms_errlog package, the expression you put in the '()' can contain the following as per the doc:
simple_expression
Specify the value to be used as a statement tag, so that you can identify the errors from this statement in the error logging table. The expression can be either a text literal, a number literal, or a general SQL expression such as a bind variable. You can also use a function expression if you convert it to a text literal — for example, TO_CHAR(SYSDATE).
so you cannot put column values. These are added to the table by the kernel, no need to add them yourself.

Not exists operator error on multiple tables selection

This selection works great with NOT IN, but with NOT EXISTS it returns an error:
SQL Error: ORA-00920: invalid relational operator
00920. 00000 - "invalid relational operator"
Does NOT EXISTS works other way?
select COMPANY.TITLE_COMPANY
from COMPANY
outer join LOCATION on (LOCATION.NAME_LOC = COMPANY.NAME_LOC)
where COMPANY.NUM_COMPANY not exists (select NUM_COMPANY from COMPANY_SUC)
;
Your syntax is wrong and it's easy to spot why. Mind that a where not exists clause is used to subtract one set of data from another set:
select
ename
from
emp
where NOT EXISTS
(select
null
from
dependents
where
emp.empno = dependents.empno
and ...
);
But you're trying to relate it to a specific field in the base query, which is wrong, it is not exactly as NOT IN, which compares data in a column to a subquery result.
Don't try to replace it with one another.

ORA-00998: must name this expression with a column alias

I get that I should add alias with all the columns and I'm doing so but I'm still getting error.
CREATE TABLE MENTIONS AS SELECT
UM.USER_ID AS U_ID,
UM.SCREEN_NAME AS USER_SCREEN_NAME,
UM.MENTION_ID AS M_USER_ID,
(
SELECT
UI.USER_SCREEN_NAME AS MENTIONED_USER
FROM
USER_INFO UI
WHERE
UI.USER_ID = UM.MENTION_ID
AND ROWNUM = 1
)
FROM
USER_MENTION UM
USER_MENTION table
USER_ID SCREEN_NAME MENTION_ID
135846337 irisschrijft 774759032636727300
50117969 Chjulian 13769472
14411827 thenriques45 13769472
26681613 ahenotri 252074645
26681613 ahenotri 9796472
158378782 SpringerOpen 9796472
144241914 Kumarappan 252074645
User_INFO table:
USER_ID USER_SCREEN_NAME
22553325 jasonesummers
23435691 QRJAM false
67421923 inTELEgentMSP
97393397 knauer0x
85303739 MarriageTheorem
3842711 seki
3036414608 Bayes_Rule
838677852 BOLIGATOR
I'm still getting the above mentioned error, what am I doing wrong?
Lookup the Oracle Error Message Manual of the current Oracle version. Here the error is mentioned but without additional information.
In such a case look up the
Oracle Error Message Manual of version 9i
For reasons I don't know a lot of error messages have a description in the 9i manual but not in the manuals of higher versions. 9i is a rather old version so the description may be out of date. But it may contain valuable hints.
ORA-00998 must name this expression with a column alias
Cause: An expression or function was used in a CREATE VIEW statement, but no corresponding column name was specified. When expressions or functions are used in a view, all column names for the view must be explicitly specified in the CREATE VIEW statement.
Action: Enter a column name for each column in the view in parentheses after the view name.
We don't have a view but a a table that was created by a select. And actually the last expression of the select list is an expression without an alias. So try your statement using an alias for the last expression. So try
CREATE TABLE MENTIONS AS SELECT
UM.USER_ID AS U_ID,
UM.SCREEN_NAME AS USER_SCREEN_NAME,
UM.MENTION_ID AS M_USER_ID,
(
SELECT
UI.USER_SCREEN_NAME
FROM
USER_INFO UI
WHERE
UI.USER_ID = UM.MENTION_ID
AND ROWNUM = 1
) AS MENTIONED_USER
FROM
USER_MENTION UM
The column alias in the inner select list is useless and can be removed.
The problem with your query is that each column in the create table needs to have a name. You think you are assigning a name in the sub-select. However, you are not.
The subquery is just returning a value -- not a value with a name. So, the AS MENTIONED_USER in your version does nothing. This is a bit tricky, I guess. One way to think of the scalar subquery is that it is just another expression or function call. Things that happen inside it don't affect the outer query -- except for the value being returned.
The correct syntax is to put the column alias outside the subselect, not inside it:
CREATE TABLE MENTIONS AS
SELECT UM.USER_ID AS U_ID, UM.SCREEN_NAME AS USER_SCREEN_NAME, UM.MENTION_ID AS M_USER_ID,
(SELECT UI.USER_SCREEN_NAME
FROM USER_INFO UI
WHERE UI.USER_ID = UM.MENTION_ID AND ROWNUM = 1
) AS MENTIONED_USER
FROM USER_MENTION UM;

Oracle SQL Cast two different columns to one column?

I am selecting data from two different columns depending on what sort of record it is.
Using a Case statement I check what type of record it is and select the appropriate column to insert.
However the syntax for using CAST is not correct and after checking the Oracle docs, there is no reason why it is not working.
CREATE TABLE TEST123 AS
SELECT DISTINCT
bill.ROW_ID,
bill.ACCNT_TYPE_CD,
CASE
WHEN bill.ACCNT_TYPE_CD = 'TestAccount'
THEN CAST(TO_CHAR(bill.INTEGRATION_ID) AS VARCHAR2(30)) AS NUM
ELSE CAST(TO_CHAR(bill.OU_NUM )AS VARCHAR2(30)) AS NUM
END
FROM SIEBEL.S_ORG_EXT bill
INNER JOIN Products prod
ON prod.BILL_ACCNT_ID = bill.ROW_ID
OR prod.CUST_ACCNT_ID = bill.ROW_ID;
Error code is:
ORA-00905: missing keyword
00905. 00000 - "missing keyword"
AS NUM must follow the END of the CASE. If you could set the column name for each condition separately, then the column could have two different names. Clearly that can't work.
CASE
WHEN bill.ACCNT_TYPE_CD = 'TestAccount'
THEN CAST(TO_CHAR(bill.INTEGRATION_ID) AS VARCHAR2(30))
ELSE CAST(TO_CHAR(bill.OU_NUM )AS VARCHAR2(30))
END AS NUM
Also, using both TO_CHAR and CAST(... as VARCHAR(30)) is redundant. They are both ways of converting a non-string to a string.
And since CASE .. END is a function, you can go even further than explained by Allan:
SELECT DISTINCT ...
CAST(
CASE WHEN bill.ACCNT_TYPE_CD = 'TestAccount'
THEN bill.INTEGRATION_ID
ELSE bill.OU_NUM
END
AS VARCHAR(30) -- `AS` here is part of the `CAST` function
-- and will denote the requested data type
) AS NUM -- `AS` here introduces the column alias
If your not familiar with the CAST function, please beware of the double meaning of the AS keyword here. See the comments in the code above

Inserting or Updating a table with 2 sub queries in SQL Server

I am having a hard time doing a 'INSERT INTO' with 2 sub queries in the WHERE clause. I'm not sure wht I'm missing, it keep stating that an expression of non-boolean type specified in context where a condition is expected, near ';'.
This is my attempt at it:
INSERT INTO [Monitor].[dbo].[MonitorIncidents]
SELECT *
FROM dbo.MonitorSource
WHERE (
SELECT DISTINCT *
FROM Lookup.dbo.ServerInfo S
WHERE NOT EXISTS
(
SELECT 1
FROM Lookup.dbo.Facts F
WHERE F.FactsName = S.SrvName
AND W.DateTime > DATEADD(hour, -23, CURRENT_TIMESTAMP)
)
)
Your WHERE clause is missing an operand like =,<, >, etc. You are just returning a field to WHERE wihout a comparison. Depending on what you want to do, extend your WHERE to include a comparison.