tags:

views:

51

answers:

2

I'm getting a syntax error on the following query:

SELECT 1,2 WHERE 1=1

But this query works fine:

SELECT 1,2 FROM (SELECT 1) t WHERE 1=1;

It almost looks like a WHERE clause always needs a table. Sometimes, in the depth of a complex query it's nice to use a SELECT/WHERE combo to turn on and off certain features. Is there a way to not always add the FROM (SELECT 1) t?

Edit:

I found another similar issue


(SELECT 1 x)
UNION
(SELECT 2)
WHERE 1=1

gives a syntax error, but this does not:


SELECT x
FROM
(
    (SELECT 1 x)
    UNION
    (SELECT 2)
) t
WHERE 1=1

I'm using 5.1.48-community MySQL Community Server (GPL). Is anyone else seeing this?

+1  A: 

You can use "FROM DUAL" to just say you're not selecting from a table. As in :

SELECT 'Hello, World' FROM DUAL;
Dante617
That's straight from the [reference manual](http://dev.mysql.com/doc/refman/5.0/en/select.html), but note the line following it: "DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced." That suggests you DON'T need a "from" statement. Color me confused.
eykanal
@eykanal: `FROM` clause is required if you are also going to use `WHERE`
Quassnoi
@OMGPonies: not by `PostgreSQL`.
Quassnoi
Where does it say `FROM` is required for using a `WHERE`? I didn't see it in the MySQL manual (http://dev.mysql.com/doc/refman/5.1/en/select.html).
User1
@User1 - I believe it says it in your link. (Note the [ brackets ] around the from clause.) You can't have a where without the from.
Dante617
@OMGPonies: of course it will work if you create it, like the guys from `OpenACS` do :) `DUAL` is not present in `PostgreSQL` by default, however, and is not recognized as a system table.
Quassnoi
Correction: The DUAL table isn't supported on SQL Server and PostgreSQL, but is on Oracle and MySQL.
OMG Ponies
@Quassnoi: The grammar says `[FROM table_references [WHERE where_condition] [ORDER BY ...]]`. Notice the missing `]` after the `FROM table_references`.
User1
@Quassnoi (continued): I guess `FROM` is required. It looks like MySQL's grammar really does make things more difficult. (kicking myself for not using Postgres)
User1
A: 

This:

SELECT  1 x
UNION
SELECT  2
WHERE   1 = 1

is two queries, combined with UNION. The second query:

SELECT  2
WHERE   1 = 1

is invalid, since it misses a FROM clause while still using WHERE.

This:

SELECT  x
FROM    (
        SELECT 1 x
        UNION
        SELECT 2
        ) t
WHERE   1 = 1

is a SELECT from an inline view, which is again, two queries combined with a UNION.

Neither of the queries uses WHERE, so it's OK for them not to have a FROM. Both queries are valid, and the resulting query is too.

Quassnoi