Unit 3 Notes PDF
Unit 3 Notes PDF
-Data types are used to represent the nature of the data that can be stored in the database
table. For example, in a particular column of a table, if we want to store a string type of data
then we will have to declare a string data type of this column.
Data types mainly classified into three categories for every database.
In MySQL, string data types are used to store text and character data. Here are the common
string data types in MySQL:
CHAR
VARCHAR
Numeric data types in SQL are used to store numbers, whether they are integers, decimals, or
floating-point numbers. These data types are essential for handling mathematical operations,
storing quantities, or managing numeric data like IDs, prices, and measurements.
TIMESTAMP: Stores date and time, often with timezone information in some databases.
Q) What are the types of sql statements? Explain all types in detail?
The primary focus of DQL is to retrieve data from the database. The main statement under
DQL is the SELECT statement, which is used to query the database and extract specific data
according to the criteria provided. This data can then be displayed, analyzed, or used in other
operations. The SELECT statement is fundamental in SQL, as it allows users to retrieve
information from one or more tables, using various clauses to filter, group, and sort the data.
DDL encompasses a set of SQL statements used to define and modify the structure of the
database objects. This includes operations like creating, altering, and deleting database
schemas, tables, indexes, and other objects. The key DDL statements include:
• CREATE: This statement is used to create new database objects, such as tables,
indexes, and views. It defines the structure of the database and its components.
• ALTER: The ALTER statement modifies the structure of an existing database object,
such as adding a new column to a table or changing the data type of an existing
column.
• DROP: The DROP statement is used to delete existing database objects, like tables or
entire databases. Once dropped, the object and all its data are permanently removed.
• TRUNCATE: This statement removes all records from a table, but unlike DROP, it
retains the table structure, allowing it to be reused.
DML deals with the manipulation of data stored in the database. It includes statements that
insert, update, and delete data within the database tables. The essential DML statements are:
• INSERT: This statement adds new records to a table. It specifies the table and the
data that should be inserted.
• UPDATE: The UPDATE statement modifies existing records in a table. It allows
users to change the values of specific columns based on a set of conditions.
• DELETE: The DELETE statement removes records from a table according to the
conditions provided. Unlike TRUNCATE, which deletes all records, DELETE can
target specific rows.
DCL includes commands that control access to the data within the database. These statements
are concerned with the permissions and security aspects of the database management. The
primary DCL statements are:
• GRANT: This statement is used to provide users or roles with specific permissions,
such as the ability to select, insert, update, or delete data in a table.
• REVOKE: The REVOKE statement is used to remove previously granted
permissions, restricting users from performing certain operations.
TCL statements are used to manage transactions in a database, ensuring that a sequence of
operations is executed in a way that maintains data integrity. Transactions are a critical aspect
of database management, particularly in environments where data consistency and reliability
are crucial. The key TCL statements are:
• COMMIT: This statement saves all the changes made during the current transaction,
making them permanent.
• ROLLBACK: The ROLLBACK statement undoes all changes made during the
current transaction, reverting the database to its previous state before the transaction
began.
• SAVEPOINT: This statement sets a specific point within a transaction that you can
roll back to, allowing for partial rollbacks.
• SET TRANSACTION: The SET TRANSACTION statement configures the
properties of a transaction, such as its isolation level, which determines how the
transaction interacts with others.
Q) What are the different types of clauses in my SQL?
-In SQL, clauses are fundamental components that define the structure and behavior of SQL
statements. They help in organizing and manipulating data within a database by setting
conditions, specifying data sources, and determining the output of a query.
1. SELECT Clause
The SELECT clause is the cornerstone of SQL queries, allowing you to specify which
columns of data you wish to retrieve from the database. It defines the exact data points that
will be displayed as the result of the query. For example, if you want to view the names and
salaries of employees in a company, you would use the SELECT clause to specify these
particular columns.
2. FROM Clause
The FROM clause indicates the source of the data that the query will retrieve. Typically, it
specifies the table(s) from which the data is to be extracted. The FROM clause is crucial as it
tells the SQL engine where to look for the data mentioned in the SELECT clause. Without it,
SQL would not know where to find the information.
3. WHERE Clause
The WHERE clause is used to filter the results of a query by specifying conditions that the
data must meet. It allows you to narrow down the result set to only include records that
satisfy certain criteria. For example, if you only want to see employees with a salary greater
than a certain amount, you would use the WHERE clause to set this condition.
4. GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values in specified columns
into summary rows, like totals or averages. It is often used in conjunction with aggregate
functions such as COUNT, SUM, AVG, MAX, or MIN to perform calculations on each
group of data. This clause helps in organizing data into meaningful summaries.
5. HAVING Clause
Similar to the WHERE clause, the HAVING clause is used to filter records, but it is applied
after the data has been grouped by the GROUP BY clause. It is used to set conditions on
groups, rather than on individual rows. For example, you could use HAVING to filter groups
that have a count of records greater than a certain number.
6. ORDER BY Clause
The ORDER BY clause allows you to sort the results of a query based on one or more
columns. By default, the data is sorted in ascending order, but you can also specify
descending order. This clause is important for organizing the output of a query in a specific
sequence, making it easier to analyze or present the data.
The LIMIT clause is used to specify the maximum number of rows that should be returned by
a query. The OFFSET clause works in tandem with LIMIT to skip a specific number of rows
before beginning to return the rows. These clauses are particularly useful for paginating
results in applications, where only a subset of records is needed at a time.
8. JOIN Clause
The JOIN clause is used to combine rows from two or more tables based on a related column
between them. There are different types of joins, such as INNER JOIN, LEFT JOIN, RIGHT
JOIN, and FULL OUTER JOIN, each serving a specific purpose in how the data is combined.
Joins are essential for querying data across multiple tables in a relational database.
-In SQL, joins are fundamental operations that enable the combination of data from two or
more tables based on related columns. Understanding joins is essential for retrieving and
analyzing relational data efficiently.
1. Inner Join
• Concept: The INNER JOIN is a relational operation that merges rows from two
tables when there is a match on a specified condition. This type of join returns only
those records where there is a corresponding entry in both tables.
• Purpose: It is used to obtain data that is present in both tables, making it suitable for
queries where matching data from multiple sources is required.
• Example Scenario: Consider two tables: employees and departments. If you want to
list the employees along with their department names, but only for employees who are
assigned to a department, you would use an INNER JOIN. This ensures that only
employees who have an associated department are included in the results.
• Concept: The LEFT JOIN or LEFT OUTER JOIN combines rows from two tables,
returning all rows from the left table and the matched rows from the right table. If there is
no match in the right table, the result includes all rows from the left table with NULL
values for columns from the right table.
• Purpose: It is used when you need a complete list of records from the left table and
optionally the related data from the right table. This join helps in identifying records in
the left table that do not have corresponding entries in the right table.
• Example Scenario: To find all employees along with their department names, including
employees who may not be assigned to any department, you would use a LEFT JOIN.
This ensures that all employees are listed, with NULL values for the department
information where no match exists.
• Concept: The RIGHT JOIN or RIGHT OUTER JOIN returns all rows from the right
table and the matching rows from the left table. If there is no match in the left table,
the result includes all rows from the right table with NULL values for columns from
the left table.
• Purpose: It is used when you need a complete list of records from the right table and
optionally the related data from the left table. This join is particularly useful when the
right table contains the primary data set of interest.
• Example Scenario: If you want to list all departments and their employees, including
departments that may not have any employees, you would use a RIGHT JOIN. This
ensures that every department is included in the results, with NULL values for
employees where no matches are found.
• Concept: The FULL JOIN or FULL OUTER JOIN combines rows from both tables,
returning all rows when there is a match in either table. This join includes all rows
from both tables, with NULL values where there are no matches.
• Purpose: It is used when you need to retrieve all records from both tables, regardless
of whether there is a match. This join provides a complete view of all data across both
tables.
• Example Scenario: To get a comprehensive list of all employees and all departments,
including employees without departments and departments without employees, you
would use a FULL JOIN. This provides a complete picture of both data sets, showing
all possible combinations of rows.
- In SQL, a nested query, or subquery, is a query embedded within another query. This concept
allows for more sophisticated data retrieval and manipulation by leveraging the results of one
query to influence or determine the results of another. Understanding nested queries is crucial
for performing complex operations and handling advanced querying scenarios in relational
databases.
Types of Nested Queries
1. Single-Row Subquery:
o A single-row subquery returns a single value—a single row and a single
column. This value is then used by the outer query to filter or compare data.
o Useful for scenarios where you need to compare a single value against a set of
rows or conditions.
o Example: If you need to find all employees with a salary greater than the
average salary of a particular department, the average salary calculated by the
subquery provides a threshold for comparison in the outer query.
2. Multiple-Row Subquery:
o This type of subquery returns a set of rows. The outer query uses this set to
filter or match against its own rows.
o Ideal for scenarios where you need to filter records based on a list or range of
values returned by the subquery.
o Example: To find employees who work in departments with more than ten
employees, the outer query uses a list of department IDs obtained from the
subquery to filter employees.
3. Multiple-Column Subquery:
o Returns multiple columns and multiple rows. The result is used by the outer
query in conditions that require comparisons across multiple columns.
o Useful for scenarios where the filtering or matching involves multiple
attributes or criteria.
o Example: To find employees whose department ID and job title match those
of a specific manager, the outer query uses a set of values (department ID and
job title) obtained from the subquery for comparison.
4. Correlated Subquery:
o A correlated subquery refers to columns from the outer query. It is evaluated
once for each row processed by the outer query, making it dependent on the
outer query’s row context.
o Ideal for scenarios where the filtering or aggregation needs to be specific to
each row of the outer query.
o Example: To list employees who earn more than the average salary within
their own department, the subquery computes the average salary for the
department of each employee as it processes each row in the outer query.
-The SQL reserved words and characters are called operators, which are used with a WHERE
clause in a SQL query. In SQL, an operator can either be a unary or binary operator. The unary
operator uses only one operand for performing the unary operation, whereas the binary operator
uses two operands for performing the binary operation.
Types of Operator
The Arithmetic Operators perform the mathematical operation on the numerical data of the
SQL tables. These operators perform addition, subtraction, multiplication, and division
operations on the numerical operands.
Following are the various arithmetic operators performed on the SQL data:
The Addition Operator in SQL performs the addition on the numerical data of the database
table. In SQL, we can easily add the numerical values of two columns of the same table by
specifying both the column names as the first and second operand. We can also add the numbers
to the existing numbers of the specific column.
The Subtraction Operator in SQL performs the subtraction on the numerical data of the
database table. In SQL, we can easily subtract the numerical values of two columns of the same
table by specifying both the column names as the first and second operand. We can also subtract
the number from the existing number of the specific table column.
The Multiplication Operator in SQL performs the Multiplication on the numerical data of the
database table. In SQL, we can easily multiply the numerical values of two columns of the
same table by specifying both the column names as the first and second operand.
The Division Operator in SQL divides the operand on the left side by the operand on the right
side.
In SQL, we can also divide the numerical values of one column by another column of the same
table by specifying both column names as the first and second operand.
The Comparison Operators in SQL compare two different data of SQL table and check whether
they are the same, greater, and lesser. The SQL comparison operators are used with the
WHERE clause in the SQL queries
Following are the various comparison operators which are performed on the data stored in the
SQL database tables:
This operator is highly used in SQL queries. The Equal Operator in SQL shows only data that
matches the specified value in the query.
This operator returns TRUE records from the database table if the value of both operands
specified in the query is matched.
o EXAMPLE:- Suppose, we want to access all the records of those employees from
the Employee_details table whose salary is 30000. Then, we have to write the following
query in the SQL database:
The Equal Not Operator in SQL shows only those data that do not match the query's specified
value.
This operator returns those records or rows from the database views and tables if the value of
both operands specified in the query is not matched with each other.
o EXAMPLE:- Suppose, we want to access all the records of those employees from
the Employee_details table whose salary is not 45000. Then, we have to write the
following query in the SQL database:
The Greater Than Operator in SQL shows only those data which are greater than the value of
the right-hand operand.
o EXAMPLE:- Suppose, we want to access all the records of those employees from
the Employee_details table whose employee id is greater than 202. Then, we have to
write the following query in the SQL database:
The Greater Than Equals to Operator in SQL shows those data from the table which are greater
than and equal to the value of the right-hand operand.
o EXAMPLE:- Suppose, we want to access all the records of those employees from
the Employee_details table whose employee id is greater than and equals to 202. For
this, we have to write the following query in the SQL database:
The Logical Operators in SQL perform the Boolean operations, which give two results True
and False. These operators provide True value if both operands match the logical condition.
Following are the various logical operators which are performed on the data stored in the SQL
database tables:
The ALL operator in SQL compares the specified value to all the values of a column from the
sub-query in the SQL database.
1. SELECT,
2. HAVING, and
3. WHERE.
The AND operator in SQL would show the record from the database table if all the conditions
separated by the AND operator evaluated to True. It is also known as the conjunctive operator
and is used with the WHERE clause.
SELECT column1, ...., columnN FROM table_Name WHERE condition1 AND condi
tion2 AND condition3 AND ....... AND conditionN;
SQL OR Operator
The OR operator in SQL shows the record from the table if any of the conditions separated by
the OR operator evaluates to True. It is also known as the conjunctive operator and is used with
the WHERE clause.
Syntax of OR operator:
The BETWEEN operator in SQL shows the record within the range mentioned in the SQL
query. This operator operates on the numbers, characters, and date/time operands.
If there is no value in the given range, then this operator shows NULL value.
The Set Operators in SQL combine a similar type of data from two or more SQL database
tables. It mixes the result, which is extracted from two or more SQL queries, into a single result.
Following are the various set operators which are performed on the similar data stored in the
two SQL database tables:
The SQL Union Operator combines the result of two or more SELECT statements and provides
the single output.
The data type and the number of columns must be the same for each SELECT statement used
with the UNION operator. This operator does not show the duplicate records in the output
table.
Syntax of UNION Set operator:
Let's understand the below example which explains how to execute Union operator in
Structured Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Table: Employee_details1
o Suppose, we want to see the employee name and employee id of each employee from
both tables in a single output. For this, we have to write the following query in SQL:
The SQL Union Operator is the same as the UNION operator, but the only difference is that it
also shows the same record.
If we want to see the employee name of each employee of both tables in a single output.
For this, we have to write the following query in SQL:
The SQL Intersect Operator shows the common record from two or more SELECT statements.
The data type and the number of columns must be the same for each SELECT statement used
with the INTERSECT operator.
Suppose, we want to see a common record of the employee from both the tables in a single
output. For this, we have to write the following query in SQL:
The SQL Minus Operator combines the result of two or more SELECT statements and shows
only the results from the first data set.
Syntax of MINUS operator:
Suppose, we want to see the name of employees from the first result set after the combination
of both tables. For this, we have to write the following query in SQL:
-SQL (Structured Query Language) is equipped with a variety of functions that enable users
to perform operations on data stored within databases. These functions can be categorized
based on the type of operation they perform, making it easier to manage, analyze, and
manipulate data. Below is a theoretical overview of the different types of SQL functions:
1. Aggregate Functions
• COUNT(): Calculates the number of rows that meet a specific criterion. It is useful
for counting the number of entries in a table or a subset of a table.
• SUM(): Computes the total sum of a numeric column, aiding in the aggregation of
financial data or quantities.
• AVG(): Determines the average value of a numeric column, providing insights into
the central tendency of data.
• MIN(): Identifies the smallest value in a set of data, which can be useful for finding
the minimum price, date, or other quantities.
• MAX(): Finds the largest value in a set of data, often used to identify maximum
values like highest sales, latest dates, etc.
2. Scalar Functions
Scalar functions operate on individual values and return a single result per row. These
functions are often employed in SELECT queries to transform data or retrieve specific parts
of a value.
• String Functions:
o LOWER() and UPPER(): These functions convert text to lowercase or
uppercase, respectively, ensuring uniformity in data.
o SUBSTRING(): Extracts a portion of a string, useful for retrieving specific
parts of a text like domain names from email addresses.
o CONCAT(): Joins two or more strings into a single string, aiding in the
creation of full names or addresses.
o LENGTH(): Returns the length of a string, which can be useful for validating
input lengths.
• Numeric Functions:
o ROUND(): Rounds a numeric value to a specified number of decimal places,
often used in financial calculations.
o ABS(): Returns the absolute (non-negative) value of a number, useful in
scenarios where the sign of the number is not relevant.
o CEIL() and FLOOR(): These functions round numbers to the nearest integer,
either up (CEIL) or down (FLOOR).
• Date and Time Functions:
o NOW() and CURDATE(): Return the current date and time or the current
date, respectively, which are vital for tracking time-stamped records.
o DATEADD(): Adds a specified interval to a date, enabling the calculation of
future or past dates.
o DATEDIFF(): Calculates the difference between two dates, commonly used
for measuring durations.
o DATEPART(): Extracts a specific part (such as year, month, or day) from a
date, which is useful for grouping or filtering data by date components.
These functions allow for manipulation and extraction of information from date and time data
types. They are particularly useful in scenarios that require tracking of temporal events,
scheduling, and date comparisons.
4. Mathematical Functions
• PI(): Returns the value of π (pi), which is fundamental in trigonometric and geometric
calculations.
• EXP(): Calculates the value of e raised to the power of a given number, useful in
exponential growth models.
• LOG(): Provides the natural logarithm of a number, often used in data
transformations and statistical analyses.
• SQRT(): Returns the square root of a number, applicable in many scientific and
engineering calculations.
5. String Functions
String functions are designed to manipulate and analyze string data types. They play a crucial
role in data cleaning, formatting, and extraction of information from text.
Q) What is views in SQL? How to create, Update and Drop the view
explain with syntax.
-A view in SQL is a virtual table that is based on the result set of a SQL query. It does not
store data physically in the database; instead, it dynamically retrieves data from one or more
tables. Views are used to simplify complex queries, enhance security by restricting access to
specific data, and provide a consistent, reusable query interface for data retrieval.
Characteristics of a View:
• Virtual Table: A view is not a real table; it’s a query that is executed when the view is
accessed.
• Dynamic: The data in a view is always up-to-date as it is based on the underlying
tables.
• Simplification: Views can simplify the structure of complex queries by encapsulating
them into a single entity.
• Security: Views can be used to restrict access to specific rows or columns of a table,
providing a level of abstraction for users.
Create a View
To create a view, you use the CREATE VIEW statement followed by the view name and the
SELECT query that defines the view. The syntax is as follows:
Update a View
Updating a view in SQL is done using the CREATE OR REPLACE VIEW statement. This
allows you to modify the query that defines the view without dropping it first.
This command updates EmployeeView to include the salary column in the view.
Drop a View
If you no longer need a view, you can remove it from the database using the DROP VIEW
statement.
This command deletes the EmployeeView from the database. After the view is dropped, any
queries that reference this view will fail unless the view is recreated.
Q) What is sequences in SQL? How to create, alter and Drop the sequence
explain with syntax.
- A sequence in SQL is a database object that generates a sequence of unique numeric values.
Sequences are often used to automatically generate primary key values or other unique
identifiers in tables. They are especially useful when you need a series of incrementing
numbers without gaps, or when different sessions need to generate unique numbers
independently.
Creating a Sequence
To create a sequence, you use the CREATE SEQUENCE statement. Here’s the basic syntax:
Example:
Altering a Sequence
You can modify an existing sequence using the ALTER SEQUENCE statement. This allows
you to change properties such as the increment value, cache size, and more.
Example:
If you no longer need a sequence, you can remove it from the database using the DROP
SEQUENCE statement.
Example:
This will permanently delete the sequence and any numbers it would have generated in the
future.
Q) What is index in SQL? How to create, alter and Drop the index explain
with syntax.