0% found this document useful (0 votes)
16 views22 pages

Unit 3 Notes PDF

Uploaded by

shivamkpatil2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views22 pages

Unit 3 Notes PDF

Uploaded by

shivamkpatil2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT 3

Q) Explain the data types in sql ?

-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.

o String Data types


o Numeric Data types
o Date and time Data types

String data types

In MySQL, string data types are used to store text and character data. Here are the common
string data types in MySQL:

CHAR

• Description: Fixed-length character string.


• Usage: When you know the exact length of the data. For example, storing country
codes like US, CA.
• Syntax: CHAR(n) where n specifies the length.
• Example: CHAR(10) stores a string with a fixed length of 10 characters. If a shorter
string is stored, MySQL pads it with spaces.

VARCHAR

• Description: Variable-length character string.


• Usage: When the length of the data varies. For example, storing names, emails.
• Syntax: VARCHAR(n) where n specifies the maximum length.
• Example: VARCHAR(255) can store a string up to 255 characters long.

Numeric data types

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.

Integer Data Types:

TINYINT: A very small integer.

Range: -128 to 127 (signed) or 0 to 255 (unsigned).


• SMALLINT: A small integer

Range: -32,768 to 32,767 (signed) or 0 to 65,535 (unsigned).

• MEDIUMINT: A medium-sized integer.

Range: -8,388,608 to 8,388,607 (signed) or 0 to 16,777,215 (unsigned).

Date and time datatype

DATE: Stores dates. (e.g., YYYY-MM-DD)

TIME: Stores time of day. (e.g., HH:MI:SS)

DATETIME: Stores both date and time. (e.g., YYYY-MM-DD HH:MI:SS)

TIMESTAMP: Stores date and time, often with timezone information in some databases.

YEAR: Stores year values, typically in YYYY format.

Q) What are the types of sql statements? Explain all types in detail?

-SQL (Structured Query Language) is a standardized language used to manage and


manipulate relational databases. SQL is composed of various types of statements, each
serving a specific purpose within the context of database operations. These statements can be
broadly categorized into several groups based on their functionality: Data Query Language
(DQL), Data Definition Language (DDL), Data Manipulation Language (DML), Data
Control Language (DCL), and Transaction Control Language (TCL).

1. Data Query Language (DQL):

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.

2. Data Definition Language (DDL):

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.

3. Data Manipulation Language (DML):

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.

4. Data Control Language (DCL):

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.

5. Transaction Control Language (TCL):

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.

7. LIMIT and OFFSET Clauses

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.

Q) What are the joins and types of joins in SQL?

-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.

2. Left (Outer) Join

• 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.

3. Right (Outer) Join

• 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.

4. Full (Outer) Join

• 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.

Q) Nested queries in SQL?

- 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.

Q) What are the operators and types of operators in SQL?

-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

SQL operators are categorized in the following categories:

1. SQL Arithmetic Operators


2. SQL Comparison Operators
3. SQL Logical Operators
4. SQL Set Operators
5. SQL Bit-wise Operators

SQL Arithmetic Operators

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:

1. SQL Addition Operator (+)


2. SQL Subtraction Operator (-)
3. SQL Multiplication Operator (+)
4. SQL Division Operator (-)

SQL Addition Operator (+)

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.

Syntax of SQL Addition Operator:

SELECT operand1 + operand2;


SQL Subtraction Operator (-)

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.

Syntax of SQL Subtraction Operator:

SELECT operand1 - operand2;


SQL Multiplication Operator (*)

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.

Syntax of SQL Multiplication Operator:


SELECT operand1 * operand2;
SQL Division Operator (/)

The Division Operator in SQL divides the operand on the left side by the operand on the right
side.

Syntax of SQL Division Operator:

SELECT operand1 / operand2;

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.

SQL Comparison Operators

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:

1. SQL Equal Operator (=)


2. SQL Not Equal Operator (!=)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)

SQL Equal Operator (=)

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:

SELECT * FROM Employee_details WHERE Emp_Salary = 30000;

SQL Equal Not Operator (!=)

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:

SELECT * FROM Employee_details WHERE Emp_Salary != 45000;

SQL Greater Than Operator (>)

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:

SELECT * FROM Employee_details WHERE Emp_Id > 202;

SQL Greater Than Equals to Operator (>=)

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:

SELECT * FROM Employee_details WHERE Emp_Id >= 202;

Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


SQL Logical Operators

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:

1. SQL ALL operator


2. SQL AND operator
3. SQL OR operator
4. SQL BETWEEN operator

SQL ALL Operator

The ALL operator in SQL compares the specified value to all the values of a column from the
sub-query in the SQL database.

This operator is always used with the following statement:

1. SELECT,
2. HAVING, and
3. WHERE.

Syntax of ALL operator:

SELECT column_Name1, ...., column_NameN FROM table_Name WHERE column Compar


ison_operator ALL (SELECT column FROM tablename2)

SQL AND Operator

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.

Syntax of AND operator:

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:

SELECT column1, ...., columnN FROM table_Name WHERE condition1 OR conditi


on2 OR condition3 OR ....... OR conditionN;

SQL BETWEEN 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.

Syntax of BETWEEN operator:

SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name


WHERE column_nameBETWEEN value1 and value2;

SQL Set Operators

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:

1. SQL Union Operator


2. SQL Union ALL Operator
3. SQL Intersect Operator
4. SQL Minus Operator

SQL Union Operator

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:

SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]


UNION
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];

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.

Emp Id Emp Name Emp Salary Emp C

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh

Table: Employee_details1

Emp Id Emp Name Emp Salary Emp C

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi

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:

SELECT Emp_ID, Emp_Name FROM Employee_details1


UNION
SELECT Emp_ID, Emp_Name FROM Employee_details2 ;
SQL Union ALL Operator

The SQL Union Operator is the same as the UNION operator, but the only difference is that it
also shows the same record.

Syntax of UNION ALL Set operator:

SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]


UNION ALL
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];

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:

SELECT Emp_Name FROM Employee_details1


UNION ALL
SELECT Emp_Name FROM Employee_details2 ;

SQL Intersect Operator

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.

Syntax of INTERSECT Set operator:

SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]


INTERSECT
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];

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:

SELECT Emp_Name FROM Employee_details1


INTERSECT
SELECT Emp_Name FROM Employee_details2 ;

SQL Minus Operator

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:

SELECT column1, column2 ...., columnN FROM First_tablename [WHERE conditions]


MINUS
SELECT column1, column2 ...., columnN FROM Second_tablename [WHERE conditions];

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:

SELECT Emp_Name FROM Employee_details1


MINUS
SELECT Emp_Name FROM Employee_details2 ;

Q) What are the functions in SQL? Types of functions 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

Aggregate functions perform operations on a set of values, returning a single value as a


result. These functions are essential for summarizing large datasets and are often used in
conjunction with the GROUP BY clause to aggregate data across multiple rows.

• 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.

3. Date and Time Functions

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.

• CURRENT_DATE: Returns the current date, facilitating the comparison of dates or


calculation of durations.
• CURRENT_TIME: Provides the current time, which is often used in time tracking
applications.
• DATE(): Extracts the date portion of a datetime expression, aiding in the separation
of date and time.
• TIME(): Extracts the time portion from a datetime expression, enabling the focus on
time-specific operations.
• TIMESTAMPDIFF(): Returns the difference between two timestamps, typically
used for calculating the elapsed time between events.

4. Mathematical Functions

Mathematical functions are used to perform various mathematical operations on numeric


data. These functions are essential in fields such as finance, engineering, and data analysis.

• 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.

• CHAR_LENGTH(): Returns the length of a string in characters, which can be useful


for validating input or analyzing text data.
• TRIM(): Removes leading and trailing spaces from a string, helping to clean and
normalize text data.
• REPLACE(): Replaces all occurrences of a specified substring within a string, aiding
in text transformations.
• REVERSE(): Reverses the characters in a string, which can be useful in certain
algorithms or data manipulations.

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:

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE VIEW EmployeeView AS
SELECT employee_id, first_name, last_name, department
FROM Employees
WHERE department = 'Sales';

In this example, EmployeeView is a view that retrieves the employee_id, first_name,


last_name, and department columns from the Employees table, but only for employees in the
'Sales' department.

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.

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE new_condition;
Example:
CREATE OR REPLACE VIEW EmployeeView AS
SELECT employee_id, first_name, last_name, department, salary
FROM Employees
WHERE department = 'Sales';

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.

DROP VIEW view_name;


Example:
DROP VIEW EmployeeView;

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:

CREATE SEQUENCE sequence_name

START WITH start_value


INCREMENT BY increment_value
[MINVALUE min_value]
[MAXVALUE max_value]
[CYCLE | NO CYCLE]
[CACHE cache_size | NO CACHE];

• Sequence_name: Name of the sequence.


• START WITH: The starting value of the sequence.
• INCREMENT BY: The value by which the sequence is incremented or decremented.
• MINVALUE and MAXVALUE: The minimum and maximum values the sequence
can generate.
• CYCLE: Determines if the sequence should restart when the max or min value is
reached.
• CACHE: Specifies how many sequence numbers are preallocated and stored in
memory for faster access.

Example:

CREATE SEQUENCE employee_seq


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 1000
CACHE 10
NO CYCLE;

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.

ALTER SEQUENCE sequence_name


[INCREMENT BY increment_value]
[MINVALUE min_value]
[MAXVALUE max_value]
[RESTART WITH start_value]
[CACHE cache_size | NO CACHE]
[CYCLE | NO CYCLE];

Example:

ALTER SEQUENCE employee_seq


INCREMENT BY 2
MAXVALUE 5000
CACHE 20;
Dropping a Sequence

If you no longer need a sequence, you can remove it from the database using the DROP
SEQUENCE statement.

DROP SEQUENCE sequence_name;

Example:

DROP SEQUENCE employee_seq;

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.

You might also like