14

I am trying to learn about deleting duplicate records from a Hive table.

My Hive table: 'dynpart' with columns: Id, Name, Technology

Id  Name  Technology
1   Abcd  Hadoop
2   Efgh  Java
3   Ijkl  MainFrames
2   Efgh  Java

We have options like 'Distinct' to use in a select query, but a select query just retrieves data from the table. Could anyone tell how to use a delete query to remove the duplicate rows from a Hive table.

Sure that it is not recommended or not the standard to Delete/Update records in Hive. But I want to learn how do we do it.

1
  • Is there a way to fasten the process? my dynamic-partitioned ext. hive table contains over 1 Mil records, with over 10% duplicates. Sep 30, 2021 at 7:28

3 Answers 3

31

You can use insert overwrite statement to update data

insert overwrite table dynpart select distinct * from dynpart;
1
  • 3
    Is there any other way where we don't have to delete the entire table and delete records
    – salmanbw
    Dec 31, 2017 at 8:47
11

Just in case when your table has duplicate rows on few or selected columns. Suppose you have a table structure as shown down below:

id  Name    Technology
1   Abcd    Hadoop
2   Efgh    Java       --> Duplicate
3   Ijkl    Mainframe
2   Efgh    Python     --> Duplicate

Here id & Name columns having duplicate rows. You can use analytical function to get the duplicate row as:

select * from
(select Id,Name,Technology,
row_Number() over (partition By Id,Name order by id desc) as row_num
from yourtable)tab
where row_num > 1;

This will give you output as:

id  Name    Technology  row_num
2   Efgh    Python           2

When you need to get both the duplicate rows:

select * from
(select Id,Name,Technology,
count(*) over (partition By Id,Name order by id desc) as duplicate_count
from yourtable)tab
where duplicate_count> 1;

Output as:

id  Name    Technology  duplicate_count
2   Efgh    Java             2
2   Efgh    Python           2
2
  • 2
    How to get rid of duplicate value Sep 11, 2019 at 6:55
  • @JonAndrews regarding vikrant's answer, using the query within a CTE command will be a solution for removing the duplicates: e.g. with duplicates_rank as (select Id,Name,Technology, row_Number() over (partition By Id,Name order by id desc) as row_num from yourtable) delete from duplicates_rank where row_num<>1 Sep 28, 2022 at 8:35
2

you can insert distinct records into some other table

create table temp as select distinct * from dynpart
2
  • 2
    or without new table: insert overwrite table dynpart select distinct * from dynpart
    – fi11er
    Apr 7, 2017 at 20:41
  • @fi11er, your answer is working. If you can put your comment in an answer, I will accept it.
    – Metadata
    Apr 8, 2017 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.