SQL Server beginner interview questions and answers

Part - 1

How to generate a random string of 10 character?

There are many ways to generate a random string. This one is a simple way to do it.

SELECT RIGHT(CAST(NEWID() AS VARCHAR(255)),10)

How to generate a random number?

Generate a random number from 0 through 1, exclusive.

SELECT RAND()

Generate a random number between 0 and 100.

SELECT FLOOR(RAND()*101)
SELECT CAST(RAND()*100 AS INT)

Generate a random number between 1 and 100

SELECT CEILING(RAND()*100)

Generate a random number between 10 and 30

SELECT 10 + FLOOR(RAND()*30)

COUNT(*) vs COUNT(1) vs SUM(1)

What is the output of the below queries when table is empty and non-empty?

SELECT COUNT(*) FROM STUDENT
SELECT COUNT(1) FROM STUDENT
SELECT SUM (1) FROM STUDENT

When the table is empty:

image.png When the table is non-empty:

image.png

How to select all the even number records from a table?

There is a table participant which has more than 10k records and you need to select all the records with id in even number (i.e. 2,4,6,8 etc)

image.png

SELECT * FROM dbo.participant WHERE id % 2 = 0

How to select all the odd number records from a table?

There is a table participant which has more than 10k records and you need to select all the records with id in odd number (i.e. 1,3,5,7 etc)

screenshot_001037_2022_05_19_11_47_19.png

SELECT * FROM dbo.participant WHERE id % 2 = 1

How to select all the records from the table except the id's which are divisible by 3?

There is a table participant which has more than 10k records and you need to select all the records from the table except id in 3,6,9, etc

screenshot_001036_2022_05_19_11_42_56.png

SELECT * FROM dbo.participant WHERE id % 3 <> 0

Did you find this article valuable?

Support Rajanand's Blog by becoming a sponsor. Any amount is appreciated!