r/SQLServer • u/sghokie • Apr 07 '21
Interview question, 'You have this table with a 'billion' rows that have duplicates, how do you fix that?'
So I was on an interview last week and got posed this question by an interviewer. It's a good question for sure, I gave the usual solutions that I have actually used in the past (not on billion rows), but this guy wasn't buying any of them.
What I would normally do would be to identify the rows with a group by having count > 1 and insert them to a temp table and then delete the old recs and re-insert the grouped ones. Or you could do a set rowcount = 1 and then delete them out in a cursor. It depends obviously how bad off the tables is and how big the table is and how many actual duplicates exist. Worst case scenario would be to pump everything distinctly into a new table, drop the old one and renew the new one back to the old name.
Then he shifted to how you would prevent duplicates in the first place. My response was that you could add an index with a unique identifier.
Okay, redditors, what's the best way to handle this?
26
u/sitdolore Apr 07 '21
I would have ask him what are the limitations. Disk contention, log space, is the table accessed a "billion" times per second from a website, etc? Then give him an answer for each limitation (slow fix with a job over time, batch insert uniques into a different table then do a schema swap, YOLO and just do it all in one shot, etc).
As others pointed out, there are many answers. When I ask these types of questions during an interview, I'm not really interested in the exact method used. I am more interested in finding out if the person is going to just jump into it without caring what the effects are going to be in the production environment.
4
u/phunkygeeza Apr 07 '21
I think this is the right answer. Either this guy thinks he knows the ONLY clever way to do this and will declare any other answer wrong, or he is smart enough to not be looking for a technical answer.
3
u/sghokie Apr 07 '21
The way I felt during the question was that he wanted a technical way to solve the issue and I think he had some sort of magic way he must have discovered at some point on stack overflow and anyone else who didn't know his way must not be smart enough.
Of course, it should be a given that you can't just start jacking with production data in a production environment.
5
u/phunkygeeza Apr 07 '21
I would have been tempted to throw it back at him and ask, "how is it that he production rollout of this massive table was so badly planned that duplicates are a problem?", "is that representative of the systems I will be working on, because, thanks but no thanks"
4
4
2
u/saucerattack Apr 07 '21
You definitely come across interviewers who use interviews as opportunities to prove how smart they are. Generally, this comes from a combination of insecurity and narcissism and you pretty much want to avoid working with or for such folks.
2
u/sghokie Apr 08 '21
I wasn't really impressed with the guy. He came across as very arrogant the entire time. I was trying to explain how I run my ETL processes and he wasn't really listening or understanding.
5
u/elus Apr 07 '21 edited Apr 07 '21
Yeah on its own we don't really know enough about the problem statement to be able to give a good solution here. If we knew more about how the data enters the table (insert only no updates or deletes), the column types and average row size and by extension the number of rows we can expect per page, then we could toss out or focus on specific solutions.
But given the size I would imagine it's an append only table and that would allow us to chunk the process into manageable blocks. In my last place of employment, we actually had a process that does this on application log tables that grew too big. Since we couldn't do it all at once we settled on parameterizing the delete based on number of rows to process at each run and another parameter to specify the number of times to run the process per evening. And the thought was that we may not get it all on the first go but we would be able to eventually catch up. And it wouldn't blow up the log file in doing so.
edit: would --> wouldn't
5
u/PaulSandwich 1 Apr 07 '21
When I ask these types of questions during an interview, I'm not really interested in the exact method used. I am more interested in finding out if the person is going to just jump into it without caring what the effects are going to be in the production environment.
Ding ding ding!
This question isn't about the solution, it's about how much the candidate knows about the process and if they can spot the gaps in the question. Because real-world requirements almost always require some sleuthing, and I need to know you can handle that.
7
u/duendeacdc Apr 07 '21
I think its better to move the duplicated rows that matter, ans truncate instead of delete. So you don't have log.
2
u/BobDogGo 1 Apr 07 '21
truncate instead of delete. So you don't have log.
I thought that was true for years but it isn't. Truncate still logs, just differently: https://sqlperformance.com/2013/05/sql-performance/drop-truncate-log-myth
7
u/copper_blood Apr 07 '21
What would I do?
Get a cup of coffee.
Assign blame to someone in another Dept.
Consult Stackoverflow.com
Delete the Database.
Restore the Database from before I screwed it up.
Now Mr. Interviewer, lets now discuss my pay and benefits.
22
u/kagato87 Apr 07 '21
Removing dupes, I would do a windowed row-number to determine the pk, passing the pk for anything where the rank is greater than one to a delete statement. I use this on smaller tables when (a few thousand) and it is instant.
With dupes as (select pk, row_number() OVER (PARTITION BY <dupe definition>) as rownum from table
Delete from table where pk in (select pk from dupes where rownum > 1)
It will not be fast on a big table. It will probably blow caches. It will slam the disk. Do it during maintenance. If anything else is going on throw a maxdop hint on it to slow it down. Unless the indexes are perfect there's no way out of it, though you could do ranges depending on the clustered index design and how it relates to your duplicates, or chunk etl to a new table if the data is not changing. If you're really lucky the data is partitioned in a way you could leverage.
For preventing it, you use the "unique" constraint or a primary key.
6
u/DapperDroidLifter Apr 07 '21
Exactly what I was going answer here,it's one of my Apex snippets I keep saved.
3
u/Pole420 Apr 07 '21
Yup, using a window function with row number was my first thought too.
1
u/Consistent-Release11 Apr 10 '21
Yep, and I would also do that in while loop to avoid lock escalation
1
u/redial2 Apr 07 '21
This would work and just the same as the ssis solution might have to be broken out across multiple days depending on downtime.
If there is no downtime, you recover the last known good table from backup and do either this or the SSIS method on the data, preferably on another server.
When it's done, pipe it over to production then re-run the process on the set of new IDs which are on the real table but not on the cleaned table. At that point, make the switch.
Afterwards, check again to make sure nothing snuck through.
Done deal.
4
Apr 07 '21
[removed] — view removed comment
3
u/redial2 Apr 07 '21
Probably best to do this from the last known good backup on its own server, pipe the results to production, then re-run the process to close the gap
4
Apr 07 '21
[removed] — view removed comment
1
u/redial2 Apr 07 '21
If you process the set of records from the backup and move those over, then start from the max ID and run to the end of the table on prod - adding those new records to the table, then you make the switch and run one last time to catch anything that fell between the cracks, you will be ok, you will get everything
1
Apr 08 '21
[removed] — view removed comment
2
2
u/redial2 Apr 08 '21
You could manage it by subtracting values from the key column but it would definitely suck.
Great point.
2
u/overglorified_monkey Apr 07 '21
I’m no expert, but I’ve had the unfortunate privilege of doing something similar on a two billion row table. It’s a headache, and the nuts and bolts matter at that type of scale. This can literally take days to complete if done reasonably efficiently, if there’s no index a lot of solutions that work in (set) theory can blow up in your face. If you let this all happen in a single transaction, the transaction log can grow until you run out of disk space (whoops).
If you don’t have an existing index on the table or if there are a massive number of duplicates, I like the idea of creating a new blank table with a primary key and using SSIS to transfer clean records over.
If you do have an index and the number of duplicates is fairly small compared to size of the table, this is one of the limited use cases where I think a cursor might make sense. Set up a cursor to loop through the distinct values in your new primary key where duplicates exist (e.g group by [PK col(s)] having count(*) > 1...) and delete all duplicates for each. This way the transaction log stays under control and you can start/stop the process to run during low usage.
Curious if anyone has feedback and/or a better way to handle this. I find working with data at that scale to be pretty frustrating in SQL Server, even in simple recovery mode.
2
u/LZ_OtHaFA Apr 07 '21
just breaking it down:
add a bit column to the table with a default of 0
efficiently set it to 1 for dups
efficiently delete all rows with value 1
remove the bit column
A simple way to efficiently delete the rows is just set the row count to 1000 or possibly higher and loop through adding a 1 second pause if necessary (being sure your bucket size is sufficiently big enough where the pause does not become an issue for total run time).
2
Apr 07 '21
RIP your trans log folder.
1
2
u/Shwoomie Apr 07 '21
There are 2 things an interviewer is asking here: Do you have technical knowledge to even approach this problem, and do you have a methodical way of thinking.
I've found that even if I didn't have enough technical knowledge, if I laid out a systematic way of thinking to solve the problem, that is what they are actually looking for.
In that regard, there isn't an exact answer. There are a lot of approaches, and sitdolore gives a great answer in how to logically approach the problem and to ask questions to get at the real problem. A similar question is "How do you keep organized". There isn't an exactly correct answer, the interviewer wants to know that you have thought about this and you employ tools to keep yourself on track and organized.
1
u/ChaiTravelatte Apr 07 '21
you could use a CTE and then delete from the CTE, I'm actually doing that right now, although I can't remember if it's on the billion or just 100 million scale
7
u/Rex_Lee Apr 07 '21
CTE's run like a dog on large when you're touching lots of records. I would definitely try temp tables versus CTEs in that scenario
1
u/mycall Apr 07 '21
If the column count is small, do a select each column while grouping by each column. This will give you a unique record. You can insert these into another table if you wish.
1
u/cosmokenney Apr 07 '21
use "row_number() over partition by..." and delete the rows with a row_number > 1
Can't use a cursor with billions of rows unless you have some kind of massive machine. The loop will take a decade to run.
1
1
u/ScotJoplin Apr 07 '21
As others have said, use a windowed function.
If the question isn’t clear, always feel free to ask the interviewer for more details. If they don’t like any of your answer and want to move on, you can throw it back at them. You want to learn about them too, not just them about you. Ask “May I ask if you’ve faced this issue and how you solved it?” If they insist on asking how to prevent it first, that’s fine. After that, revisit your question and answers. If they aren’t prepared to do that, don’t take the job. Chances are you don’t want to work there.
0
Apr 07 '21
I probably would use SELECT DISTINCT to load unique records into a new table, commit, then drop the old table and rename the new table to the old name in a single transaction. This would require using some sys functions of SQL Server, and the equivalent in whatever other RDBMS.
14
u/BobDogGo 1 Apr 07 '21
I'd create an empty copy of that table with a unique constraint and use SSIS Dataflow to move the records to the new table and redirect error records to an error table or just nowhere if you don't care. Then rename the tables/adjust foreign keys etc.
I prefer that solution because SSIS dataflows allow you to adjust your batch sizes and minimize logging overhead