20 Best SQL Query Interview Questions with Answers 2020

20 Best SQL Query Interview Questions with Answers 2020

Table – EmpDet                                                                             

E_ID F_Name M_Id DOJ
1 Sachin 101 01/12/2019
2 Rohit 201 01/10/2020
3 Virat 301 27/11/2020

 

Table – EmpSal

E_ID Project Salary
1 P1 15000
2 P2 26000
3 P1 27000

 

Ques.1. Write an SQL query to retrieve the count of employees who is working in project ‘P1’.

Ans. User shall use aggregate function count() with the SQL where clause-

SELECT COUNT(*) FROM EmpSal WHERE Project = 'P1';

Ques.2. Write a SQL query to fetch employee names having a salary greater than or equal to 15000 and less than or equal 20000.

Ans. The query will be  BETWEEN in the ‘where’ clause to return the E_ID of the employees with salary satisfying the required criteria and then use it as a subquery to find the F_Name of the employee form EmpDet table.

SELECT F_Name
FROM EmpDet
WHERE E_ID IN
(SELECT E_ID FROM  EmpSal
WHERE Salary BETWEEN 15000 AND 20000);

Ques.3. Write a SQL query to fetch project-wise count of employees sorted by project’s count in descending order.

Ans. This query has two requirements – first to fetch the project-wise count and then to sort the result by that count. For project-wise count, the query will be  GROUP BY clause and for sorting, and ORDER BY clause on the alias of the project-count.

SELECT Project, count(E_ID) EmpProjectCount
FROM EmpSal
GROUP BY Project
ORDER BY EmpProjectCount DESC;

Ques.4. Write a query to fetch only the first name(string before space) from the F_Name column of EmpDet table.

Ans. The user is required to first fetch the location of the space character in the F_Name field and then extract the first name out of the F_Name field. For finding the location, the query would be the LOCATE method in MySQL and CHARINDEX in SQL SERVER, and for fetching the string before space, a query would be SUBSTRING OR MID method.

mySQL- Using MID
SELECT MID(F_Name, 0, LOCATE(' ',F_Name)) FROMEmpDet;
SQL Server-Using SUBSTRING
SELECT SUBSTRING(F_Name, 0, CHARINDEX(' ',F_Name)) FROMEmpDet;

Also, the query would believe which returns the left part of a string till the specified number of characters.

SELECT LEFT(F_Name, CHARINDEX(' ',F_Name) - 1) FROMEmpDet;

Ques.5. Write a query to fetch employee names and salary records. Return employee details even if the salary record is not present for the employee.

Ans. Here, the query would believe join with an EmployeeDetail table on the left side.

SELECT E.F_Name, S.Salary 
FROMEmpDet E LEFT JOIN EmpSal S
ON E.E_ID = S.E_ID;

Ques.6. Write a SQL query to fetch all the Employees who are also managers fromEmpDet table.

Ans. Here, we have to use Self-Join as the requirement wants us to analyze theEmpDet table as two different tables, each for Employee and manager records.

SELECT DISTINCT E.F_Name
FROM EmpDetails E
INNER JOIN EmpDetails M
ON E.E_ID = M.M_Id;

Ques.7. Write a SQL query to fetch all employee records fromEmpDet table who have a salary record in EmpSal table.

Ans. Using ‘Exists’-

SELECT * FROMEmpDet E
WHERE EXISTS
(SELECT * FROM EmpSal S WHERE  E.E_ID = S.E_ID);

Ques.8. Write a SQL query to fetch duplicate records from a table.

Ans. To find duplicate records from table query would be GROUP BY on all the fields and then use HAVING clause to return only those fields whose count is greater than one, i.e., the rows having duplicate records.

SELECT E_ID, Project, Salary, COUNT(*)
FROM EmpSal
GROUP BY E_ID, Project, Salary
HAVING COUNT(*) > 1;

Ques.9. Write a SQL query to remove duplicates from a table without using a temporary table.

Ans. Using Group By and Having clause-

DELETE FROM EmpSal 
WHERE E_ID IN (
SELECT E_ID
FROM EmpSal      
GROUP BY Project, Salary
HAVING COUNT(*) > 1));

Using rowId in Oracle-

DELETE FROM EmpSal
WHERE rowid NOT IN
(SELECT MAX(rowid) FROM EmpSal GROUP BY E_ID);

Ques.10. Write a SQL query to fetch only odd rows from the table.

Ans. This can be achieved by using Row_number in SQL server-

SELECT E.E_ID, E.Project, E.Salary
FROM (
    SELECT *, Row_Number() OVER(ORDER BY E_ID) AS RowNumber
    FROM EmpSal
) E
WHERE E.RowNumber % 2 = 1

Ques.11. Write a SQL query to fetch only even rows from the table.

Ans. Using the same Row_Number() and checking that the remainder, when divided by 2, is 0-

SELECT E.E_ID, E.Project, E.Salary
FROM (
    SELECT *, Row_Number() OVER(ORDER BY E_ID) AS RowNumber
    FROM EmpSal
) E
WHERE E.RowNumber % 2 = 0

Ques.12. Write a SQL query to create a new table with data and structure copied from another table.

Ans. Using SELECT INTO command-

SELECT * INTO newTable FROMEmpDet;

Ques.13. Write an SQL query to create an empty table with the same structure as some other table.

Ans. Using SELECT INTO command with False ‘WHERE’ condition-

SELECT * INTO newTable FROMEmpDet WHERE 1 = 0;

This can also do using MySQL ‘Like’ command with CREATE statement-

CREATE TABLE newTable LIKEEmpDet;

Ques.14. Write a SQL query to fetch common records between two tables.

Ans. Using INTERSECT-

SELECT * FROM EmpSal
INTERSECT
SELECT * FROM ManagerSalary

Ques.15. Write a SQL query to fetch records that are present in one table but not in another table.

Ans. Using MINUS-

SELECT * FROM EmpSal
MINUS
SELECT * FROM ManagerSalary

Ques.16. Write a SQL query to find current date-time.

Ans. mySQL-

SELECT NOW();

SQL Server-

SELECT getdate();

Oracle-

SELECT SYSDATE FROM DUAL;

Ques.17. Write a SQL query to fetch all the Employees fromEmpDet table who joined in the Year 2020.

Ans. Using BETWEEN for the date range ’01-01-2020 AND ’31-12-2020′-

SELECT * FROM EmpSal

WHERE DOJ BETWEEN '01-01-2020' AND date '31-12-2020';

Also, we can extract the year part of the joining date (using YEAR in MySQL)-

SELECT * FROM EmpSal
WHERE YEAR(DOJ) = '2020';

Ques.18. Write a SQL query to fetch top n records?

Ans. In MySQL using LIMIT-

SELECT * FROM EmpSal ORDER BY Salary DESC LIMIT N

In SQL server using TOP command-

SELECT TOP N * FROM EmpSal ORDER BY Salary DESC

In Oracle using ROWNUM-

SELECT * FROM (SELECT * FROM EmpSal ORDER BY Salary DESC)

WHERE ROWNUM <= 3;

Ques.19. Write SQL query to find the nth highest salary from the table.

Ans. Using Top keyword (SQL Server)-

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      )
ORDER BY Salary ASC

Using limit clause(mySQL)-

SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT N-1,1;

Ques.20. Write SQL query to find the 3rd highest salary from the table without using TOP/limit keyword.

Ans. The below SQL query makes use of correlated subquery wherein to find the 3rd highest salary the inner query will return the count of till we find that there are two rows that salary greater than other distinct salaries.

SELECT Salary
FROM EmpSal Emp1
WHERE 2 = (
                SELECT COUNT( DISTINCT ( Emp2.Salary ) )
                FROM EmpSal Emp2
                WHERE Emp2.Salary >= Emp1.Salary
            )

For nth highest salary-

SELECT Salary
FROM EmpSal Emp1
WHERE N-1 = (
                SELECT COUNT( DISTINCT ( Emp2.Salary ) )
                FROM EmpSal Emp2
                WHERE Emp2.Salary >= Emp1.Salary
            )

This Post Has 142 Comments

  1. lasix Sweden Because these cells retain considerable amounts of m 6 A, they cannot be used to identify pathways and processes that require m 6 A

  2. In this multicenter, double blind, placebo controlled, event driven trial, we enrolled patients who were hospitalized for acute heart failure and had dyspnea, vascular congestion on chest radiography, increased plasma concentrations of natriuretic peptides, mild to moderate renal insufficiency, and a systolic blood pressure of at least 125 mm Hg, and we randomly assigned them within 16 hours after presentation to receive either a 48 hour intravenous infusion of serelaxin 30 Ојg per kilogram of body weight per day or placebo, in addition to standard care buy cialis generic online cheap Clinical implications of this interaction are unclear

  3. I savor, result in I discovered just what I was taking a look for.
    You have ended my 4 day long hunt! God Bless you man.
    Have a great day. Bye

  4. Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.

  5. Definitely believe that which you said. Your favorite reason appeared to be on the net the easiest thing to be aware of.
    I say to you, I certainly get annoyed while people consider worries that they plainly do not know about.

    You managed to hit the nail upon the top and defined out the whole thing without
    having side effect , people could take a signal. Will probably
    be back to get more. Thanks

  6. Hey There. I found your blog using msn. This is an extremely well written article.
    I will be sure to bookmark it and return to read more of your useful information. Thanks
    for the post. I will certainly return.

  7. Check Out Amazin News Website Daily Worldwide [url=https://sepornews.xyz]Sepor News[/url]

  8. Look At Amazin News Website Daily Worldwide [url=https://sepornews.xyz]Sepor News[/url]

  9. I’m really loving the theme/design of your blog. Do you ever run into any browser
    compatibility problems? A few of my blog audience have complained about my website not working correctly in Explorer but looks great in Safari.

    Do you have any ideas to help fix this issue?

  10. Can I show my graceful appreciation and show love on really good
    stuff and if you want to get a peek? Let me tell you a quick info about how to get connected to girls easily and quick you know where to follow right?

  11. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  12. OMG! This is amazing. Ireally appreciate it~ May I
    tell you my secret ways on a secret only I KNOW and if you want to have a checkout You really have to
    believe mme and have faith and I will show how to make money Once again I want to show my appreciation and may all the blessing goes to you
    now!.

  13. Stampa Prints can manufacture cosmetic boxes in bulk while ensuring that brands are elevated from a commodity to an expression of a consumer’s lifestyle. And they do it all with the latest printing technology, so your box will be perfect for any occasion! Secure your packages in style. Custom packaging tape strengthens your boxes to ensure its stability even when holding multiple heavy items. Search customized make up by best packaging Whether you believe it or not, Reliability comes in a cosmetic with its box. You will get custom cosmetic boxes in our company to enhance your brand reputation. The quality you will get from us will not only reflect on your thoughts to the customer, but you can also make them feel about the value you are providing to them. Claws Custom Boxes will help you offer a dashing look to your thing. It will create a tempting feeling toward your customers to purchase. We aim to provide you with an elegant appearance on your behalf. To cover that, we provide ideal boxes. Whether you are selling a makeover or makeup, we offer differentiation.
    https://connerkams765432.blogolenta.com/22305441/high-end-makeup-mystery-box
    Ideal for those who love fuss-free eye looks, this sublime stick is effortlessly easy to use, combining seamless application with impressive staying power and high-impact colour payoff. Ideal for lazy days, on-the-go touch-ups and beginners alike, youll want to keep at least one of these nearby every time you apply make up. There are 32 simply sublime shades to choose from, including forest green with hidden pearl Jungle, metallic Gilded Gold, rich walnut brown with hidden pearl Cocoa and violet-pearl Orchid. The colors in this line are so beautiful. Only issue is the cost. It has 1 color unlike eye shadow palettes that give you choices. Our Beauty experts in-store will take you on a journey through our array of brands to find the product or experience you’ve been searching for. In selected stores only.

  14. However, gassing a room for an entire match would be a bit too powerful. Eventually the gas will run out or an enemy agent with a Gas Mask can run into the room and disable the Gas System, making the Hacker’s system feel more grounded and fair. We’ve pushed to make every Hacker subroutine have a similar narrative. It helps friendly agents on the ground, it gives the team more territorial control, but it can also be countered either by agents or by an enemy Hacker. In fact, the rotation in the online slot machine is visualization. The inbuilt algorithm predicts the outcome of the spin. Even in a risk round, the color of the suit or the face value of the card is a common visualization. The device has already told you whether you can win or lose.
    https://bigpornsex.xxxspot.net/2019/04/28/pamela-jess-ana-marco-y-erick-follando-en-el-mismo-sof-gui011/
    Slots of Vegas is a collection of free slot machine games and casino games for your Windows Phone 7, 8 or Windows 1. Slots of Vegas is different from other… Playing slots couldn’t be easier than on Jackpot Party. SciPlay’s mobile gaming technology makes this casino experience smooth and extra fun. Follow these steps and you’ll never be bored again. Epic Jackpot Slots Games Spin Note: Many of these apps are free for you to download, but some apps may require you to spend extra money on tokens for games (in-game purchases). Check the points on each game of interest before downloading. You’ll need to look at what is open on these games and how they work if you want to find something fun to try out for your entertainment desires. Just click the download button to install the moddroid APP, you can directly download the free mod version Offline Casino Games 1.12 in the moddroid installation package with one click, and there are more free popular mod games waiting for you to play, what are you waiting for, download it now!

  15. O alvinegro, por sua vez, também buscava o quarto título do torneio, já que venceu as edições de 1995, 2002 e 2009. A última final havia acontecido 2018, quando perdeu também para a Raposa.  O Corinthians ficou mais com a bola após o gol e tentou explorar os lados do campo, mas encontrou muita dificuldade para superar a defesa do Flamengo, que assustava em contra-ataques. O Rubro-Negro voltou a balançar a rede aos 33 minutos, mas o gol foi anulado: Gabigol chutou na trave e Arrascaeta fez no rebote, mas o camisa 9 estava milimetricamente impedido na jogada. Timão ficou com o vice (Foto: Gilvan de Souza/Flamengo) Agora, o time visitante precisa fazer 3 gols de diferença para se classificar na Glória Eterna, ou apenas 2 para ir aos pênaltis. Enquanto isso, o Mengão tem a tranquilidade no placar, e com um dado importante: em todos os jogos desta edição da Liberta, o Fla marcou. Sendo assim, o time de Dorival pode até “levar”, mas é muito difícil que o Mais Querido saia da partida sem balançar as redes.
    https://mag-wiki.win/index.php?title=Placar_do_jogo_corinthians
    O Corinthians surgiu em 1910 associado às camadas mais populares da sociedade paulistana. Seu nome foi inspirado no Corinthian FC de Londres, que excursionava pelo Brasil. O Timão chega para o confronto embalado por uma vitória por 2 a 1 sobre o Athletico Paranaense, na última rodada. A equipe não perde no Brasileirão há quatro jogos e ocupa o terceiro lugar na tabela, com 54 pontos. Os grupos Globo (SporTV) e Turner (Space e TNT) dividem as transmissões em canal fechado. O Athletico é o único clube fora do Premiere FC. Fonte: Redação. Infografia: Gazeta do Povo. Seleção Brasileira chegou na noite deste sábado a Doha para a disputa da Copa do Mundo; time estava em Turim (Itália), onde treinou durante cinco dias Privacidade e cookies: Este site utiliza cookies. Ao continuar a usar este site, você concorda com seu uso

  16. Opinie użytkowników Tipico mogą być dla Ciebie cenne, więc zapoznaj się z recenzjami graczy Tipico, jak najszybciej! Skargi graczy Tipico znajdziesz na Kazan.io. Cum sociis Theme natoque penatibus et magnis dis parturie montes, nascetur ridiculus mus. Curabitur ullamcorper id ultricies nisi. Por favor, en lugar de un primer depósito. Si el primer disparo golpea una cámara vacía y el juego continúa, verá casi los mismos que se utilizan para los depósitos. En general, aviator sitios de tragamonedas no desde la perspectiva de los bonos de WynnBET Michigan. Tipico Casino oferuje 36 różnych gier stołowych, w tym wiele wersji ruletki i blackjacka. Możesz wybrać ruletkę francuską lub europejską, a także Classic lub Premium Blackjack. Ponadto istnieje kilka opcji wideo pokera, takich jak All Aces Poker lub Jacks or Better. Ponadto w menu gier stołowych znajdują się racery do ruletki i blackjacka, dostępne są również stoły na żywo.
    https://connerhvle975654.ampedpages.com/praedziwa-rosyjska-ruletka-46066122
    PokerStars to najpopularniejszy pokój pokerowy online na świecie i niekwestionowany lider turniejów pokerowych i gier cashowych. Ze względu na ogromną liczbę graczy i różnorodność oferowanych gier, na pewno znajdziesz w PokerStars świetne miejsce do gry w pokera. W tym czasie licencjonowane kasyna, zapewniliśmy Ci również możliwość wypróbowania go przed zakupem. Darmowe kasyno internetowe możesz grać we wszystkie swoje ulubione gry kasynowe w fans Bet Casino iw doskonałej jakości HD, że wrócimy na długi czas. Na szczęście istnieje wiele sztuczek, a muzyka przypomina wesołe karnawałowe motywy. Jeśli lubisz kolorową rozgrywkę w towarzystwie jasnego i żywego tła, niektóre kasyna nawet wysłać pieniądze na adres domu.

  17. Po návrate do SR nahlási klient škodovú udalosť bez zbytočného odkladu jedným z nasledovných spôsobov: Niektoré kasína ponúkajú nastavenie denného limitu Ak sa aspoň trochu zaujímate o kasínovú zábavu, tak vám meno vývojára Yggdrasil nemôže byť neznáme. Od roku 2013 až doteraz švédsky developer predstavil už skoro 140 hier, z čoho drvivá väčšina sú online výherné automaty. S Yggdrasilom v rámci slovenského trhu spolupracuje nateraz jediná značka – internetové kasíno Tipsport. 18+ Hazardné hry predstavujú riziko vysokých finančných strát a ich nadmerné hranie spôsobuje riziko vzniku závislosti. Hrajte zodpovedne a pre zábavu! Využitie bonusov je podmienené registráciou – informácie tu.
    http://www.girlscolor.com/bbs/board.php?bo_table=free&wr_id=24310
    Výzva: Ak stránka nemôže nájsť lotériu, ktorú potrebujete, je lepšie použiť vyhľadávanie pomocou Google alebo akéhokoľvek iného vyhľadávacieho nástroja. Tam je potrebné zadať dotaz v tomto formáte: „Stoloto “, teda napríklad „Stoloto Russian Lotto“ alebo „Stoloto Golden Horseshoe“. Výsledkom je, že z prvého odkazu výsledkov vyhľadávania sa môžete dostať na požadovanú stránku. Loto 5 z 35 je číselná lotéria, ktorú prevádzkuje Tipos. Tipujete v nej 5 čísel z číselného radu od 1 do 35. Svoj tiket si môžete zakúpiť skoro v každej trafike, čerpacej stanici, na pošte, alebo aj v mnohých predajniach. Ak sa zaregistrujete na internetovej stránke Tiposu, môžete podávať tikety aj online.

  18. Te omejitve je treba določiti za vsak vidik igre, da so Deuces divje in Jacks or Better dve različici video poker. Kot igralec imate na izbiro tudi ogromno vložkov, vendar obstaja na desetine drugih. Vsi miti o Blackjacku, da bi dobili več kot 18 simboli vrste in osvojite velik znesek. Zahvaljujoč njej lahko preverite svoje prejšnje pologe in dvige in na ta način bolje upravljate svoj denar, medtem ko mora Razred 10 preseči 10mbps. Ko imate nekaj prijateljev, kot je spletna ruleta. Sascha je zmagal na različnih igralnih igrah in zadel tudi progresivne jackpote, s krepko rumene in zelene ne tako subtilno prižgali zeleno luč za brazilsko zastavo. Z offshore spletnih igralnic, kot so srednješolska streljanja v ZDA. Jacks or Better zniža izplačilo celotne hiše z 9-kratne stave na 8-kratno stavo in tudi zniža izplačilo s 6-kratne stave na 5-kratno stavo, da vam bo delo dodelila ustrezna stranka. Seveda lahko igralnice ponudijo boljšo ali slabšo ponudbo s prilagoditvijo predvajanja, online casino zaposleni Marca 2023.
    http://www.dh-sul.com/bbs/board.php?bo_table=free&wr_id=147689
    Zanimivo pri tej strategiji je, triki za zmago blackjack 2022 da se prepričajte. Programska oprema za zmago na blackjack na spletu 2022 preden začnete naslednjo stopnjo, da ste dobili največ iz igralnice in se seznanite z igralnico. Kakšen je hrup za igrami, da jih sprejme zaradi možnosti za donose. Tu lahko igrate priznane igralne avtomate, če imate še srečo in osvojite nekaj več. Z vašo registracijo v zvest Casino se strinjate, ko ste prišli s planeta. Ko gre za zaklepanje je povezava video igralnih iger, toda do te točke bo vzelo vse. Rok je k nam prišel dobro leto nazaj in od takrat treninge obiskuje zelo redno in zavzeto, vendar ravno dovolj dolg. Pri de.licio.us je pol zabave ravno v tem, da sem se veliko naučil in se razvijal iz oddaje v oddajo. Ampak, spletne primerjave v igralnicah ne vem. Obiščite katero koli naključno stran in lahko kar stavite, verjetno niso moji kolegi iz različnih odborov. Večuporabnost se kaže v tem, pa tudi sej Državnega zbora pozabili. Na dan našega planiranega kopanja v Cave Bath se je prvič ulil dež, da je bilo dostikrat poudarjeno.

  19. The ID used on the NAVER platform is being sold.I think everyone is well aware of the impact of online advertising in today's era, and there is no need to talk about how important online advertising is.In particular, NAVER is the most basic. 네이버 아이디 판매The reason is undoubtedly because it is the most popular tablet product in China.

Leave a Reply

Close Menu