0

I come across this scenario frequently in sql and I have seen it done, but would like to summarize the case when/when not to reference a new variable within a statement.

  1. This doesn't work -
SELECT 
COUNT(id) AS total_id,
COUNT(DISTINCT id) AS distinct_id,
total_id - distinct_id AS var
FROM mytable
  1. but this does -
SELECT 
COUNT(id) AS total_id,
COUNT(DISTINCT id) AS distinct_id,
COUNT(id) - COUNT(DISTINCT id) AS var
FROM mytable

How can I implement scenario 1?

4
  • You can reference a named variable outside the query [select total_id from (select count(id) as total_id from mytable)z]. It makes sense when you need to, but is not needed in your example above. Commented Feb 10, 2021 at 22:25
  • what's wrong with second query? that's how you do it in sql Commented Feb 10, 2021 at 22:35
  • very simple use case above - applying to above, how would that look? Commented Feb 10, 2021 at 22:36
  • 1
    Your misconception might be to think an alias is like a variable in a procedural language. It is not. It just determines the name of the column in the result. Commented Feb 10, 2021 at 22:37

1 Answer 1

1

You can use a subquery.

PostgreSQL:
SELECT total_id, distinct_id, (total_id + distinct_id) as var FROM
(
    SELECT COUNT(id) AS total_id, COUNT(DISTINCT id) AS distinct_id
    FROM mytable
) as m
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I was looking for, thank you!

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.