1

I've got 3 tables with different structures, which share the same logical column: price. I want to find the biggest price from all records from all 3 tables. I'm trying something like:

SELECT MAX(price) FROM (

SELECT MAX(price) FROM pc
UNION
SELECT MAX(price) FROM printer
UNION
SELECT MAX(price) FROM laptop

);

but I get an syntax error: Incorrect syntax near ';'.. What is wrong and how it should look like? This should be compatible to the SQL standard, not a particular RDBMS.

1
  • You should add alias in the inner queries like "Max(price) as price". try this it may be also the cause of error. Also the subquery you need to give alias Commented May 12, 2013 at 11:04

2 Answers 2

3

you need to give alias for the subquery,

SELECT MAX(price) max_price
FROM 
(
    SELECT price FROM pc
    UNION ALL
    SELECT price FROM printer
    UNION ALL
    SELECT price FROM laptop
) subquery

getting the maximum price inside the subquery is not necessary.

Sign up to request clarification or add additional context in comments.

4 Comments

is max_price same thing as AS max_price? And what is subquery in the last line?
AS is an optional keyword so it's the same. subquery is the alias of the subquery. you can change it to what ever you want as long as it is not a reserved keywrd.
by the way, what database server are you using? did you try to execute the query above?
Well, it's sql-ex.ru, a SQL-learning platform. They may be using MS SQL, but I'm not sure. The error message is what I got from there. This learning platform is supposed to use SQL standard. BTW what I asked is just a small part of entire question I was working on ;) thanks!
2

Try this sql.

SELECT MAX(price) FROM (

SELECT MAX(price) as price FROM pc
UNION
SELECT MAX(price) as price FROM printer
UNION
SELECT MAX(price) as price FROM laptop

) t;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.