J.S.Orris
J.S.Orris

Reputation: 4821

How To Switch Columns In SQL Results

Lets say I have a simple query like:

SELECT
    A
   ,B
FROM
    C

I will get this result:

A|B
---
x|x

Without changing the select clause in the query (SELECT A, B), how can I receive a result as follows:

B|A
---
x|x
######## EDIT

The reason I ask is because I want to do the following but is improper syntax:

SELECT A, DISTINCT B
FROM C

I truly want the DISTINCT B in the first column because it is easier to both look at and find patterns in the results.

Is there a better approach to take?

Upvotes: 0

Views: 791

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

Your revised query could be written:

SELECT DISTINCT A, B
FROM RBase;

or

SELECT DISTINCT B, A
FROM RBase;

Upvotes: 1

Bacon Bits
Bacon Bits

Reputation: 32145

You don't. In SQL columns are returned in the order specified by the query.

Unless you're talking about a trick question where you say this qualifies:

SELECT
    B
   ,A
FROM (
    SELECT
        A
       ,B
    FROM
        C) D

Or unless you're talking about displaying the columns in a different order in your application, in which case that depends completely on your application.

However, in pure SQL, the column order is defined by the query.

Upvotes: 1

lared
lared

Reputation: 1974

You could use a subquery:

SELECT A, B FROM (SELECT B AS A, A AS B FROM C) AS sq;

Obviously the column names won't match but the column content would be swapped.

Upvotes: 1

Related Questions