Common Mistakes
Here are mistakes I made during Hackerrank certification:
- using double quote
""instead of single quote"" - what is usage differences between
GROUP BYandDINSTINC - should we use
WHEREorHAVING - using
NOT IN
Differences GROUP BY and DISTINC
Understanding the difference between GROUP BY and DISTINCT is crucial for effective SQL querying. Here’s a breakdown of when to use each:
DISTINCT:
- Purpose: DISTINCT is used to retrieve unique values from one or more columns in a result set. It eliminates duplicate rows, showing each unique combination of the selected columns only once.
- When to use: When you simply want to see a list of unique values in a column or combination of columns. When you need to remove duplicate rows from your query results. It’s ideal for straightforward de-duplication.
- Example:
|
|
GROUP BY:
- Purpose: GROUP BY is used to group rows that have the same values in specified columns. It’s typically used in conjunction with aggregate functions (like COUNT(), SUM(), AVG(), MAX(), MIN()) to summarize data for each group.
- When to use: When you want to perform calculations or aggregations on groups of data. When you need to summarize data based on categories or groupings. When you want to analyze data in a summarized way.
- Example:
|
|
Key Differences Summarized:
- Aggregation:
GROUP BYis designed for aggregation.DISTINCTis not.
- Functionality:
DISTINCTremoves duplicate rows.GROUP BYorganizes rows into groups.
- Use Cases:
DISTINCTis for simple unique value retrieval.GROUP BYis for summarizing and analyzing grouped data. In essence, if you just want to see unique values, useDISTINCT. If you want to group data and perform calculations on those groups, useGROUP BY.
Using HAVING
my code was like
|
|
the main issue is that you can’t use an aggregate function like SUM(i.total_price)/COUNT(c.id) directly in a WHERE clause. You need to use a HAVING clause after the GROUP BY clause to filter based on aggregated results. Also, you need to use the subquery’s result from the CTE.
Here’s the corrected syntax:
|
|
Using NOT IN
It was not a mistake. But it is just a syntax that I need to familiar with. The problem was to filter the products were not sold.
|
|