[SQL] HackerRank: The Blunder

Eun LeeEun Lee
2 min read

Question

Samantha accidentally calculated the average salary by removing all zeros from the salary values. What is the difference between this miscalculated average and the actual average salary?(and round it up to the next intreger)

https://www.hackerrank.com/challenges/the-blunder/problem


Solution

REPLACE(`CAST`(SALARY AS `VARCHAR`), '0', '')

First, delete ‘0’ in SALARY Column to save Samanth from her mistake.

But problem is…SALARY column is designated as INT Type. So I changed data type to ‘VARCHAR’ by using ‘CAST’

Problem solved, replace ‘0’ to ‘’ simply.

CAST(REPLACE(CAST(SALARY AS VARCHAR), '0', '') AS **DECIMAL**))

And then, change data type into ‘DECIMAL’ but why not ‘INT’?

If we used INT type, the decimal places would be discarded, which is not suitable when we need to accurately calculate decimal values.

CEILING(AVG(cast (SALARY as DECIMAL)) 
    - AVG(CAST(REPLACE(CAST(SALARY AS VARCHAR), '0', '') AS DECIMAL)))

Last part, we get the value with DECIMAL. so just round it up!


Today I’ve learned

  1. TEXT TYPE
TypeExplanationExample
CHARFixed bytechar(5) → ‘123 ‘ (5byte)
VARCHARFelxible bytevarchar(5) → ‘123’ (3byte)
TEXTvery long textno max size limit
  1. INT TYPE
  • discard the decimal point and save/output only int
TypeRangebyte
int-2,147,483,648 ~ 2,147,483,6474
smallint-32,768 ~ 32,7672
tinyint0 ~ 2551
biglint-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,8078
  1. FLOAT TYPE
  • decimal/ numeric → calculate accurately

  • float/real → save or calculate data efficiently

TypeRangebyte
decimalup to 38placesmax 17bytes
numericup to 38placesmax 17bytes
float1.79E-308 ~ 1.79E+3088
real1.18E-38 ~ 3.40E+384

For the first time, I thought about efficiency of Database. Choose the right data type according to my circumstance

0
Subscribe to my newsletter

Read articles from Eun Lee directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Eun Lee
Eun Lee