Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Databases and SQL: Incorrect use of column alias in HAVING clause in SQL example #29078

Open
3 tasks done
dekr1sh opened this issue Nov 12, 2024 · 0 comments
Open
3 tasks done

Comments

@dekr1sh
Copy link

dekr1sh commented Nov 12, 2024

Checks

Describe your suggestion

Suggestion: Correct SQL Example to Avoid Alias in HAVING Clause

Issue:
The SQL snippet on the page currently uses a column alias (posts_written) in the HAVING clause:

SELECT users.id, users.name, COUNT(posts.id) AS posts_written
  FROM users
  JOIN posts ON users.id = posts.user_id
  GROUP BY users.id
  HAVING posts_written >= 10;

Using a column alias in HAVING is not supported in standard SQL due to the query execution order. HAVING is processed before the SELECT statement assigns any aliases, so the alias posts_written does not yet exist at that point in the query execution. This can lead to an error in many SQL databases.

Proposed Solution:
To ensure compatibility across SQL databases and adhere to SQL standards, it would be better to use the full expression (COUNT(posts.id)) in the HAVING clause:

SELECT users.id, users.name, COUNT(posts.id) AS posts_written
  FROM users
  JOIN posts ON users.id = posts.user_id
  GROUP BY users.id
  HAVING COUNT(posts.id) >= 10;

Explanation:
This adjustment will ensure that the query is compatible with SQL databases that strictly follow standard SQL, improving the reliability of the example for learners.

Path

Node / JS

Lesson Url

https://www.theodinproject.com/lessons/node-path-databases-databases-and-sql

(Optional) Discord Name

de_kr1sh

(Optional) Additional Comments

Looking forward to contributing to this issue as it will be my first contribution to an open-source project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant