Today, I am diverging from the more technical posts that I routinely share. Instead, as the title suggests, I want to dive into a something a little more fun: the interview trick question.
Anybody that has interviewed for a job has most likely run into the trick question. Some interviewers like to throw out multiple trick questions all in an effort to trip up the candidate and get the candidate to doubt him/her self. Sure, there can be some benefit to throwing out a trick question or four. One such benefit would be to see how the candidate performs under pressure (see them squirm).
The downside to throwing out trick questions, in my opinion, would be that you can turn a serious candidate into an uninterested candidate. So, when throwing out the tricks, tread carefully.
Let’s take a look at an interview trick question candidate. This is a more technical question and is designed to make you think a little bit. Before reading on to see the answer, I implore that you try to answer the question for yourself legitimately.
How can you insert data into two tables using a single statement without the use of triggers, service broker or some other behind-the-scenes feature?
Are you thinking about it?
Do you have your answer yet?
Now that you have your answer, go ahead and continue reading.
Is your answer to this question something along the lines of “You can’t do that and this is just a trick question”?
Well, honestly, it is a bit of a trick question. But I assure you, you can certainly perform an insert into multiple tables from a single statement. Here is one such setup that demonstrates how you can do this:
CREATE TABLE tin1 ( t1id INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED , someval VARCHAR(100) ); CREATE TABLE tin2 ( t2id INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED , someval VARCHAR(100) ); GO INSERT INTO tin1 ( someval ) OUTPUT INSERTED.someval INTO dbo.tin2 ( someval ) VALUES ( 'double my insert pleasure' ); SELECT * FROM dbo.tin1; SELECT * FROM dbo.tin2;
Do you see how I was able to perform that insert into multiple tables? The trick is in using the OUTPUT clause. This little feature in SQL Server can be of great use for things such as building multiple staging tables during an ETL process.
Here is that little trick again just to highlight it.
OUTPUT INSERTED.someval INTO
There are cases when an interview trick question is suitable. It is when the purported question is truly more technical than trick and is really trying to evaluate your depth and knowledge of SQL Server. The puzzle during the interview boils down to figuring out when it is a trick and when it might not be. Then from there, work your way through possible solutions. But don’t be afraid to admit when you haven’t got a clue. That will be far more impressive than to try and flim-flam the interviewer.
I invite you to share your trick questions in the comments. Also, how did you solve this particular trick question?