DBMS Basics: Key Concepts Explained
DBMS Basics: Key Concepts Explained
1. What is DBMS?
2. What is data?
⇒ Data is the collection of Information. Raw and isolated facts about an entity
are called data. Like text data, photos, audio, video, etc.
3. What is information?
⇒ Information is processed, meaningful usable data.
SQL 1
if the Book is data the assignments which we took from those books are called
information.
4. What is a Database?
⇒ Collection of similar or related data is called a Database. A Database is a
logical, consistent, and organized collection of data that can easily be
accessed, managed, and updated.
like: if the video is data then YouTube is the database. same if photos are data
then Google Photos is the database.
7. Data redundancy.
⇒ Redundancy in DBMS is the problem that arises when the database is not
normalized. It is the concept of storing multiple copies of the same data in
different parts of the database.
SQL 2
[Link]
Normalization: X_noem=(x-x_min)/(x_max-x_min)
8. Data Inconsistency
⇒
When the same data exists in different formats in multiple tables. This condition
is known as Data Inconsistency. It means that different files contain different
information about a particular object or person. This can cause unreliable and
meaningless information. Data Redundancy leads to Data Inconsistency.
SQL 3
[Link]
data-inconsistency/
1. DDL⇒
SQL 4
Data Definition Language (DDL) is a set of special commands that allows us to
define and modify the structure and the metadata of the database. These
commands can be used to create, modify, and delete the database structures
such as schema, tables, indexes, etc. eg:
Create, Drop, Alter, Truncate, Rename.
DCL stands for Data Control Language. It is used to retrieve stored or saved
data.
(But in the Oracle database, the execution of data control language does not have
the feature of rolling back.)
Here are some tasks that come under DCL:
4.
Rollback: It is used to restore the database to the original since the last
Commit.
SQL 5
[Link]
[Link]
2. What is an Entity?
⇒ An entity in
DBMS(Database management System) is a real-world thing or a real-world
object that is distinguishable from other objects in the real world. For example,
a car is an entity. An attribute of an entity gives us information about the
characteristic features of an entity. For example, a black car entity has an
attribute called color which has a value of black.
The entity has two types:
1. Tangible: Entities which physically present in the real world are called
Tangible entities. Eg: Pen, Car.
2. Intangible: Entities that exist logically. Eg: Bank account.
Entity Set: An entity set is a collection or set of all entities of a particular entity type
at any point in time. The type of all the entities should be the same.
SQL 6
Example :
The collection of all the students from the student table at a particular instant in
time is an example of an entity set.
The collection of all the employees from the employee table at a particular
instant in time is an example of an entity set.
Weak Entity Set: A weak entity set in DBMS is an entity set that does not have a
primary key, i.e., there exists no attribute that can uniquely represent each entity in
the entity set.
For Example, An entity set of cars having attributes such as a car's color, a car's
name is a weak entity since two cars can have the same color as well as the same
SQL 7
name. So, none of the attributes can be considered as the primary key and hence
the entity set is a weak entity set.
Strong Entity Set: Strong entity set in DBMS is the entity set in which there exists a
primary key, i.e., there exists an attribute that can uniquely represent each element
in the entity.
SQL 8
[Link]
[Link]
type/#:~:text=Tangible Entity %3A Entities that exist,Example%3A Bank
Account%2C etc.
Simple Attributes
Composite Attributes
Multi-Valued Attributes
Derived Attributes
SQL 9
Key Attributes
Stored Attributes
SQL 10
Multi-Valued Attributes: Multi-valued attributes have opposite functionality to
that of single-valued attributes and as the name suggests, multi-valued
attributes can take up and store more than one value at a time for an entity
instance from a set of possible values.
Derived Attributes: Derived attributes are those attributes whose values can be
derived from the values of other attributes. They are always dependent upon
other attributes for their value.
SQL 11
⇒ Relationship is an association between two or more entities of the same or
different entity set.
The relation is 3 types:
Many-to-Many Relationship:
Participation Constraints:
The relationship can be between two strong entities or a strong entity and a weak
entity. Depending upon the type of entity participating in the relationship, the
participation can be partial or total. There are two types of participation
constraints:
Partial Participation
SQL 12
Total Participation
Partial Participation: Partial Participation exists when all the entity of an entity
type is not associated with one or the other entity of another entity type. This is
represented by joining the relationship with the entity type with the help of one line.
Example: We have two entity types ‘Customer’ and ‘Order’. Then there can be
‘Customers’ who have not done any orders. So, here there is partial participation of
the entity in the relationship.
Total Participation: Total Participation exists when all the entity of an entity type is
associated with one or the other entity of another entity type. This is represented
by joining the relationship with the entity type with the help of a double parallel line.
Such a relationship usually exist between a strong entity and a weak entity.
Example: We have two entity type ‘Employee’ and ‘Dependant’. Then all the
‘Dependent’ entity are related to one or the other ‘Employee’ entity. This is called
total participation of the entity in the relationship. But, it may be possible that some
‘Employee’ is not related to any of the ‘Dependant’ entity. So, ‘Employee’ is
showing partial participation whereas the ‘Dependant’ is showing total participation
in the relationship.
SQL 13
Inconsistent
Not secure
Data redundancy
Data isolation
Data integrity
Atomicity problem
19.
What is data abstraction in DBMS?
⇒ Data abstraction in DBMS is a process of hiding irrelevant details from users.
Because database systems are made of complex data structures so, it makes
accessible the user interact with the database.
Physical level: It is the lowest level of abstraction. It describes how data are
stored.
Logical level: It is the next higher level of abstraction. It describes what data are
stored in the database and what the relationship among those data is.
View level: It is the highest level of data abstraction. It describes only part of the
entire database.
For example- The user interacts with the system using the GUI and fills in the
required details, but the user doesn't have any idea how the data is being used. So,
the abstraction level is entirely high in the VIEW LEVEL.
Then, the next level is for PROGRAMMERS as in this level the fields and records are
visible and the programmers have the knowledge of this layer. So, the level of
abstraction here is a little low in VIEW LEVEL.
And lastly, the physical level in which storage blocks are described.
SQL 14
20. What is Relational Algebra?
⇒
Relational Algebra is a Procedural Query Language that contains a set of
operations that take one or two relations as input and produce a new
relationship. Relational algebra is the basic set of operations for the relational
model.
select
project
set difference
union
rename, etc.
SQL 15
First Normal Form(1NF)
[Link]
1. Insertion anomalies: This occurs when we are not able to insert data into a
database because some attributes may be missing at the time of insertion.
2. Updation anomalies: This occurs when the same data items are repeated with
the same values and are not linked to each other.
3. Deletion anomalies: This occurs when deleting one part of the data deletes the
other necessary information from the database.
5. 2NF: A relation is in 2NF if it is in 1NF and all non-key attributes are fully
functional and dependent on the candidate key.
SQL 16
23. What is Denormalization?
⇒ Denormalization is the process of boosting database performance and adding
redundant data which helps to get rid of complex data. Denormalization is a part of
the database optimization technique.
SQL 17
3. RIGHT JOIN
4. FULL JOIN
[Link]
ACID properties are some basic rules, which have to be satisfied by every
transaction to preserve its integrity. These properties and rules are:
ATOMICITY: Atomicity is more generally known as the? all or nothing rule.' This
implies all are considered as one unit, and they either run to completion or are not
executed at all.
DURABILITY: This property ensures that once the transaction is committed it will
be stored in the non-volatile memory and a system crash can also not affect it
anymore.
[Link]
SQL 18
The 2-Tier architecture is the same as the basic client-server. In the two-tier
architecture, applications on the client end can directly communicate with the
database on the server side.
The 3-Tier architecture contains another layer between the client and server. The
introduction of 3-tier architecture is for the ease of the users as it provides the GUI,
which, makes the system secure and much more accessible. In this architecture,
the application on the client end interacts with an application on the server which
further communicates with the database system.
SQL 19
31. What is the difference between a shared lock and an exclusive lock?
⇒ Shared lock: A shared lock is required for reading a data item. In the shared
lock, many transactions may hold a lock on the same data item. When more than
one transaction is allowed to read the data items then that is known as the shared
lock.
Exclusive lock: When any transaction is about to perform the write operation, then
the lock on the data item is exclusive. Because, if we allow more than one
transaction then that will lead to inconsistency in the database.
SQL 20
relationships between the different tables and columns of a relational database.
Individual values in a key are called key values.
1. Primary Key
2. Candidate Key
3. Super Key
4. Foreign Key
5. Composite Key
6. Alternate Key
7. Unique Key
Primary Key: The primary key is a column of a table or a set of columns that
helps to identify every record present in that table uniquely. There can be only
one primary Key in a table. Also, the primary Key cannot have the same values
repeating for any row. Every value of the primary key must be different with no
repetitions. Among many details, a primary key is the most significant one to
understand what are keys and what is a primary key in DBMS.
The PRIMARY KEY (PK) constraint put on a column or set of columns will not
allow them to have any null values or duplicates. One table can have only one
primary key constraint. Any value in the primary key cannot be changed by any
foreign keys which refer to it.
Super Key:
Super Key is the set of all the keys that help to identify rows in a table uniquely.
This means that all those columns of a table that are capable of identifying the
other columns of that table uniquely will all be considered super keys.
Candidate Key
SQL 21
Candidate keys are those attributes that uniquely identify rows of a table. The
Primary Key of a table is selected from one of the candidate keys. So, candidate
keys have the same properties as the primary keys explained above. There can
be more than one candidate key in a table.
There can be more candidate keys than just one for any table, but they can
never be empty. Every candidate key carries unique information and value.
Besides these characteristics, a combination of attributes also works as a set of
candidate keys.
Alternate Key
As stated above, a table can have multiple choices for a primary key; however, it
can choose only one. So, all the keys that did not become the primary Key are
called alternate keys.
Foreign Key:
Foreign Key is used to establish relationships between two tables. A foreign key
will require each value in a column or set of columns to match the Primary Key
of the referential table. Foreign keys help to maintain data and referential
integrity.
Foreign keys are essential for maintaining a difference between two entities that
might be linked with the same information but do not share similar information.
In such cases, the tables are linked to maintaining a connection but do not
entirely work as a replacement for each other. For instance, any individual
working for the marketing department might have marketing department
information in its employee table, but that does not mean the table can be
similar to the department table held by the marketing department.
Composite key:
SQL 22
A composite Key is a set of two or more attributes that help identify each tuple
in a table uniquely. The attributes in the set may not be unique when considered
separately. However, when taken all together, they will ensure uniqueness. The
‘concatenated key’ is another name for a composite key.
Unique Key:
A unique Key is a column or set of columns that uniquely identify each record in
a table. All values will have to be unique in this Key. A unique Key differs from a
primary key because it can have only one null value, whereas a primary Key
cannot have any null values.
Among the seven types of keys available in the DBMS, a few other types of
keys in SQL are also accessible. The key type is called Artificial Keys. An
artificial has no relevance or meaning to the business but is often used to tackle
conflicting data management situations. For example, if there is no attribute that
comprises all required primary key properties or if the primary keys are
complex.
[Link] primary
key is used,used to identify a row.
RDBMS DBMS
SQL 23
The data stored is in table format The data stored is in the file format
Multiple data elements are accessible together Individual access to data elements
Data in the form of a table are linked together No connection between the data
It features multiple layers of security while handling There is only low security while
data handling data
34. Do we consider NULL values the same as that of Blank space or zero?
⇒ NULL value represents a value that is unavailable, unknown, or not
applicable whereas zero is a Number and blank space is a character.
A trigger is a stored
procedure that runs Stored procedures are
automatically when pieces of code written in
1. Basics
various events happen PL/SQL to do some specific
(eg: update, insert, task.
delete).
SQL 24
an action automatically. when it is invoked.
Transaction statements
All transaction statements
such as COMMIT,
Transaction such as COMMIT and
5. ROLLBACK, and
statements ROLLBACK are allowed in
SAVEPOINT are not
procedures.
allowed in triggers.
Trigger:
procedures:
SQL 25
DELIMITER //
DELIMITER ;
Trigger: [Link]
A clustered index requires less memory Non-clustered index requires more memory for
for operations. operations.
In a clustered index, the index is the In the Non-Clustered index, the index is the copy
main data. of data.
Clustered index has inherent ability of Non-clustered index does not have inherent
storing data on the disk. ability of storing data on the disk.
Clustered index store pointers to block Non-Clustered index store both value and a
not data. pointer to actual row that holds data.
In Clustered index, Clustered key In Non-Clustered index, index key defines order
defines order of data within table. of data within index.
SQL 26
smaller.
[Link]
clustered-index/
Drop command: The SQL DROP command is a DDL (Data Definition Language)
command that deletes the defined table with all its table data, associated
indexes, constraints, triggers, and permission specifications. The DROP
command drops the existing table from the database. It only requires the table
name to be dropped from the database.
Syntax: DROP TABLE table_name;
Delete commands:
The SQL DELETE command is a DML (Data Manipulation Language) command
that deletes existing records from the table in the database. It can delete one or
more rows from the table depending on the condition given with the WHERE
SQL 27
clause. Thus the deletion of data is controlled according to the user's needs
and requirements. The DELETE statement does not delete the table from the
database. It just deletes the records present inside it and maintains a
transaction log of each deleted row.
syntax: DELETE FROM table_name WHERE condition;
Difference:
The TRUNCATE
The DELETE
Command deletes all
command deletes one The DROP Command
the rows from the
Use or more existing drops the complete
existing table, leaving
records from the table table from the database.
the row with the
in the database.
column names.
SQL 28
more rows based on a table from the database table without any
specific condition. after deleting the rows. condition.
We need ALTER
permission on the
DELETE permission is schema to which the We need table ALTER
Permission required to delete the table belongs and permission to use the
rows of the table. CONTROL permission TRUNCATE command.
on the table to use the
DROP command.
DELETE FROM
DROP TABLE TRUNCATE TABLE
Syntax table_name WHERE
table_name; table_name;
condition;
[Link]
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the table. If there is any violation between
the constraint and the data action, the action is aborted.
SQL 29
PRIMARY KEY - A combination of a NOT NULL and UNIQUE . Uniquely identifies each
row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CREATE INDEX - Used to create and retrieve data from the database very quickly
89 A 230
90 B 430
91 C 324
92 D 730
BOOK_ID PRICE
B 430
D 730
SQL 30
What is the “Having Clause”?
Data from a group is fetched with the help of the “Having” clause. It tries to cater to
the conditions expected in the final result. The clause is applicable only with Select
statements. The clause is used in column functions.
89 A Hindi 22000
90 B Hindi 20000
91 C English 25000
Consider, we want the count of books with the count of language > 1. Apply the
“Having” clause to the content in the table.
FROM BOOKS
GROUP BY LANGUAGE
HAVING COUNT(LANGUAGE) > 1;
COUNT(BOOK_ID) LANGUAGE
2 Hindi
SQL 31
Applicable without GROUP BY clause Does not function without GROUP BY clause
Used with single row operations such as Applicable with multiple row functions such as
Upper, Lower and so on Sum, count and so on
Having Clause: Having Clause is basically like the aggregate function with the
GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate
functions. While the GROUP BY Clause groups rows that have the same values into
summary rows. The having clause is used with the where clause to find rows with
certain conditions. The having clause is always used after the Group By clause.
Group By Clause : The GROUP BY clause is often used with aggregate functions
(MAX, SUM, AVG) to group the results by one or more columns or In simple words
we can say that The GROUP BY clause is used in collaboration with the SELECT
statement to arrange required data into groups. The GROUP BY statement groups
rows that have the same values. This Statement is used after the where clause.
This statement is often used with some aggregate function like SUM, AVG, COUNT
atc. to group the results by one or more columns.
SQL 32
The group by clause is used to
It is used for applying some extra
1. group the data according to a
conditions to the query.
particular column or row.
43. Change the name & address of the student with ID 103 to RITA and DELHI
respectively.
⇒
UPDATE STUDENT
SET STUDENT_NAME=’RITA’; ADDRESS = ‘DELHI’
WHERE STUDENT_ID=103;
44. Print the details of the student obtaining the highest marks(if there is more than
one student getting marks then the highest will be according to the alphabetical
order of their names).
⇒
SELECT *
SQL 33
FROM STUDENT
WHERE MARKS=(SELECT MAX(MARKS) FROM STUDENT)
ORDER BY STUDENT_NAME LIMIT 1;
45. Display the name & address of the students where the name’s second
letter is ‘U’.
⇒
SELECT student_name, Address
FROM STUDENT
WHERE Student_name LIKE ‘_u%’.
46. Print the Marks and numbers of students having marks more than the
average marks of the students from NOIDA city.
⇒
SELECT Marks, COUNT (DISTINCT Student_ID)
FROM STUDENT
GROUP BY Marks
Order By :
Order By Syntax –
SQL 34
SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3....... ASC|DESC;
Group By :
Group by statement is used to group the rows that have the same value. It is
often used with aggregate functions for example:AVG(), MAX(), COUNT(),
MIN() etc. One thing to remember about the group by clause is that the tuples
are grouped based on the similarity between the attribute values of tuples.
Group By Syntax –
Difference:
SQL 35
Whereas in order by statement,
Attribute cannot be in the group by
4. attribute can be under aggregate
statement under aggregate function.
function.
For example: Center entity offers the Course entity act as a single entity in the
relationship which is in a relationship with another entity visitor. In the real world, if
a visitor visits a coaching center then he will never enquiry about the Course only
or just about the Center instead he will ask the enquiry about both.
SQL 36
or
create an SQL table from another table without copying any values from the
old table→ Create Table new_table as(select * from old_table where 1=2).
AS (SELECT *
51. SQL View with advantages. Why Company use View that much?
⇒
In SQL, a view is a virtual table based on the result set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if the
data were coming from one single table.
Syn:
FROM table_name
WHERE condition;
Advantages:
SQL 37
want the user to have access.
Query Simplification: You can write simple select statements against views,
which handle complex queries and joins.
SQL 38
for each row
set [Link] = Student.subj1 + Student.subj2 + Student.s
Stored procedures are prepared SQL code that you save so you can reuse it over
and over again. So if you have an SQL query that you write over and over again,
save it as a stored procedure and call it to run it. You can also pass parameters to
stored procedures so that the stored procedure can act on the passed parameter
values.
Stored Procedures are created to perform one or more DML operations on the
Database. It is nothing but the group of SQL statements that accepts some input in
the form of parameters performs some task and may or may not return a value.
SQL 39
BEGIN
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = @Country;
END;
1. A procedure can have both input and output parameters, but a function can
only
have input parameters.
8. A procedure can return 0 or n values (max 1024). But a function can return only
1
mandatory value.
9. A procedure can't be called from a function but we can call a function from a
procedure
SQL 40
54.
Query
𝘪𝘥 (𝘪𝘯𝘵𝘦𝘨𝘦𝘳)
𝘯𝘢𝘮𝘦 (𝘵𝘦𝘹𝘵)
𝘴𝘢𝘭𝘢𝘳𝘺 (𝘯𝘶𝘮𝘦𝘳𝘪𝘤)
𝘥𝘦𝘱𝘢𝘳𝘵𝘮𝘦𝘯𝘵 (𝘵𝘦𝘹𝘵)
2. Write an SQL query to find the name and salary of the lowest-paid employee in
each department.
⇒
select name,salary from (select e*, rank() over (partition by dept_name order by
salary) as rnk) x where [Link]<2
SQL 41
3. Write an SQL query to find the name and salary of the highest-paid employee
in each department who was hired in the last year.
⇒ select max(salary) from (select name,salary,dept, RANK() OVER(PARTITION
BY DEPT order by salary) as rnk from employees where
(select *, DATEDIFF(YEAR,HireDate, GETDATE()) as Different from Employees
where DATEDIFF(YEAR,HireDate, GETDATE()) between 0 and 1
order by HireDate ASC)
5. Write an SQL query to find the name and salary of the highest-paid employee
in each department who has been with the company for at least 5 years.
6. 5. Write an SQL query to find the names of all employees who have the same
name as another employee in the company.
7. 6. Write an SQL query to find the name and salary of the employee who has the
highest salary among all employees who were hired in the last year.
8. 7. Write an SQL query to find the name and salary of the employee who has the
highest salary among all employees who have been with the company for at
least 10 years.
SQL 42
9. 8. Write an SQL query to find the name and department of all employees who
have been with the company for more than 10 years and have a salary greater
than $100,000.
10. 9. Write an SQL query to find the name and salary of the employee who has the
second-highest salary in the company.
11. 10. Write an SQL query to find the name and department of all employees who
have the same manager as another employee in the company.
12. Write an SQL query to report all the duplicate emails. You can return the result
table in any order.
⇒
select email
from Person
group by email
having count(email) > 1;
13. Construct a SQL query to provide each player's first login date. You can return
the result table in any order.
⇒
SQL 43
14. Write an SQL query to report all customers who never order anything. You can
return the result table in any order.
⇒
15. 1. Write an SQL query to report the movies with an odd-numbered ID and a
description that is not "boring". Return the result table ordered by rating in
descending order.
⇒
SELECT *
FROM Cinema
WHERE id % 2 = 1 AND description NOT LIKE '%boring%'
ORDER BY rating DESC;
16. 1. Construct a SQL query to display the names and balances of people who
have a balance greater than $10,000. The balance of an account is equal to the
sum of the amounts of all transactions involving that account. You can return
the result table in any order.
⇒
17. 1. Write a SQL query that detects managers with at least 5 direct reports from
the Employee table.
⇒
SQL 44
SELECT Name
FROM Employee
WHERE id IN
(SELECT ManagerId
FROM Employee
GROUP BY ManagerId
HAVING COUNT(DISTINCT Id) >= 5);
18. Construct an SQL query that retrieves the fname in upper case from the
Employee table and uses the ALIAS name as the EmployeeName in the result.
⇒
19. Construct an SQL query to find out how many people work in the "HR"
department
⇒
20. Construct an SQL query to retrieve the first four characters of the ‘lname’
column from the Employee table.
⇒
21. Construct a new table with data and structure that are copied from the
existing table ‘Employee’ by writing a query. The name of the new table
should be ‘SampleTable’.
⇒
22. Construct an SQL query to find the names of employees whose first names
start with "S".
⇒
SQL 45
Select * from employee where fname like's%'
24. Construct an SQL query to retrieve all employees who are also managers.
⇒
25. Construct an SQL query to retrieve the employee count broken down by
department and ordered by department count in an ascending manner.
⇒
26. Construct an SQL query to retrieve duplicate records from the Employee
table.
⇒
27. 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 Emp_details
SQL 46
where Manager_id=986;
28. Write an SQL query to fetch the different projects available from the
EmployeeSalary table.
⇒
select distinct(project)
from EmployeeSalary
29. Write an SQL query to fetch the count of employees working in project ‘P1’.
⇒
select count(*)
from empsalary
where project = 'p1'
30. Write an SQL query to find the maximum, minimum, and average salary of
the employees.
⇒
select Max(salary)
min(salary)
avg(salary)
from Emp_sal
31. Write an SQL query to find the employee id whose salary lies in the range of
9000 and 15000.
⇒
select emp_id
from sal_details
where salary between 9000 and 15000;
32. Write an SQL query to fetch those employees who live in Toronto and work
under the manager with ManagerId – 321.
⇒
SQL 47
select emp_id, city, ManagerId
from emp_details
where ManagerId=321 and city='Toronto'
33. Write an SQL query to fetch all the employees who either live in California or
work under a manager with ManagerId – 321.
⇒
34. Write an SQL query to fetch all those employees who work on Projects other
than P1.
⇒
select empid
from employee salary
where not Project='P1';
-------------------------------------
SELECT EmpId
FROM EmployeeSalary
WHERE Project <> 'P1';
35. Write an SQL query to display the total salary of each employee adding the
Salary with Variable value.
⇒
36. 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.
⇒
SQL 48
select FullName
from EmployeeDetails
where Fullname like '__hn%';
37. Write an SQL query to fetch all the EmpIds which are present in either of the
tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
⇒
38. Write an SQL query to fetch common records between two tables.
⇒
39. Write an SQL query to fetch records that are present in one table but not in
another table.
⇒
SQL 49
select emp_sal.*
from emp_sal
Left Join
Man_sal using(emp_id)
where man_sal.emp_id Is Null;
40. 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);
41. Write an SQL query to fetch the EmpIds that are present in
EmployeeDetails but not in EmployeeSalary.
⇒
42. Write an SQL query to fetch the employees’ full names and replace the
space with ‘-’.
⇒
select replace(FullName,'','-')
from EmployeeDetails;
43. Write an SQL query to fetch the position of a given character(s) in a field.
⇒
SQL 50
44. Write an SQL query to display both the EmpId and ManagerId together.
⇒
45. Write a query to fetch only the first name(string before space) from the
FullName column of the EmployeeDetails table.
⇒
MySql-
select mid(FullName,1,LOCATE('',FullName))
from EmployeeDetails;
SQL Server-
select substring(FullName,1,CharIndex('',FullName))
from EmployeeDetails;
46. Write an SQL query to uppercase the name of the employee and
lowercase the city values.
⇒
select upper(Name),lower(city)
from EmployeeDetails;
47. 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;
48. Write an SQL query to update the employee names by removing leading
and trailing spaces.
SQL 51
⇒
Update Emp_details
set FullName=LTRIM(RTRIM(FullName));
);
END
SQL 52
where [Link]=[Link]-1 and [Link]=[Link]-1
and [Link]=[Link] and [Link]=[Link];
select enail
from customer
group by email
having count(*)>1;
select [Link],[Link],[Link]
from Employee e
join Department d
on [Link]=[Link]
where (DepartmentId,salary) in
(select DepartmentId,max(salary)
from employee
group by DepartmentId)
56. You have been given a database schema consisting of two tables orders
and order items. Write a SQL query that calculates the total revenue
generated from each order. The total revenue should be calculated b
multiplying the price item by the quantity and summing up the results for
each order. The results should be sorted by order_id in ascending order.
SQL 53
Orders(order_id, customer_I'd, order_date). Order_items( order_item_I'd,
order_id, product_name, price, quantity)
⇒
SELECT
o.order_id,
SUM([Link] * [Link]) AS total_revenue
FROM
orders o
JOIN
order_items oi ON o.order_id = oi.order_id
GROUP BY
o.order_id
ORDER BY
o.order_id ASC;
57.
Write a SQL query that retrieves the employee information along with an
additional column names bonus, based on the following conditions:
SELECT
Id,
name,
salary,
department,
SQL 54
CASE
WHEN salary > 5000 THEN salary * 0.10
WHEN salary BETWEEN 3000 AND 5000 THEN salary * 0.
ELSE salary * 0.02
END AS bonus
FROM
employees;
58.
Employee table contains I'd first_name last_name salary. Write a query that
satisfy the conditions
2. Retrve the data from the 5th row up to the 10th row (both inclusive)
⇒
SELECT
Id,
first_name,
last_name,
salary
FROM
Employee
ORDER BY
salary DESC
LIMIT 6 OFFSET 4;
59.
Leetcode → [Link]
problem-solving#175-combine-two-tables--easy--leetcode
[Link]
questions-easy/
SQL 55
char_length → Length of the characters.
New
1. Write an SQL query to render a column. Why do we use OFFSET command?
⇒
To render a column in SQL, you can use the SELECT statement to specify the
column you want to retrieve from a table. Here's an example of an SQL query
that selects a column named column_name from a table named table_name :
SELECT column_name
FROM table_name;
For example, if you want to skip the first 10 rows and then return the next set of
rows, you can use:
SELECT column_name
FROM table_name
ORDER BY some_column
OFFSET 10;
----------------------------------------------
Offset for a Range -
SELECT column_name
FROM table_name
ORDER BY some_column
OFFSET 10
LIMIT 5;
SQL 56
This would skip the first 10 rows and return all rows after that.
3. Write a SQL query to get second highest query using sub query.
⇒
4. Write a SQL query to find all the student names Nitin in a table
⇒
SELECT *
FROM students
WHERE name = 'Nitin';
5. Write a query to get all the students with name length 10, starting with K and
ending with z.
⇒
SELECT *
FROM students
WHERE LENGTH(name) = 10 AND name LIKE 'K%z';
to assign a rank to each row within a partition of a result set. Here's an example
using the RANK() function to find the second highest salary from a table named
employees .
SELECT salary
FROM (
SQL 57
SELECT salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) ranked_salaries
WHERE rank = 2;
-------------------------------------------------------------
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) A
FROM employees
) ranked_salaries
WHERE rank = 2;
often redundant because the HAVING clause is typically used to filter groups of
rows created by GROUP BY . When used without GROUP BY , HAVING acts similarly to
a WHERE clause, but it's evaluated after the SELECT statement.
SELECT name
FROM students
HAVING name LIKE 'A%';
9. What would be the result of row number, rank, and dense rank ?
⇒
The ROW_NUMBER() , RANK() , and DENSE_RANK() window functions in SQL are used to
assign a unique rank or number to rows within a result set, usually based on
SQL 58
some ordering. The way each function handles ties (rows with the same value)
differs, and this affects the output rankings.
Example Table
Suppose we have a table students with columns name and score :
name score
Alice 90
Bob 95
Carol 90
Dave 95
Eve 85
1. ROW_NUMBER() :
2. RANK() :
3. DENSE_RANK() :
SQL 59
rank
FROM students;
Result Explanation
Assuming we run these queries on the example table above, here are the
results and the differences:
Bob 95 1 1 1
Dave 95 2 1 1
Alice 90 3 3 2
Carol 90 4 3 2
Eve 85 5 5 3
Differences Explained:
1. ROW_NUMBER() :
No Ties Handling: It does not consider ties, so each row gets a distinct
number in sequence (1, 2, 3, ...).
2. RANK() :
Handles Ties: Assigns the same rank to rows with identical values in
the ORDER BY column.
Gaps in Ranks: If there are ties, the next rank skips numbers
accordingly. For example, if two rows tie at rank 1, the next rank is 3
(not 2).
3. DENSE_RANK() :
Handles Ties: Also assigns the same rank to rows with identical values
in the ORDER BY column.
No Gaps in Ranks: Unlike RANK() , DENSE_RANK() does not skip any rank
numbers after ties. If two rows tie at rank 1, the next rank is 2.
SQL 60
Conclusion
Use ROW_NUMBER() when you need a unique number for each row.
Use RANK() when you want to assign the same rank to tied rows but have
gaps in subsequent rankings.
Use DENSE_RANK() when you want to assign the same rank to tied rows
without any gaps in the ranking sequence.
10. Find all the students who either are male or live in Mumbai.
⇒
SELECT *
FROM students
WHERE gender = 'Male' OR city = 'Mumbai';
11. Extract all the distinct email ID domains from all the employee.
⇒
12. Can you join two tables without any common column?
⇒
Yes, you can join two tables without any common column, but this type of join
is less common and has specific use cases. When you join two tables without a
common column, the result is typically a Cartesian product (or cross join) of the
two tables. This means every row from the first table is combined with every
row from the second table.
Example Tables
Assume you have two tables:
table1 :
SQL 61
id name
1 Alice
2 Bob
table2 :
code city
A Paris
B Tokyo
SELECT *
FROM table1
CROSS JOIN table2;
Explanation:
: Produces a Cartesian product of table1 and table2 . Every
CROSS JOIN
combination of rows from the two tables is included in the result set.
Result Set
The result will be:
1 Alice A Paris
1 Alice B Tokyo
2 Bob A Paris
2 Bob B Tokyo
When to Use
Generating Combinations: When you need to create all possible
combinations of rows from the two tables.
Caution
SQL 62
Large Datasets: Be cautious when using CROSS JOIN with large tables, as it
can produce a large number of rows and may impact performance.
Unexpected Results: Ensure that the Cartesian product is what you intend,
as it can sometimes produce unexpected or unwanted results if not
carefully planned.
In summary, while you can join tables without a common column using a
Cartesian product, it's essential to use this approach thoughtfully based on
your specific needs.
In SQL, when dealing with NULL values, any comparison involving NULL always
results in NULL because NULL represents an unknown or missing value. This
includes comparisons like NULL = NULL .
SELECT CASE
WHEN NULL = NULL THEN 'Amit'
ELSE 'Rahul'
END
FROM dual;
Explanation:
: This comparison evaluates to NULL because NULL represents an
NULL = NULL
unknown value, and the result of comparing two unknown values is also
unknown.
CASE WHEN NULL = NULL THEN 'Amit' ELSE 'Rahul' END : Since the condition NULL =
NULLevaluates to NULL (not true), the CASE statement defaults to the ELSE
clause.
ELSE 'Rahul' : Given that the condition is not true (i.e., it evaluates to NULL ),
the ELSE part of the CASE statement is executed.
Output:
The result of the query will be:
SQL 63
RAHUL
This is because the condition in the CASE statement is NULL , and thus the ELSE
COUNT(*)
Counts Rows: COUNT(*) counts the total number of rows in a table or a result
set, regardless of whether any columns contain NULL values.
Includes All Rows: It includes all rows in the count, even if some columns
contain NULL values or if there are no values in specific columns.
Example:
COUNT(ColName)
Excludes NULLs: It excludes rows where the specified column has a NULL
Column Specific: The count is specific to the column you provide and does
not count rows where the column value is NULL .
Example:
SQL 64
SELECT COUNT(email) AS email_count
FROM employees;
This query counts the number of non- NULL email addresses in the employees
table.
Key Differences:
Scope of Counting:
Null Handling:
Use Case:
Use COUNT(*) when you need the total number of rows in a table or
result set.
Use COUNT(ColName) when you need to count only the rows where a
specific column has non- NULL values.
id name email
1 Alice alice@[Link]
2 Bob NULL
3 Carol carol@[Link]
4 Dave NULL
COUNT(email) would return 2 (only the rows where email is not NULL ).
SQL 65
15. How do we create a table with all the employee Names and Manager Names?
⇒
To create a table that includes both employee names and their manager names,
you'll need to join the employees table with itself. This is commonly done using a
self-join, where the table is joined with itself based on a relationship between
employees and their managers.
Assumptions
employees Table: Contains columns like employee_id , employee_name , and
manager_id .
Steps
1. Create the Table: First, ensure you have the employees table created with
the necessary columns.
2. Join the Table: Use a self-join to match employees with their managers.
SQL Example
Here is an example SQL query that creates a new table to store the employee
names and their manager names:
SQL 66
(2, 'Bob', 1), -- Bob is managed by Alice
(3, 'Carol', 1), -- Carol is managed by Alice
(4, 'Dave', 2); -- Dave is managed by Bob
Explanation:
employees e1 : Alias for the employee records in the first instance of the
employees table.
employees e2 : Alias for the manager records in the second instance of the
employees table.
: Ensures that all employees are included in the result, even if they
LEFT JOIN
Result:
Given the sample data, the result might look like:
employee_name manager_name
SQL 67
Alice NULL
Bob Alice
Carol Alice
Dave Bob
This table shows each employee along with the name of their manager. If an
employee does not have a manager, the manager_name will be NULL .
16. Write a query for collecting the names of children who pursuing their
graduation in their residential city.
⇒
SELECT [Link]
FROM children c
JOIN education e ON [Link] = e.child_id
WHERE c.residential_city = e.institution_city;
Key Points:
Purpose: To speed up the retrieval of data by reducing the amount of data
the database engine needs to scan.
Use Case: Often used on columns frequently queried with WHERE clauses,
join operations, or used in sorting ( ORDER BY ).
Trade-Offs: While indexes speed up read operations, they can slow down
write operations (like INSERT , UPDATE , DELETE ) because the index must also
be updated.
SQL 68
18. Show how to write a query to show details of an HR whose name starts with M.
=
SQL 69
How to get the cumulative sum in a table?
Find the Nth largest salary from employee table.
Write valid query.
Write a SQL query to find the common records between two tables.
Write a query to get all the employee detail from EmployeeDetail table.
How to calculate the output of the functions?
How to do database integrity?
Use regular expression to find the number of people who are from Delhi and
have arrived in Patna in the last 7 days, as specified.
Create a ranking row without using Rank function in SQL.
Does the data stored in the stored procedure increase access time or execution
time? Explain.
What is the function of COALESCE()?
Write a valid query for the given problem.
What is a RANK() function?
How to fetch only even rows from a table?
What do you understand by Fuzzy merging?
Which language will you use to handle it?
Get the Emp_id for employees whose Dept_id is either invalid or not present in
the database.
If we drop a table, does it also drop related objects like constraints, indexes,
columns,
Define DDL, DML and DCL.
What is the use of NVL function in Oracle?
How to generate row number in a table without using ROWNUM() ?
How would you select the top 100 customers with the highest spend over a
year-long period?
What are the differences among ROWNUM, RANK and DENSE_RANK?
All you have to do is to go through the code and comment the question for
which the following is an answer of the given.
What are the steps you will take to improve the performance of a poor
performing query?
What is parser?
How many rows will be populated ?
How would you group the users together in meaningful segments?
Get all employee detail from EmployeeDetail table whose “FirstName” not start
with any single character between ‘a-p’
SQL 70
Write a SQL query to find the date along with the IDs whose temperature is
lower from the next day.
How can you create an empty table from an existing table?
What is the difference between DELETE and TRUNCATE commands?
Given two tables, one of customers and another of car accidents, write a SQL
query to get the top car accidents by day.
Write a query to find employees who have completed more than 2 years in the
company.
Find the hours for which the product ‘A’ was out of stock, assuming this is all
the data for one day only
Give some problems or scenarios where map-reduce concept works well and
where it doesn’t work.
Guess the question.
What is the correct order of writing SQL query from given tags?
Print the message ‘NUMBER’ if valid, ‘NOT NUM’ if not.
Query the list of CITY names from STATION that does not start with vowels and
do not end with vowels.
calculate the count distinct ids which are there present for last 7 days with
respect to given date.
Arrange the Emp_name in alphabetical order in the new table that only has the
salary and Emp_name column in it.
State some biases that you are likely to encounter when cleaning a database.
Write a query to replace “not provided” where there is null in the below table
and then show the department manager column.
What will be the output of Following SQL Query.
To create a sql script so that it keeps information of all the user’s badge swipe
in the last 30 days only and truncates the rest of the dataList the total number
of products of each brand.
List the total numbers of products of each [Link] the appropriate result.
Write a query using above tables to display the Emp_no, name and Experience
( in year and month)from joining date to current date. Question
Refer to the following table and answer the questions related to it.
For what purpose we are using view?
Guess the question.
How can you create an empty table from an existing table?
UNANSWERED
Can we have another column in a table other than a primary key column which
SQL 71
will act as a primary key?
You are provided with a poor performing query, suggest some methods to
improve it and satisfy the required conditions.
Suggest some ways to handle Duplicate Records.
After entering the data from the front-end application interface, how do you test
whether a database is updated or not?
Find the 4th highest employee salary from the table
What are different types of UDF in SQL?
What changes can you recommend to reduce the use of triggers?
If a table contains duplicate rows, does a query result display the duplicate values
by default?
How can you use a CTE to return the fifth highest salary from a table?
What is Hash Join?
List the id , marks of all students whose marks don’t fall under any grade.
How will you update a table without using Update statement?
Can you modify the rows in a table based on values from another table? Explain.
Find no. of subscribers each month or MoM.
What do you understand by Fuzzy merging?
What is the purpose of the group functions in SQL?
Write a SQL query to find total number of employees who are inside the office at
4PM . Consider all possible cases .
What is the role of “Database Testing” in SQL?
What’s the actual practical use of OFFSET? SQL
Find the output.
The wildcard in a WHERE clause is useful when?
How do you go about investigating the slowness and helping them to improve
queries?
Which expressions or functions allow you to implement conditional processing in a
SQL statement?
Explain the difference between “long” and “wide” format data.
Explain PARTITION key.
How can you use a CTE to return the fifth highest (or Nth highest) salary from a
table?
What is the difference between Case and Searched Case statements in SQL? How
do data management procedures like missing data handling make selection bias
worse?
SQL 72
🧿 SQL
SQL 73