Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

DBMS SQL

Uploaded by

maangoo567
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

DBMS SQL

Uploaded by

maangoo567
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Write the query to create a new table.

CREATE TABLE tableName (columnName datatype, columnName datatype, ... );

2. Write the query to insert a new record into a table:

INSERT INTO tableName (Column1, Column2, ?) VALUES (Value1, Value2, ?);

3. Write the query to delete records from a table:

DELETE FROM tableName WHERE condition;

4. Write the query to update records in a table:

UPDATE tableName SET columnName = newValue WHERE condition;

5. Write the query to delete a table from the database:

DROP TABLE tableName;

6. Write the query to select all records from a table to retrieve data:

SELECT * FROM tableName;


7. Write the query to select the specific column from a table:

SELECT Column1, Column2 FROM tableName;

8. Write the query to select distinct values from a column:

SELECT DISTINCT columnName FROM tableName;

9. Write the query to filter records using a WHERE clause:

SELECT * FROM tableName WHERE condition;

10. Write the query to sort records in descending order:

SELECT * FROM tableName ORDER BY columnName DESC;

11. Write the query to sort records in ascending order:

SELECT * FROM tableName ORDER BY columnName ASC;


12. Write the query to join two tables based on a common column:

SELECT * FROM Table1 JOIN Table2 ON Table1.columnName = Table2.columnNam


e;

13. Write the query to count the number of rows in a table.

We will use the COUNT() function to count the number of rows. The statement is given
below:
SELECT COUNT(*) FROM tableName;

14. Write the query to group records and calculate aggregate functions:

SELECT columnName, COUNT(*), AVG(columnName) FROM tableName GROUP BY


columnName;

15. Write the query to limit the number of rows returned in a result set.

We will use the LIMIT clause to limit the number of rows. The statement is given below:

SELECT columnName FROM tableName LIMIT 10;

16. Write the query to find the sum of values in a column:

SELECT SUM(columnName) FROM tableName;

17. Write the query to find the average value of a column:

SELECT AVG(columnName) FROM tableName;


18. Write the query to get the minimum value from a column:

SELECT MIN(columnName) FROM tableName;

19. Write the query to retrieve the maximum value from a column:

SELECT MAX(columnName) FROM tableName;

20. Write the query to retrieve rows with values within a specified range:

SELECT columnName FROM tableName WHERE columnName BETWEEN Value1 A


ND Value2;
21. Write the query to retrieve rows with values matching a list of specified values:

SELECT columnName FROM tableName WHERE columnName


IN (Value1, Value2, Value3);

22. Write the query to search for patterns in a column using wildcard characters:

SELECT columnName FROM tableName WHERE columnName LIKE 'abc%';

23. Write the query to filter data based on aggregate functions in a GROUP BY query:

SELECT Column1, COUNT(Column2) FROM tableName GROUP BY Column1 HAVIN


G COUNT(Column2) > 5;
24. Write the query to retrieve rows with dates within a specified range:

SELECT columnName FROM tableName WHERE columnName BETWEEN '2023-01-


01' AND '2023-07-30';

25. Write the query to combine the result sets of two or more SELECT statements:

SELECT * FROM Table1 UNION SELECT columnName FROM Table2;

26. Write the query to perform conditional logic in a query:

SELECT columnNamse, CASE WHEN Condition1 THEN 'Value1' WHEN Condition2


THEN 'Value2' ELSE 'Value3' END AS newColumn FROM tableName;

27. Write the query to delete all rows from a table, but keeps the table structure:

TRUNCATE TABLE tableName;

28. Write the query to create an index on one or more columns of a table:

CREATE INDEX indexName ON tableName (Column1, Column2);

29. Write the query to modify the structure of an existing table:

ALTER TABLE tableName ADD columnName datatype;


30. Write the query to return the first non-null value from a list of expressions:

SELECT COALESCE(Column1, Column2,.. ColumnN) AS Result FROM tableName;


31. Write the query to return null if two expressions are equal, otherwise, return the first
expression.

We will use the NULLIF() function to do so, the statement is given below:

SELECT NULLIF(Column1, 0) AS result FROM tableName;

Real-life based questions for each of the SQL queries:


1. Create a new table:
- As a database administrator for a retail company, how would you design a table to store
customer information, including their name, email, and phone number?

2. Insert a new record into a table:


- Imagine you're a sales representative entering a new customer's data into the CRM system. Walk
me through the process of inserting this information into the database.

3. Delete records from a table:


- In an online bookstore, how would you delete all customer reviews that were flagged as spam or
inappropriate?

4. Update records in a table:


- As an inventory manager for a grocery store, how would you update the quantity of a product in
the database after receiving a new shipment?

5. Delete a table from the database:


- Suppose you're decommissioning an old feature in a software application. Explain the process of
removing the corresponding table from the database.

6. Select all records from a table to retrieve data:


- As a customer service representative, how would you retrieve all orders placed by a specific
customer from the database?

7. Select specific column from a table:


- In a hospital's patient management system, how would you retrieve the names and ages of all
patients currently admitted?

8. Select distinct values from a column:


- In an online forum, how would you retrieve a list of unique usernames from the database to
display on the registration page?

9. Filter records using a WHERE clause:


- As a financial analyst, how would you retrieve all transactions above $1000 made by a specific
client from the banking database?

10. Sort records in descending order:


- In an e-commerce platform, how would you display a list of products sorted by price from
highest to lowest?

11. Sort records in ascending order:


- As a teacher, how would you retrieve a list of student grades sorted alphabetically by their last
names?

12. Join two tables based on a common column:


- In a university database, how would you retrieve a list of students along with their respective
majors by joining the "students" and "majors" tables?

13. Count the number of rows in a table:


- As an IT manager, how would you determine the total number of active user accounts in the
company's system?

14. Group records and calculate aggregate functions:


- In a sales database, how would you calculate the total revenue generated by each product
category?

15. Limit the number of rows returned in a result set:


- As a news website administrator, how would you display only the 10 most recent articles on the
homepage?

16. Find the sum of values in a column:


- In a financial application, how would you calculate the total balance across all bank accounts
held by a specific client?

17. Find the average value of a column:


- In a survey database, how would you calculate the average satisfaction rating given by customers
for a particular product?

18. Get the minimum value from a column:


- In a temperature monitoring system, how would you determine the coldest temperature
recorded in a specific location?

19. Retrieve the maximum value from a column:


- In an online gaming platform, how would you find the highest score achieved by any player in a
particular game?

20. Retrieve rows with values within a specified range:


- As a real estate agent, how would you retrieve a list of properties with prices between $200,000
and $300,000 from the database?

21. Retrieve rows with values matching a list of specified values:


- In a product inventory system, how would you retrieve a list of products with specific SKUs
provided by the warehouse manager?

22. Search for patterns in a column using wildcard characters:


- In a customer database, how would you retrieve email addresses of all customers whose emails
start with "john" for a targeted email campaign?

23. Filter data based on aggregate functions in a GROUP BY query:


- In a restaurant's reservation system, how would you retrieve a list of tables that have been
reserved more than 5 times in the past month?

24. Retrieve rows with dates within a specified range:


- In a scheduling application, how would you retrieve a list of appointments scheduled between
January 1st, 2023, and July 30th, 2023?

25. Combine the result sets of two or more SELECT statements:


- In a social media platform, how would you merge the lists of followers and followings for a
user's profile page?

26. Perform conditional logic in a query:


- In an HR database, how would you categorize employees into different salary brackets based on
their years of experience?

27. Delete all rows from a table, but keep the table structure:
- In a testing environment, how would you clear out all test data from the "user" table before
running a new round of tests?

28. Create an index on one or more columns of a table:


- In a large dataset of customer orders, how would you improve query performance by creating an
index on the "customer_id" column?

29. Modify the structure of an existing table:


- In a blogging platform, how would you add a new column to the "posts" table to track the
number of views each post receives?

30. Return the first non-null value from a list of expressions:


- In a survey database, how would you display the primary language spoken by respondents,
prioritizing their preferred language if available?

31. Return null if two expressions are equal, otherwise, return the first expression:
- In a voting system, how would you handle cases where two candidates receive the same number
of votes, returning null to indicate a tie?

Answers:

1. Create a new table:


- Answer: To create a table to store customer information, you would execute the SQL query:
`CREATE TABLE customers (customer_id INT PRIMARY KEY, name VARCHAR(255), email
VARCHAR(255), phone VARCHAR(20));`

2. Insert a new record into a table:


- Answer: As a sales representative, you would execute the SQL query to insert a new customer's
data: `INSERT INTO customers (name, email, phone) VALUES ('John Doe',
'john@example.com', '+1234567890');`

3. Delete records from a table:


- Answer: To delete all flagged customer reviews from the database, you would execute the SQL
query: `DELETE FROM reviews WHERE flagged = 'spam' OR flagged = 'inappropriate';`

4. Update records in a table:


- Answer: As an inventory manager, to update the quantity of a product after receiving a new
shipment, you would execute the SQL query: `UPDATE products SET quantity = quantity + 100
WHERE product_id = 'ABC123';`

5. Delete a table from the database:


- Answer: To remove an old feature's corresponding table from the database, you would execute
the SQL query: `DROP TABLE old_feature_data;`

6. Select all records from a table to retrieve data:


- Answer: As a customer service representative, to retrieve all orders placed by a specific
customer, you would execute the SQL query: `SELECT * FROM orders WHERE customer_id =
'12345';`

7. Select specific column from a table:


- Answer: In a hospital's patient management system, to retrieve the names and ages of all
patients currently admitted, you would execute the SQL query: `SELECT name, age FROM patients
WHERE admitted = true;`

8. Select distinct values from a column:


- Answer: In an online forum, to retrieve a list of unique usernames from the database, you would
execute the SQL query: `SELECT DISTINCT username FROM users;`

9. Filter records using a WHERE clause:


- Answer: As a financial analyst, to retrieve all transactions above $1000 made by a specific client,
you would execute the SQL query: `SELECT * FROM transactions WHERE amount > 1000 AND
client_id = 'ABC123';`

10. Sort records in descending order:


- Answer: In an e-commerce platform, to display a list of products sorted by price from highest to
lowest, you would execute the SQL query: `SELECT * FROM products ORDER BY price DESC;`

11. Sort records in ascending order:


- Answer: As a teacher, to retrieve a list of student grades sorted alphabetically by their last
names, you would execute the SQL query: `SELECT * FROM grades ORDER BY last_name ASC;`

12. Join two tables based on a common column:


- Answer: In a university database, to retrieve a list of students along with their respective majors,
you would execute the SQL query: `SELECT students.name, majors.major FROM students INNER
JOIN majors ON students.major_id = majors.major_id;`

13. Count the number of rows in a table:


- Answer: As an IT manager, to determine the total number of active user accounts in the
company's system, you would execute the SQL query: `SELECT COUNT(*) FROM users WHERE
status = 'active';`

14. Group records and calculate aggregate functions:


- Answer: In a sales database, to calculate the total revenue generated by each product category,
you would execute the SQL query: `SELECT category, SUM(revenue) FROM sales GROUP BY
category;`

15. Limit the number of rows returned in a result set:


- Answer: As a news website administrator, to display only the 10 most recent articles on the
homepage, you would execute the SQL query: `SELECT * FROM articles ORDER BY publish_date
DESC LIMIT 10;`

16. Find the sum of values in a column:


- Answer: In a financial application, to calculate the total balance across all bank accounts held by
a specific client, you would execute the SQL query: `SELECT SUM(balance) FROM accounts
WHERE client_id = 'ABC123';`

17. Find the average value of a column:


- Answer: In a survey database, to calculate the average satisfaction rating given by customers for
a particular product, you would execute the SQL query: `SELECT AVG(satisfaction_rating) FROM
feedback WHERE product_id = 'XYZ789';`

18. Get the minimum value from a column:


- Answer: In a temperature monitoring system, to determine the coldest temperature recorded in
a specific location, you would execute the SQL query: `SELECT MIN(temperature) FROM readings
WHERE location = 'City A';`

19. Retrieve the maximum value from a column:


- Answer: In an online gaming platform, to find the highest score achieved by any player in a
particular game, you would execute the SQL query: `SELECT MAX(score) FROM game_scores
WHERE game_id = '123';`

20. Retrieve rows with values within a specified range:


- Answer: As a real estate agent, to retrieve a list of properties with prices between $200,000 and
$300,000 from the database, you would execute the SQL query: `SELECT * FROM properties
WHERE price BETWEEN 200000 AND 300000;`

21. Retrieve rows with values matching a list of specified values:


- Answer: In a product inventory system, to retrieve a list of products with specific SKUs provided
by the warehouse manager, you would execute the SQL query: `SELECT * FROM products WHERE
sku IN ('SKU123', 'SKU456', 'SKU789');`

22. Search for patterns in a column using wildcard characters:


- Answer: In a customer database, to retrieve email addresses of all customers whose emails start
with "john" for a targeted email campaign, you would execute the SQL query: `SELECT email FROM
customers WHERE email LIKE 'john%';`

23. Filter data based on aggregate functions in a GROUP BY query:


- Answer: In a restaurant's reservation system, to retrieve a list of tables that have been reserved
more than 5 times in the past month, you would execute the SQL query: `SELECT table_id FROM
reservations GROUP BY table_id HAVING COUNT(*) > 5;`

24. Retrieve rows with dates within a specified range:


- Answer: In a scheduling application, to retrieve a list of appointments scheduled between
January 1st, 2023, and July 30th, 2023, you would execute the SQL query: `SELECT * FROM
appointments WHERE appointment_date BETWEEN '2023-01-01' AND '2023-07-30';`

25. Combine the result sets of two or more SELECT statements:


- Answer: In a social media platform, to merge the lists of followers and followings for a user's
profile page, you would execute the SQL query: `SELECT * FROM followers WHERE user_id = '123'
UNION SELECT * FROM followings WHERE user_id = '123';`

26. Perform conditional logic in a query:


- Answer: In an HR database, to categorize employees into different salary brackets based
Table – EmployeeDetails

EmpId FullName ManagerId DateOfJoining City

121 John Snow 321 01/31/2019 Toronto

321 Walter White 986 01/30/2020 California

421 Kuldeep Rana 876 27/11/2021 New Delhi

Table – EmployeeSalary

EmpId Project Salary Variable

121 P1 8000 500

321 P2 10000 1000

421 P1 12000 0

1. Write an SQL query to fetch the EmpId and FullName of all the employees working under the
Manager with id – ‘986’.
SELECT EmpId, FullName FROM EmployeeDetails WHERE ManagerId = 986;

2. Write an SQL query to fetch the different projects available from the EmployeeSalary table.
SELECT DISTINCT(Project) FROM EmployeeSalary;
3. Write an SQL query to fetch the count of employees working in project ‘P1’.
SELECT COUNT(*) FROM EmployeeSalary WHERE Project = 'P1';

4. Write an SQL query to find the maximum, minimum, and average salary of the employees.
SELECT Max(Salary), Min(Salary), AVG(Salary) FROM EmployeeSalary;

5. Write an SQL query to find the employee id whose salary lies in the range of 9000 and 15000.
SELECT EmpId, Salary FROM EmployeeSalary WHERE Salary BETWEEN 9000 AND 15000;

6. Write an SQL query to fetch those employees who live in Toronto and work under the manager
with ManagerId – 321.
SELECT EmpId, City, ManagerId FROM EmployeeDetails WHERE City='Toronto' AND
ManagerId='321';

7. Write an SQL query to fetch all the employees who either live in California or work under a
manager with ManagerId – 321.
SELECT EmpId, City, ManagerId FROM EmployeeDetails WHERE City='California' OR
ManagerId='321';

8. Write an SQL query to fetch all those employees who work on Projects other than P1.
SELECT EmpId FROM EmployeeSalary WHERE NOT Project='P1';
Or using the ‘not equal to’ operator-
SELECT EmpId FROM EmployeeSalary WHERE Project <> 'P1';

9. Write an SQL query to display the total salary of each employee adding the Salary with Variable
value.
SELECT EmpId, Salary+Variable as TotalSalary FROM EmployeeSalary;

10. Write an SQL query to fetch the employees whose name begins with any two characters,
followed by a text “hn” and ends with any sequence of characters.
SELECT FullName FROM EmployeeDetails WHERE FullName LIKE ‘__hn%’;
11. Write an SQL query to fetch all the EmpIds which are present in either of the tables –
‘EmployeeDetails’ and ‘EmployeeSalary’.
SELECT EmpId FROM EmployeeDetails UNION SELECT EmpId FROM EmployeeSalary;

12. Write an SQL query to fetch common records between two tables.
SELECT * FROM EmployeeSalary INTERSECT SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have INTERSECT operator so we can use the subquery-

SELECT * FROM EmployeeSalary WHERE EmpId IN (SELECT EmpId from ManagerSalary);

13. Write an SQL query to fetch records that are present in one table but not in another table.
SELECT * FROM EmployeeSalary MINUS SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have a MINUS operator so we can use LEFT join-

SELECT EmployeeSalary.*FROM EmployeeSalary LEFT JOIN ManagerSalary USING (EmpId) WHERE


ManagerSalary.EmpId IS NULL;

14. Write an SQL query to fetch the EmpIds that are present in both the tables – ‘EmployeeDetails’
and ‘EmployeeSalary.
SELECT EmpId FROM EmployeeDetails where EmpId IN (SELECT EmpId FROM EmployeeSalary);

15. Write an SQL query to fetch the EmpIds that are present in EmployeeDetails but not in
EmployeeSalary.
SELECT EmpId FROM EmployeeDetails where EmpId Not IN (SELECT EmpId FROM
EmployeeSalary);

16. Write an SQL query to fetch the employee’s full names and replace the space with ‘-’.
SELECT REPLACE(FullName, ' ', '-') FROM EmployeeDetails;
17. Write an SQL query to fetch the position of a given character(s) in a field.
SELECT INSTR(FullName, 'Snow') FROM EmployeeDetails;

18. Write an SQL query to display both the EmpId and ManagerId together.
SELECT CONCAT(EmpId, ManagerId) as NewId FROM EmployeeDetails;

19. Write a query to fetch only the first name(string before space) from the FullName column of the
EmployeeDetails table.
SELECT MID(FullName, 1, LOCATE(' ',FullName)) FROM EmployeeDetails;
SQL Server – using SUBSTRING
SELECT SUBSTRING(FullName, 1, CHARINDEX(' ',FullName)) FROM EmployeeDetails;

20. Write an SQL query to uppercase the name of the employee and lowercase the city values.
SELECT UPPER(FullName), LOWER(City) FROM EmployeeDetails;

21. Write an SQL query to find the count of the total occurrences of a particular character – ‘n’ in the
FullName field.
SELECT FullName, LENGTH(FullName) - LENGTH(REPLACE(FullName, 'n', '')) FROM
EmployeeDetails;

22. Write an SQL query to update the employee names by removing leading and trailing spaces.
UPDATE EmployeeDetails SET FullName = LTRIM(RTRIM(FullName));

23. Fetch all the employees who are not working on any project.
SELECT EmpId FROM EmployeeSalary WHERE Project IS NULL;

24. Write an SQL query to fetch employee names having a salary greater than or equal to 5000 and
less than or equal to 10000.
SELECT FullName FROM EmployeeDetails WHERE EmpId IN (SELECT EmpId FROM
EmployeeSalary WHERE Salary BETWEEN 5000 AND 10000);
25. Write an SQL query to find the current date-time.
MySQL-
SELECT NOW();

SQL Server-
SELECT getdate();

Oracle-
SELECT SYSDATE FROM DUAL;

26. Write an SQL query to fetch all the Employee details from the EmployeeDetails table who joined
in the Year 2020.
SELECT * FROM EmployeeDetails WHERE DateOfJoining BETWEEN '2020/01/01' AND
'2020/12/31';
Also, we can extract the year part from the joining date (using YEAR in MySQL)-
SELECT * FROM EmployeeDetails WHERE YEAR(DateOfJoining) = '2020';

27. Write an SQL query to fetch all employee records from the EmployeeDetails table who have a
salary record in the EmployeeSalary table.
SELECT * FROM EmployeeDetails E WHERE EXISTS (SELECT * FROM EmployeeSalary S
WHERE E.EmpId = S.EmpId);

28. Write an SQL query to fetch the project-wise count of employees sorted by project’s count in
descending order.
SELECT Project, count(EmpId) EmpProjectCount FROM EmployeeSalary GROUP BY Project
ORDER BY EmpProjectCount DESC;

29. Write a query to fetch employee names and salary records. Display the employee details even if
the salary record is not present for the employee.
SELECT E.FullName, S.Salary FROM EmployeeDetails E LEFT JOIN EmployeeSalary S ON E.EmpId =
S.EmpId;
30. Write an SQL query to join 3 tables.
SELECT column1, column2 FROM TableA JOIN TableB ON TableA.Column3 = TableB.Column3
JOIN TableC ON TableA.Column4 = TableC.Column4;

You might also like