Andynedine
Andynedine

Reputation: 441

Is it possible to SELECT sqlserver data using WHERE with position?

Normally we use a column to filter a sql sentence

SELECT col_id, col_name FROM dataTable WHERE col__id>5

It is possible use a position to ORDER: ORDER BY 1 DESC

Is it possible use a position to filter?? Something like "this":

SELECT col_id, col_name FROM dataTable WHERE #2 LIKE '%Peter%'

Upvotes: 0

Views: 57

Answers (3)

Matt Gibson
Matt Gibson

Reputation: 38238

No. The WHERE clause is (logically) evaluated before the SELECT list, so it cannot refer to SELECT list items by number, as they haven't been numbered yet.

It's possible to do it in the ORDER BY as that's evaluated after the list of selected columns is evaluated, so you can refer to columns by number (though that's not recommended) or alias.

Also, even if it were possible, it would make your SQL more fragile and harder to read.

Upvotes: 2

Dhaval
Dhaval

Reputation: 2379

WHERE Clause run before select clause

here is Logical Query Flow

  1. [From]
  2. [Where]
  3. [Aggregations]
  4. [SELECT]
  5. [Order By]
  6. [Over]
  7. [Distinct]
  8. [Top]

FOR EXAMPLE

Upvotes: 1

Devart
Devart

Reputation: 121952

DECLARE @i TINYINT = 2

SELECT col_id, [col_name]
FROM dataTable
WHERE
    CASE @i
        WHEN 1 THEN col_id
        WHEN 2 THEN [col_name]
    END LIKE '%Peter%'

Upvotes: 0

Related Questions