50 SQL Server Query 1712112772
50 SQL Server Query 1712112772
50 SQL Server Query 1712112772
• CREATE DATABASE:
• ORG:
2. SHOW DATABASES;
This command is used to display a list of all databases on the SQL server.
SHOW DATABASES:
SHOW DATABASES is an SQL statement that lists all the databases present on the SQL
server.
3. USE ORG;
This command is used to switch to the "ORG" database, making it the current active
database for subsequent SQL operations.
USE:
USE is an SQL statement that specifies which database you want to work with.
ORG:
"ORG" is the name of the database that you want to switch to.
SQL Query Example @CoderBaba 100 SQL queries
Explanation in Detail:
Creating a Database:
• After executing the above command, you will see a list of all databases, including
the newly created "ORG" database.
Example output:
SQL Components:
1. CREATE TABLE:
• The CREATE TABLE statement is used to create a new table in the database.
2. Worker:
3. Columns:
• WORKER_ID:
• Constraints:
• FIRST_NAME:
• LAST_NAME:
• SALARY:
• JOINING_DATE:
• DEPARTMENT:
Explanation:
• INSERT INTO:
• The INSERT INTO statement is used to insert new records into a table.
• Worker:
• "Worker" is the name of the table into which the records will be inserted.
• These are the column names of the "Worker" table where the data will be
inserted.
• VALUES:
• The VALUES keyword is used to specify the values to be inserted into the
respective columns.
Records to Insert:
The query is inserting the following records into the "Worker" table:
SQL Query Example @CoderBaba 100 SQL queries
Example:
After executing the INSERT INTO query, the "Worker" table will have the following
records:
SQL Query Example @CoderBaba 100 SQL queries
SQL Components:
1. CREATE TABLE:
• The CREATE TABLE statement is used to create a new table in the database.
2. Bonus:
• These are the columns of the "Bonus" table with their respective data types.
4. FOREIGN KEY:
• The FOREIGN KEY constraint is used to ensure the referential integrity of the
data in the table.
5. REFERENCES Worker(WORKER_ID):
6. ON DELETE CASCADE:
• This specifies the action to be taken when a referenced row in the "Worker"
table is deleted. CASCADE means that if a row in the "Worker" table is
deleted, then the corresponding rows in the "Bonus" table with the same
WORKER_REF_ID will also be automatically deleted.
SQL Query Example @CoderBaba 100 SQL queries
Explanation:
Table Creation:
Columns:
• ON DELETE CASCADE: This means that if a row in the "Worker" table is deleted,
then the corresponding rows in the "Bonus" table with the same WORKER_REF_ID
will also be automatically deleted to maintain referential integrity.
Here's how the "Bonus" table might look after creating it:
• BONUS_DATE: The date and time when the bonus was given.
The WORKER_REF_ID is a foreign key that references the WORKER_ID column in the
"Worker" table. If a row with a specific WORKER_ID is deleted from the "Worker" table, the
corresponding rows in the "Bonus" table with the same WORKER_REF_ID will be
automatically deleted due to the ON DELETE CASCADE constraint.
SQL Components:
1. INSERT INTO:
• The INSERT INTO statement is used to insert new records into a table.
2. Bonus:
• Bonus is the name of the table where the data will be inserted.
• These are the columns of the Bonus table into which data will be inserted.
4. VALUES:
• The VALUES keyword is used to specify the values to be inserted into the
specified columns.
Explanation:
The query is inserting multiple rows of data into the Bonus table with the following
columns: WORKER_REF_ID, BONUS_AMOUNT, and BONUS_DATE.
Data to be Inserted:
Here is the data that will be inserted into the Bonus table:
Query Breakdown:
SQL Query Example @CoderBaba 100 SQL queries
• This specifies that the data should be inserted into the Bonus table.
• This part specifies the columns of the Bonus table where the data will be
inserted.
• VALUES:
• This keyword indicates that the following values will be inserted into the
specified columns.
Example:
If the Bonus table is initially empty, executing the above query will insert the provided data
into the table. After executing the query, the Bonus table will look like:
SQL Components:
1. CREATE TABLE:
• The CREATE TABLE statement is used to create a new table in the database.
2. Title:
3. Column Definitions:
• WORKER_REF_ID INT:
• WORKER_TITLE CHAR(25):
• AFFECTED_FROM DATETIME:
• REFERENCES Worker(WORKER_ID):
• ON DELETE CASCADE:
• This means that if a record in the Worker table is deleted, all related
records in the Title table with the corresponding WORKER_REF_ID
will also be deleted automatically.
Explanation in Detail:
The query is creating a table named "Title" with the following columns:
SQL Query Example @CoderBaba 100 SQL queries
1. WORKER_REF_ID:
• This column is of type INT and is likely used to reference a worker's ID from
another table (presumably the Worker table).
2. WORKER_TITLE:
• This column is of type CHAR(25) and is intended to store the title of the
worker, such as "Manager", "Developer", etc.
3. AFFECTED_FROM:
• This column is of type DATETIME and is likely used to store the date and time
from which the title is affected or valid.
• The FOREIGN KEY constraint ensures the integrity of the data. It makes sure
that the values in the WORKER_REF_ID column in the Title table correspond
to values in the WORKER_ID column in the Worker table.
In this example:
• The Worker table has been created with a WORKER_ID, FIRST_NAME, and
LAST_NAME.
• A worker named "John Doe" with WORKER_ID of 1 has been added to the Worker
table.
• The Title table has been created with a WORKER_REF_ID, WORKER_TITLE, and
AFFECTED_FROM.
• A title of "Manager" for the worker with WORKER_REF_ID of 1 has been added to the
Title table.
SQL Query Example @CoderBaba 100 SQL queries
Output:
SQL Query Example @CoderBaba 100 SQL queries
Q-2. Write an SQL query to fetch “FIRST_NAME” from the Worker table in upper case.
Q-3. Write an SQL query to fetch unique values of DEPARTMENT from the Worker table.
In this query:
SQL Query Example @CoderBaba 100 SQL queries
• FROM Worker: specifies the table from which the data will be retrieved.
Q-4. Write an SQL query to print the first three characters of FIRST_NAME from the
Worker table.
Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the first name
column ‘Amitabh’ from the Worker table.
In this query:
• FROM Worker: specifies the table from which the data will be retrieved.
Q-6. Write an SQL query to print the FIRST_NAME from the Worker table after removing
white spaces from the right side.
Ans.
In this query:
SQL Query Example @CoderBaba 100 SQL queries
• FROM Worker: specifies the table from which the data will be retrieved.
Q-7. Write an SQL query to print the DEPARTMENT from the Worker table after
removing white spaces from the left side.
Ans.
Q-8. Write an SQL query that fetches the unique values of DEPARTMENT
from the Worker table and prints its length.
Ans.
Q-9. Write an SQL query to print the FIRST_NAME from the Worker table after replacing
‘a’ with ‘A’.
Ans.
Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME from the Worker
table into a single column COMPLETE_NAME. A space char should separate them.
Ans.
Q-11. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending.
SQL Query Example @CoderBaba 100 SQL queries
Ans.
Q-12. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending and DEPARTMENT Descending.
Ans.
Q-13. Write an SQL query to print details for Workers with the first names “Vipul” and
“Satish” from the Worker table.
Ans.
Q-14. Write an SQL query to print details of workers excluding first names, “Vipul” and
“Satish” from the Worker table.
Ans.
Q-15. Write an SQL query to print details of Workers with DEPARTMENT name as
“Admin”.
Ans.
Q-16. Write an SQL query to print details of the Workers whose FIRST_NAME contains
‘a’.
Ans.
SQL Query Example @CoderBaba 100 SQL queries
Q-17. Write an SQL query to print details of the Workers whose FIRST_NAME ends with
‘a’.
Ans.
Ans.
Q-19. Write an SQL query to print details of the Workers whose SALARY
lies between 100000 and 500000.
Ans.
Q-20. Write an SQL query to print details of the Workers who joined in Feb 2021.
Ans.
Q-21. Write an SQL query to fetch the count of employees working in the department
‘Admin’.
Ans.
Q-22. Write an SQL query to fetch worker names with salaries >= 50000 and <= 100000.
Ans.
Q-23. Write an SQL query to fetch the number of workers for each department in
descending order.
Ans.
Q-24. Write an SQL query to print details of the Workers who are also Managers.
Ans.
Q-25. Write an SQL query to fetch duplicate records having matching data in some
fields of a table.
Ans.
Q-26. Write an SQL query to show only odd rows from a table.
Ans.
Q-27. Write an SQL query to show only even rows from a table.
Ans.
Q-28. Write an SQL query to clone a new table from another table.
Ans.
Ans.
Q-30. Write an SQL query to show records from one table that another table does not
have.
Ans.
Q-31. Write an SQL query to show the current date and time.
Ans.
SELECT CURDATE();
Whereas the following MySQL query returns the current date and time:
SELECT NOW();
Here is a SQL Server query that returns the current date and time:
SELECT getdate();
Find this Oracle query that also returns the current date and time:
Q-32. Write an SQL query to show the top n (say 10) records of a table.
Ans.
MySQL query to return the top n records using the LIMIT method:
SQL Query Example @CoderBaba 100 SQL queries
SQL Server query to return the top n records using the TOP command:
Oracle query to return the top n records with the help of ROWNUM:
Now, that you should have a solid foundation in intermediate SQL, let’s take a look at
some more advanced SQL query questions. These questions will require us to use more
complex SQL syntax and concepts, such as nested queries, joins, unions, and intersects.
Q-33. Write an SQL query to determine the nth (say n=5) highest salary from a table.
Ans.
Q-34. Write an SQL query to determine the 5th highest salary without using the TOP or
limit method.
Ans.
The following query is using the correlated subquery to return the 5th highest salary:
SELECT Salary
FROM Worker W1
WHERE 4 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Use the following generic method to find the nth highest salary without using TOP or
limit.
SELECT Salary
FROM Worker W1
WHERE n-1 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Q-35. Write an SQL query to fetch the list of employees with the same salary.
Ans.
Q-36. Write an SQL query to show the second-highest salary from a table.
Ans.
Q-37. Write an SQL query to show one row twice in the results from a table.
Ans.
Ans.
Q-39. Write an SQL query to fetch the first 50% of records from a table.
Ans.
SELECT *
FROM WORKER
SQL Query Example @CoderBaba 100 SQL queries
Practicing SQL query interview questions is a great way to improve your understanding
of the language and become more proficient in using it. However, in addition to
improving your technical skills, practicing SQL query questions can also help you
advance your career. Many employers are looking for candidates who have strong SQL
skills, so being able to demonstrate your proficiency in the language can give you a
competitive edge.
Q-40. Write an SQL query to fetch the departments that have less than five people in
them.
Ans.
Q-41. Write an SQL query to show all departments along with the number of people in
there.
Ans.
Q-42. Write an SQL query to show the last record from a table.
Ans.
Ans.
Q-44. Write an SQL query to fetch the last five records from a table.
Ans.
Q-45. Write an SQL query to print the names of employees having the
highest salary in each department.
Ans.
Q-46. Write an SQL query to fetch three max salaries from a table.
Ans.
SELECT distinct Salary from worker a WHERE 3 >= (SELECT count(distinct Salary)
from worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;
Q-47. Write an SQL query to fetch three min salaries from a table.
Ans.
SQL Query Example @CoderBaba 100 SQL queries
SELECT distinct Salary from worker a WHERE 3 >= (SELECT count(distinct Salary)
from worker b WHERE a.Salary >= b.Salary) order by a.Salary desc;
Q-48. Write an SQL query to fetch nth max salaries from a table.
Ans.
SELECT distinct Salary from worker a WHERE n >= (SELECT count(distinct Salary)
from worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;
Q-49. Write an SQL query to fetch departments along with the total salaries paid for
each of them.
Ans.
Q-50. Write an SQL query to fetch the names of workers who earn the highest salary.
Ans.
---Create database
Use ORG
----
FIRST_NAME CHAR(25),
LAST_NAME CHAR(25),
SALARY INT,
JOINING_DATE DATETIME,
DEPARMENT CHAR(25)
);
--DATA INSERT
-- BONUS
WORKER_REF_ID INT,
BONUS_AMOUNT INT,
BONUS_DATE DATETIME,
REFERENCES Worker(WORKER_ID)
ON DELETE CASCADE
);
WORKER_REF_ID INT,
WORKER_TITLE CHAR(25),
AFFECTED_FROM DATETIME,
);
----
--Q-1. Write an SQL query to fetch “FIRST_NAME” from the Worker table using the alias
name <WORKER_NAME>.
--Q-2. Write an SQL query to fetch “FIRST_NAME” from the Worker table in upper case.
--Q-3. Write an SQL query to fetch unique values of DEPARTMENT from the Worker table.
--Q-4. Write an SQL query to print the first three characters of FIRST_NAME from the
Worker table.
--Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the first name
column ‘Amitabh’ from the Worker table.
--Q-6. Write an SQL query to print the FIRST_NAME from the Worker table after
removing
--Q-7. Write an SQL query to print the FIRST_NAME from the Worker table after
removing
--Q-8. Write an SQL query that fetches the unique values of DEPARTMENT from
--Q-9. Write an SQL query to print the FIRST_NAME from the Worker table after
replacing ‘a’ with ‘A’.
--Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME from the
Worker table into a single column
--Q-11. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending.
--Q-12. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending and DEPARTMENT Descending.
---Q-13. Write an SQL query to print details for Workers with the first names “Vipul”
and “Satish” from the Worker table.
----Q-14. Write an SQL query to print details of workers excluding first names,
“Vipul” and “Satish” from the Worker table.
--Q-15. Write an SQL query to print details of Workers with DEPARTMENT name as
“Admin”.
--Q-16. Write an SQL query to print details of the Workers whose FIRST_NAME
contains ‘a’.
--Q-17. Write an SQL query to print details of the Workers whose FIRST_NAME ends
with ‘a’.
--Q-19. Write an SQL query to print details of the Workers whose SALARY lies
between 100000 and 500000.
--Q-20. Write an SQL query to print details of the Workers who joined in Feb 2021.
--Q-21. Write an SQL query to fetch the count of employees working in the
department ‘Admin’.
--Q-22. Write an SQL query to fetch worker names with salaries >= 50000 and <=
100000.
--Q-23. Write an SQL query to fetch the number of workers for each department in
descending order.
SQL Query Example @CoderBaba 100 SQL queries
Explanation:
2. FROM Worker
• Specifies the table (Worker) from which the data will be retrieved.
3. GROUP BY DEPARTMENT
• Groups the result set by the DEPARTMENT column. This means the query
will count the number of workers for each unique department.
• Orders the result set by the No_Of_Workers in descending order. This will list
the departments with the highest number of workers first.
Example:
--Q-24. Write an SQL query to print details of the Workers who are also Managers.
Explanation:
• Worker AS W:
• This aliases the Worker table as W. The alias W is used to reference the
Worker table in the query.
• Title AS T:
• This aliases the Title table as T. The alias T is used to reference the Title table
in the query.
2. JOIN Condition:
• INNER JOIN:
• This joins the Worker table (W) with the Title table (T) based on the condition
specified.
• ON W.WORKER_ID = T.WORKER_REF_ID:
• This specifies the join condition. It joins rows from Worker and Title where
the WORKER_ID in Worker matches the WORKER_REF_ID in Title.
3. Filtering Condition:
• This is a filtering condition that restricts the result set to only include rows
where the WORKER_TITLE in the Title table is 'Manager'.
4. SELECT Statement:
• This selects the FIRST_NAME from the Worker table and WORKER_TITLE
from the Title table.
Overall Query:
The query is selecting the FIRST_NAME from the Worker table and the WORKER_TITLE
from the Title table, but only for workers who have a title of 'Manager'.
--Q-25. Write an SQL query to fetch duplicate records having matching data in some
fields of a table.
HAVING COUNT(*)>1
Explanation:
2. FROM Title
• This specifies that the data is being selected from the Title table.
• The GROUP BY clause is used to group rows that have the same values in specified
columns (in this case, WORKER_TITLE and AFFECTED_FROM).
• This means that the query will count the number of occurrences of each unique
combination of WORKER_TITLE and AFFECTED_FROM.
SQL Query Example @CoderBaba 100 SQL queries
• The HAVING clause is used to filter the results after the GROUP BY operation has
been performed.
• COUNT(*) > 1: This condition filters the groups to only include those where the
count of occurrences (COUNT(*)) is greater than 1.
Summary:
The SQL query is retrieving records from the Title table where:
• It then filters the results to only include those combinations that occur more than
once.
---Q-26. Write an SQL query to show only odd rows from a table.
--Q-27. Write an SQL query to show only even rows from a table.
--Q-28. Write an SQL query to clone a new table from another table.
--Q-30. Write an SQL query to show records from one table that another table does not
have.
MS SQL Server does not support the MINUS operator. Instead, you can achieve the same
result using the EXCEPT operator.
--Q-31. Write an SQL query to show the current date and time.
SELECT GETDATE()
---Q-32. Write an SQL query to show the top n (say 10) records of a table.
--Q-33. Write an SQL query to determine the nth (say n=5) highest salary from a table.
FROM
) AS SALARY
--Q-34. Write an SQL query to determine the 5th highest salary without using the TOP or
limit method.
WHERE 5=(
)
SQL Query Example @CoderBaba 100 SQL queries
----Q-35. Write an SQL query to fetch the list of employees with the same salary.
Explanation:
• The query uses two instances of the Worker table, named W and W1, to compare
the salaries of different workers.
2. SELECT Clause:
• The query selects the WORKER_ID, FIRST_NAME, and SALARY columns from the
Worker table.
3. WHERE Clause:
• W.SALARY = W1.SALARY: This condition ensures that the two workers being
compared have the same salary.
4. DISTINCT Keyword:
SELECT DISTINCT
• The DISTINCT keyword is used to ensure that the resulting pairs of workers are
unique and not duplicated.
Summary:
The SQL query retrieves distinct pairs of workers (W and W1) who have the same salary but
are different workers. It then selects and displays their WORKER_ID, FIRST_NAME, and
SALARY.
--Q-36. Write an SQL query to show the second-highest salary from a table.
Step-by-Step Explanation:
This subquery finds the maximum salary from the Worker table.
• This part of the query filters out the maximum salary from the main
table.
• The NOT IN clause excludes the maximum salary (i.e., the highest
salary) obtained from the subquery.
• This part of the query then selects the maximum salary from the
filtered results.
--Q-37. Write an SQL query to show one row twice in the results from a table.
UNION ALL
--Q-39. Write an SQL query to fetch the first 50% of records from a table.
---Q-40. Write an SQL query to fetch the departments that have less than five people in
them.
--Q-41. Write an SQL query to show all departments along with the number of people in
there.
--Q-42. Write an SQL query to show the last record from a table.
--Q-44. Write an SQL query to fetch the last five records from a table.
--Q-45. Write an SQL query to print the names of employees having the highest salary in
each department.
SQL Query Example @CoderBaba 100 SQL queries
--Q-46. Write an SQL query to fetch three max salaries from a table.
Explanation:
1. Main Query:
This part of the query retrieves the distinct salaries from the Worker table and aliases the
table as W.
2. Subquery:
• The subquery counts the number of distinct salaries that are less than or equal to
the salary of each worker from the main query (W.SALARY).
• This subquery is correlated with the main query, meaning it is executed for each row
in the main query.
3. WHERE Clause:
WHERE 3 >= ( SELECT COUNT(DISTINCT SALARY) FROM Worker W1 WHERE W.SALARY <=
W1.SALARY )
• This condition filters the rows where the count of distinct salaries that are less than
or equal to the salary of the current worker is less than or equal to 3.
SQL Query Example @CoderBaba 100 SQL queries
• Essentially, this will retrieve the salaries of the top 3 highest earners in the Worker
table.
4. ORDER BY Clause:
--Q-47. Write an SQL query to fetch three min salaries from a table.
Explanation:
Main Query:
• This part of the query retrieves all distinct salary values from the Worker table and
assigns the table an alias W.
Subquery:
• This subquery counts the number of distinct salary values that are less than or
equal to the salary of each record in the main query. It uses the same Worker table
but with a different alias W1.
WHERE 3 >= ( SELECT COUNT(DISTINCT SALARY) FROM Worker W1 WHERE W.SALARY >=
W1.SALARY )
• The WHERE clause filters the records based on the count of distinct salary values.
• The condition 3 >= indicates that we are interested in the top 3 highest salaries.
ORDER BY clause:
• This sorts the result set in descending order based on the salary.
SQL Query Example @CoderBaba 100 SQL queries
--Q-48. Write an SQL query to fetch nth max salaries from a table.
--Q-49. Write an SQL query to fetch departments along with the total salaries paid for
each of them
--Q-50. Write an SQL query to fetch the names of workers who earn the highest salary.