Can't order by or select only this one column - sql

I'm trying to do an extremely simple sql query but am running into an issue with this one column named Group. The Group column is not a key.
The following two statements fail in SQL:
SELECT *
FROM Lib.Stuff st
LEFT JOIN Lib.StuffOptions sto
on st.OptionId=sto.id
order by pa.Group desc, pa.Level
SELECT st.LongName,
st.Group,
sto.Name
FROM Lib.Stuff st
LEFT JOIN Lib.StuffOptions sto
on st.OptionId=sto.id
Both calls fail with the same error: Incorrect syntax near the keyword Group. I can use literally any other column name of Stuff and it works. But only for Group it fails.

Group is a reserved keyword, you need to use square brackets to escape it.
SELECT st.LongName,
st.[Group],
sto.Name
FROM Lib.Stuff st
LEFT JOIN Lib.StuffOptions sto
on st.OptionId=sto.id
Better to avoid using reserved keywords as identifiers

Related

Outer join for Alias name and column name -Oracle

I had a working sample query earlier in my code as mentioned below.
SELECT DISTINCT
nombre_aplicacion,
APLICACION,
NOMBRE_APLCODE,
DESCRIPCION,
AREAFUNC
FROM (
select **CODAPLICATION nombre_aplicacion**,
APLICACION,
NOMBRE_APLCODE,
DESCRPTION,
AREAFUNC
from admin.VW_APLICACIONES#dblink,
admin.VW_PRODUCTOS#dblink
where **nombre_aplicacion (+) = CODAPLICATION**
)
WHERE 1=1
ORDER BY nombre_aplicacion ASC;
When I try similar type of query with different tables I was getting error as invalid ORA-00904: "NOMBRE_APLICACION": invalid identifier.
If I remove nombre_aplicacion (+) = CODAPLICATION in where condition query is fetching the result. Can any one suggest why I was facing error as its working earlier with sample query and I was getting error? Is this join is valid?
The query is not valid as:
In the inner sub-query you select areafunc and in the outer query you use area which does not appear in the inner sub-query so will not be available.
In the inner sub-query, you define CODAPLICATION to have the alias nombre_aplicacion and then you try to use that alias in the WHERE clause as a join condition; that will not work.
You have not described which column belongs to which table but you want something like:
SELECT DISTINCT
a.codaplication AS nombre_aplicacion,
a.aplicacion,
a.nombre_aplcode,
p.descrption,
p.areafunc
from APLICACIONES a
LEFT OUTER JOIN PRODUCTOS p
ON (a.primary_key_column = p.foreign_key_column)
ORDER BY nombre_aplicacion ASC;
Note: you are going to have to correct the code to give the correct table aliases for each column and give the correct columns for the join condition.

ORA-00904 for one INNER JOIN but not for another

for one particular query I've written up the ORA-00904 error has occurred
SELECT '103040698' as StudID, M.Title, R.SHORTDESC, C.COLOURNAME
FROM MOVIE0698 M
INNER JOIN RATING0698 R
ON M.SHORTDESC = R.SHORTDESC
INNER JOIN COLOURTYPE0698 C
ON M.COLOURNAME = C.COLOURNAME
ORDER BY Title ASC;
specfically for ON **M.**SHORTDESC = R.SHORTDESC
However, the previous query I had just written beforehand that used an INNER JOIN as well
SELECT '103040698' as StudID, A.FullName, M.Title, M.RelYear
FROM CASTING0698 C
INNER JOIN ACTOR0698 A
ON C.ActorNo = A.ActorNo
INNER JOIN MOVIE0698 M
ON C.MovieNo = M.MovieNo
ORDER BY RelYear DESC;
this query runs perfectly, so I'm just unclear what I've done wrong.
From what I remember INNER JOINs are written with the child table first then the parent table e.g. ON C.ActorNo = A.ActorNo but I could be wrong since I know some software will accept either way while others are sensitive to it.
for context, I'm using SQLJunior for my school work
here is the whole error
ON M.shortdesc = R.shortdesc
*
Error at line 4: ORA-00904: "M"."SHORTDESC": invalid identifier
In plain English the error message means "the MOVIES0698 table doesn't have a column called SHORTDESC"
Remember that Oracle column names are only case insensitive if they are not enclosed in quotes, or were quoted allcaps. If a column name is enclosed in quotes, and is not all uppercase, when it is created then it must forced more be referred to using quotes
SHORTDESC -- not case sensitive, you could write SELECT shortDesc
"SHORTDESC" -- not case sensitive, because it's all caps anyway, can write SELECT shortdesc
"ShortDesc" -- case sens, must refer to this column using quotes forever more: SELECT "ShortDesc"... JOIN ON M."ShortDesc" etc
In summary, never enclosed oracle column names in quotes, for any reason. If you want to call a column something that is a reserved word, call it something else
If movies has no such column you have to join on a different column (SHORTDESC seems like it would be a text column, which probably makes for a poor join target anyway; is there no other column that is intended to relate movies and ratings better? Such as a "movieid" in the ratings table? It seems to me like one movie could have one or more ratings (some critics rate it high, others low, and you average the scores of many ratings..?)
I was using the wrong column names to join these tables together, i was writing it as
SELECT '103040698' as StudID, M.Title, R.SHORTDESC, C.COLOURNAME
FROM MOVIE0698 M
INNER JOIN RATING0698 R
ON M.SHORTDESC = R.SHORTDESC
INNER JOIN COLOURTYPE0698 C
ON M.COLOURNAME = C.COLOURNAME
ORDER BY Title ASC;
instead of
SELECT '103040698' as StudID, M.Title, R.SHORTDESC, C.COLOURNAME
FROM MOVIE0698 M
INNER JOIN RATING0698 R
ON M.ratingcode= R.ratingcode
INNER JOIN COLOURTYPE0698 C
ON M.colourcode= C.colourcode
ORDER BY Title ASC;
TL:DR
I had to use the proper foreign/primary key for INNER JOIN

Joining two tables, sorting and finding the Top revenue values

I am trying to create a query with the top 3 shops that have the highest average revenue amount and retail_type being fashion and shoes. I have to join 3 tables where I have to join 2 to the 1st one. Something seems to be wrong with the syntax below:
Select * from (Select
a.shop_id,
c.retail_type,
avg(b.revenue_amount) as avg_revenue_amount
From
shops a
Left join rev b on a.shop_id = b.shop_id
Left join trans c on b.trans_id = c.trans_id
Where
c.retail_type in (‘fashion’, ‘ shoes ’)
Group by
1,
2
Order by
avg_revenue_amount desc)
limit 10;
I would recommend writing the query as:
select s.shop_id, t.retail_type,
avg(r.revenue_amount) as avg_revenue_amount
from shops s join
rev r
on s.shop_id = r.shop_id join
trans
t
on r.trans_id = t.trans_id
where t.retail_type in ('fashion', 'shoes')
group by s.shop_id, t.retail_type
order by avg_revenue_amount desc
limit 10;
You don't specify your database, but the following are potentially problematic:
Bad quotes in the in clause.
Lack of alias after the derived table.
Use of numeric placeholders in GROUP BY.
Not all of these are necessarily errors, but they could be depending on your database.
The following would not cause a syntax error but might cause other problems:
Spaces around a string for an IN comparison means the comparison might not work.
Use of arbitrary letters for table aliases makes the query really hard to follow.
The WHERE clause turns the LEFT JOINs to inner joins so LEFT JOINs are highly misleading.
The subquery is superfluous.
You have extra bracket on the line:
avg_revenue_amount) desc)
Also you have typo on the second line: a.shop.id -> a.shop_id and another problem with quotes: ‘fashion’, ‘ shoes ’ -> 'fashion', 'shoes'
Check edited query on the SQL Fiddle.

Inner Join Invalid Object Name

Trying to do a simple inner join query but keep getting errors
Select Alias from Db.SchmaName.Customers as Customer
Select Alias from Db.SchmaName.Orders as Order
Inner Join Order on Customer.Alias = Order.Alias
The Db and SchmaNames are both exactly the same but Alias column is different between the 2 tables.
Both of the select statements work as expected but the error for the Inner Join is
"Invalid object name 'Order'"
I get this error even if I do not use the table alias and instead type out the full path to the table
I'm surprised that's the error you're getting. ORDER is a reserved word in SQL Server, don't use it for your object and alias names, you should be getting the error:
Incorrect syntax near 'order'.
Don't use reserved words (or even key words really) for object names, or if you have to, quote them ([Order]). Personally I would do:
SELECT Alias --This is missing an alias as well, so would be ambigous
FROM Db.SchmaName.Orders O
INNER JOIN Customer C ON C.Alias = O.Alias;
Aliases are great for making your SQL succinct. Aliasing the table Customers as Customer, doesn't really do that. A lot of people (like myself), tend to use a few characters to alias a table. So, for Customer I used C. Personally, I tend to use the letters of specific words in the object's name. For example, if I have a table called StockItem I would probably use SI. For a table I have called ic_BD_HPT1 I use HPT1.
Those are two queries, not one.
Select Alias from Db.SchmaName.Customers as Customer
Select Alias from Db.SchmaName.Orders as Order
Inner Join Order on Customer.Alias = Order.Alias
Is actually
Select Alias from Db.SchmaName.Customers as Customer;
Select Alias from Db.SchmaName.Orders as Order
Inner Join Order on Customer.Alias = Order.Alias;
The second query is invalid, as it tries to join the Order alias to itself.
To join two tables you need to specify the tables themselves in the FROM, JOIN statements. If you want to select a column that exists in both tables you have to explicitly specify which one you want, eg:
Select Order.Alias
from Db.SchmaName.Orders as [Order]
Inner Join Db.SchmaName.Customers as Customer
on Customer.Alias = [Order].Alias;
ORDER is a keyword which means you need to either enclose it in square brackets or use a better alias. In fact, Orders is just fine :
Select Orders.Alias
from Db.SchmaName.Orders
Inner Join Db.SchmaName.Customers as Customer
on Customer.Alias = Orders.Alias;
use different table alias name rather key word of SQL(Order),another issue Alias column is exist in your both table so use table.column in selection and
your join need like below
Select Customer.Alias from Db.SchmaName.Customers as Customer
inner join Db.SchmaName.Orders as O
on Customer.Alias = O.Alias
Order is a Keyword in SQL. You can not use Keywords in SQL for aliases, except if you put [] around the alias.
I would use a different name for the alias.
There are two queries in your question.
This is one
Select Alias from Db.SchmaName.Customers as Customer
And this is the second one
Select Alias from Db.SchmaName.Orders as Order
Inner Join Order on Customer.Alias = Order.Alias
The error you are getting is on the second query,
You are trying to JOIN against the Alias you've given to the table Orders, i.e ORDER. What you should do instead is reference the Alias on the ON clause, like so
Select Order.Alias, Customer.Alias
from Db.SchmaName.Orders as Order
INNER JOIN Db.SchmaName.Customers as Customer on Order.Alias = Customer.Alias

Trouble with parenthesis in MS Access for SQL Inner Joins

Have tried the below SQL in MS Access but cannot seem to get it working, anyone got a better idea?
SELECT top 4 Student.STUDENT_DEGREE, Student.STUDENT_SEX,STUDENT_GROUP_ID,STUDENT_GROUP_ID2,RESULT_MARK
FROM (((Student)
INNER JOIN Result ON Student.STUDENT_ID=Result.RESULT_STUDENT_ID)
INNER JOIN Group ON RESULT_GROUP_ID = GROUP_ID)
where STUDENT_GROUP_ID <> ''
order by Result.RESULT_MARK desc;
Whenever i run this i just get the error:
Syntax error in FROM clause
Group is a reserved word. Enclose that name in square brackets to avoid confusing the db engine. You can also assign an alias for the table name.
FROM
(Student
INNER JOIN Result
ON Student.STUDENT_ID=Result.RESULT_STUDENT_ID)
INNER JOIN [Group] AS g
ON Result.RESULT_GROUP_ID = g.GROUP_ID
I had to guess which tables contain those fields in the last ON clause. If you set up the joins in Design View of the Access query designer, it will help you get the names right. It will also add the parentheses which the db engine requires for any query which includes more than one join.
Also qualify the table sources for the field names in your SELECT list and elsewhere in the query. Here again, the query designer can supply the correct names for you.
Remove the extra set of parentheses around Student:
SELECT top 4 Student.STUDENT_DEGREE,Student.STUDENT_SEX,STUDENT_GROUP_ID,STUDENT_GROUP_ID2,RESULT_MARK
FROM ((Student
INNER JOIN Result ON Student.STUDENT_ID=Result.RESULT_STUDENT_ID)
INNER JOIN Group ON RESULT_GROUP_ID = GROUP_ID)
where STUDENT_GROUP_ID <> ''
order by Result.RESULT_MARK desc;