0% found this document useful (0 votes)
10 views39 pages

Dbms Lab Manula-1

The document outlines practical lab exercises for database management using SQL, specifically focusing on creating, altering, and dropping tables, as well as inserting, updating, and deleting data. It discusses the advantages of SQL, features of MySQL, and the components of SQL, including DDL, DML, DCL, and TCL. Additionally, it provides detailed explanations and examples of SQL commands, emphasizing best practices for data manipulation and integrity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views39 pages

Dbms Lab Manula-1

The document outlines practical lab exercises for database management using SQL, specifically focusing on creating, altering, and dropping tables, as well as inserting, updating, and deleting data. It discusses the advantages of SQL, features of MySQL, and the components of SQL, including DDL, DML, DCL, and TCL. Additionally, it provides detailed explanations and examples of SQL commands, emphasizing best practices for data manipulation and integrity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

DPG INSTUTE OF TECHNOLOGY

AND MANAGEMENT
GURUGRAM, HARYANA

PRACTICAL LAB
FILE CODE: - BCA
205

SUBMITTED TO: - SUBMITTED BY: -


DR. NIDHI Sarveshwar Singh
(CAD DEPARTMENT) BCA – D (3rd Sem)
ROLL NO: - 23BCA244
INDEX

S.No Database Queries Date Remarks

1. Write a query to create, alter and drop the table.

2. Write a query to insert, update and delete the data.

3. Write a query to describe the structure of the table.

4. Write a query to show the data of a table with different


clauses
order by, ascending and descending order.
5. Write a query to apply different constraint like primary key
and foreign key.

6. Write a query to show the following function.

MIN
MAX
AVG
SUM

7. Write a query to use following operator.

Like operator
Not Like operator
In and Not in operator
Between operator
Structured Query Language
SQL, or Structured Query Language, is a standard programming language
specifically designed for managing and manipulating databases. It enables users
to create, retrieve, update, and delete data within a relational database. SQL is
widely used in database management systems like MySQL, Oracle, SQL Server,
and PostgreSQL.

Advantages of SQL
SQL (Structured Query Language) is a powerful and widely-used language for
managing relational databases. Here are some of its key advantages:

Ease of Use:

 Simple Syntax: SQL uses a syntax that is similar to natural


language, making it easy to learn and understand.
 Intuitive Queries: You can perform complex data manipulation
tasks with relatively simple SQL queries.

Data Integrity:

 ACID Properties: SQL databases adhere to the ACID properties


(Atomicity, Consistency, Isolation, Durability), ensuring data consistency
and reliability.
 Data Validation: You can define constraints to enforce data integrity
and prevent invalid data from being entered into the database.

Powerful Querying Capabilities:

 Complex Queries: SQL allows you to perform complex queries,


including joins, aggregations, and subqueries, to extract valuable insights
from your data.
 Flexible Data Manipulation: You can easily insert, update, and
delete data in your database using SQL commands.

High Performance:

 Optimized Query Execution: SQL databases are optimized for


efficient query execution, allowing you to retrieve and process large
amounts of data quickly.
 Indexing: You can create indexes on specific columns to further
improve query performance.

Scalability:

 Handles Large Datasets: SQL databases can handle large datasets and
complex data structures.
 Scalable Architecture: Many SQL databases support horizontal scaling,
allowing you to distribute the workload across multiple servers.

Standardization:

 Industry Standard: SQL is an industry-standard language, making


it widely supported and portable across different database systems.
 Interoperability: SQL databases can interoperate with other systems and
applications.

Security:

 Robust Security Features: SQL databases offer robust security features,


such as user authentication, access control, and encryption, to protect
your data.

Features of MYSQL
MySQL is an open-source relational database management system (RDBMS)
known for its efficiency, reliability, and ease of use. It’s widely used for web
applications, data warehousing, and enterprise-level applications. Here are some
of the main features that make MySQL a popular choice:

1. Open Source

 MySQL is open-source, meaning it's free to download, use, and modify.


This makes it an accessible choice for individual developers, startups,
and enterprises.

2. High Performance

 MySQL is designed for speed and efficiency, handling a high volume of


queries and transactions quickly, which is why it’s often chosen for
high- traffic websites and applications.
3. Platform Independence

 MySQL is compatible with multiple operating systems, including


Windows, macOS, Linux, and UNIX, making it flexible for
diverse deployment environments.

4. Scalability

 MySQL supports small, medium, and large-scale applications. It can


handle a massive volume of data and scale to manage large
databases effectively as an application grows.

5. Data Security

 With features like data encryption, user authentication, and access


control, MySQL provides robust data security, protecting data from
unauthorized access and ensuring data integrity.

6. Support for Relational Databases

 MySQL is a relational database, meaning it organizes data into tables


connected by relationships, ensuring efficient data storage and
retrieval.

7. SQL Compatibility

 MySQL fully supports the SQL language, allowing users to write


powerful and complex queries. It supports standard SQL commands like
SELECT, INSERT, UPDATE, and DELETE, making it versatile for
data manipulation.

8. Transaction Control

 MySQL supports transaction control features, including:


o Commit and Rollback: Ensure data integrity by allowing users
to save or undo changes.
o Savepoint: Allows breaking transactions into smaller parts and
rolling back to specific points within the transaction.

9. ACID Compliance

 MySQL is ACID (Atomicity, Consistency, Isolation, Durability)


compliant, ensuring reliable transaction handling, data consistency, and
error recovery, which are crucial for critical applications.
10. Replication Support

 MySQL allows for data replication across multiple servers, helping with
load balancing, redundancy, and high availability. Replication can be
configured in master-slave or master-master setups to improve
performance and provide backups.

SQL Components
SQL (Structured Query Language) has several essential components, each
serving a distinct purpose in managing and manipulating databases. Here’s a
breakdown of the primary SQL components:

1. Data Definition Language (DDL)

DDL commands define and modify the structure of database objects, such as
tables, indexes, and databases. These commands primarily focus on the schema
or structure of the database.

 CREATE: Creates new databases, tables, views, indexes, or


other database objects.
 ALTER: Modifies existing database objects (e.g., adding a column to
a table).
 DROP: Deletes databases, tables, views, or indexes.
 TRUNCATE: Removes all rows from a table but keeps the
structure intact.

2. Data Manipulation Language (DML)

DML commands are used to manage data within tables. They allow for
retrieving, inserting, updating, and deleting data from the database.

 SELECT: Retrieves data from one or more tables.


 INSERT: Adds new data/rows into a table.
 UPDATE: Modifies existing data in a table.
 DELETE: Removes data/rows from a table.

3. Data Control Language (DCL)

DCL commands control user access to database objects, ensuring security by


managing permissions.

 GRANT: Gives users specific permissions on database objects.


 REVOKE: Removes permissions granted to users.
4. Transaction Control Language (TCL)

TCL commands manage transactions within SQL, helping maintain data


integrity. They are essential in systems where multiple transactions occur
simultaneously.

 COMMIT: Saves all changes made in the transaction to the


database permanently.
 ROLLBACK: Reverts changes made during the transaction since the
last COMMIT, undoing any modifications.
 SAVEPOINT: Sets a temporary save point in a transaction to roll back
to that specific point if needed.
 SET TRANSACTION: Sets properties for a transaction, like
isolation level.
AIM: Write a query to create, alter and drop the table.
Definition
 Create Table: The CREATE TABLE statement is used to define a
new table in a database with specified columns and data types.

Code: -

Explanation

 employee_id INT PRIMARY KEY: Creates a column employee_id


as an integer type and sets it as the Primary Key, meaning it uniquely
identifies each record in the table.
 first_name VARCHAR(50) NOT NULL: Defines first_name as a
variable-length character string with a maximum length of 50, requiring
a non-null value.
 last_name VARCHAR(50) NOT NULL: Similar to first_name, but
for the last_name column.
 age INT CHECK (age >= 18): Defines an age column as an integer with
a CHECK constraint to ensure the age is at least 18.
 hire_date DATE DEFAULT CURRENT_DATE: Adds hire_date as a
date column, defaulting to the current date if no value is specified.
 department_id INT: Adds department_id as an integer, which could
later link to another table.

Output of table

After executing the CREATE TABLE command, the table structure can be
viewed using:

DESCRIBE employees;
Altering the Table

The ALTER TABLE statement allows you to modify the structure of an


existing table, such as adding a new column.

Code

Explanation

 ALTER TABLE employees: Specifies the table to alter, in this


case, employees.
 ADD COLUMN salary DECIMAL(10, 2): Adds a new column salary
with a decimal data type, allowing up to 10 digits in total, with 2 digits
after the decimal point.

Output

After executing the ALTER TABLE command, check the modified table
structure:
The salary column is now part of the employees table.

Dropping the Table

The DROP TABLE statement deletes an entire table, including all its data and
structure.

Code: -

DROP TABLE

employees; Explanation

 DROP TABLE employees: Deletes the employees table entirely,


including all data within it. This action is permanent and cannot be
undone in SQL unless a backup exists.

Output

If you try to describe or access the employees table after running DROP
TABLE, you’ll receive an error stating that the table does not exist:
Aim: - Write a Query to Insert, Update, and Delete Data in a Table.
1. Overview and Purpose of Data Manipulation Commands

 INSERT Command: Adds new records to a table.


 UPDATE Command: Modifies existing data in one or more columns
in a table.
 DELETE Command: Removes records from a table based on
specific conditions.

The INSERT, UPDATE, and DELETE commands are part of SQL's Data
Manipulation Language (DML), used to modify data within tables in a
relational database. These commands are essential for managing data over time,
allowing for flexible data operations.

These commands are collectively known as Data Manipulation


Language (DML) commands in SQL, allowing users to manage the data
within tables effectively.

2. INSERT Command

Definition:

The INSERT command adds one or more rows of data to a table. You can insert
data into all columns or specific columns.
Syntax:

There are two primary forms of the INSERT statement:

1. Inserting data into all columns:

2. Inserting data into specific columns:


Example:

Consider a table Employee with columns Employee ID, Employee Name, Age,
and Salary.

Explanation:

 In the first example, all columns are provided with values.


 In the second example, only specific columns are populated;
other columns will remain NULL or have default values.

Output:
The table Employee now has two rows:

3. UPDATE Command

Definition:

The UPDATE statement modifies existing records in a table. It can update one
or more columns based on specified conditions. The UPDATE command
modifies existing rows in a table. It allows changing values in specific columns,
and you can specify conditions to select which rows to update.

Syntax:

 WHERE clause specifies which rows to update; without it, all rows
are affected.
Example:

Explanation:

 The command updates Salary to 55000 for the employee with


Employee ID 1.

Output:

4. DELETE Command
Definition:
The DELETE statement removes records from a table. It can delete specific
records or all records if no condition is provided.
Syntax:

 WHERE clause is necessary to delete specific rows; without it, all


rows are deleted.

Example:

Explanation:

 This command deletes the record where EmployeeID is 2, removing


Jane Smith from the table.
Output:

5. Use of Transactions with DML Commands

In databases, transactions ensure that a set of DML operations completes


successfully together. If any command fails, all commands in the transaction are
rolled back.

Example:

 Explanation: If all operations succeed, COMMIT saves changes. If


an error occurs, ROLLBACK undoes the changes.

6. Practical Considerations and Best Practices

 Always use the WHERE clause in UPDATE and DELETE to


prevent accidental changes.
 Use transactions to safeguard data integrity in critical operations.
AIM: Write a Query to Describe the Structure of the Table.

1. Overview and Purpose of DESCRIBE Command

The DESCRIBE command (sometimes abbreviated as DESC) is used in SQL to


display the structure of a table, including each column's name, data type, null
ability, and any constraints (like primary keys). This command is especially
useful when you want to:

 Check the structure of a table before performing operations.


 Confirm the presence of specific columns or constraints.
 Understand the data types and constraints on each column.

3. Syntax of DESCRIBE Command

Or, in some databases, the alternative keyword SHOW COLUMNS FROM may
be used as follows:

3. Example

Let’s say we have an Employee table with the following structure:

To view the structure of the Employee table, we use:


4. Expected Output

Executing the DESCRIBE command on the Employee table will return


something like this:

 Field: Lists each column name.


 Type: Specifies the data type of each column (e.g., INT, VARCHAR(100)).
 Null: Indicates whether the column allows NULL values (YES or NO).
 Key: Shows any key constraints (PRI for primary key, UNI for unique key).
 Default: Displays default values for columns, if defined.

 Extra: Additional information, such as auto-increment behaviour.

5. Explanation of Each Column in DESCRIBE Output

1. Field:
o Lists each column name in the table. This is essential to
identify column names accurately, especially for complex
queries.
2. Type:
o Shows the data type of each column. Data types are crucial for
understanding what type of values each column can hold, e.g.,
INT for integer values, VARCHAR for variable-length strings,
and DECIMAL for decimal numbers.
3. Null:
o Indicates whether each column can store NULL values. If NO,
the column is mandatory, meaning each row must have a value in
this column.
4. Key:
o Displays any key constraints, like PRI for primary key and UNI for
unique key. Primary keys uniquely identify each row, while unique
keys prevent duplicate values in the column.
5. Default:
o Shows any default values assigned to the column. If no value
is specified during data insertion, this default value will be
used.
6. Extra:
o Displays additional properties. For example, auto_increment
indicates that the value in this column automatically increments
with each new record, useful for unique identifiers.

6. Practical Usage of DESCRIBE

 Data Validation:
o Before inserting data, use DESCRIBE to confirm the data
types and constraints.
 Schema Inspection:
o When working with a new table or unfamiliar database,
use DESCRIBE to understand the table structure.
 Debugging:
o If a query returns an error related to data types or missing
columns, DESCRIBE helps identify the exact structure.

7. Additional Notes

 Compatibility: The DESCRIBE command is supported in MySQL and


some other RDBMS systems. For databases that don’t support it
directly, alternative commands or graphical interfaces are often used to
view table structures.
 Alternative: SHOW COLUMNS FROM table_name; or querying
metadata tables (like INFORMATION_SCHEMA) are other ways
to retrieve schema details.

For example, in some databases, you can use:

This query fetches similar information by accessing the database's metadata


tables.

Example of a Full Description with Commentary

Assume we execute the command:

The output shows:


Employee ID:

 Type: INT - Stores integer values.


 Null: NO - The column cannot contain NULL values.
 Key: PRI - Defined as the primary key, uniquely identifying each record.
 Extra: auto_increment - Automatically increments with each new
row, commonly used for IDs.

 Employee Name:
o Type: VARCHAR (100) - A variable character field, allowing
up to 100 characters.
o Null: YES - Can store NULL values, allowing optional data
entry for names.

 Age:
o Type: INT - Stores integer values.
o Null: YES - Can store NULL values if the age is not provided.

 Salary:
o Type: DECIMAL (10,2) - Stores decimal numbers with up to
10 digits and 2 decimal places.
o Null: YES - Can store NULL values, making it optional.

 Department:
o Type: VARCHAR (50) - A variable character field, allowing up
to 50 characters.
o Null: YES - Can store NULL values, making it optional.
Summary:

The DESCRIBE command is a valuable tool in SQL for viewing the structure
of any table. It provides details on column names, data types, constraints, and
additional properties that define how data is stored and managed within a
table. This command helps database administrators, developers, and analysts
verify table schema before performing complex data operations, ensuring
compatibility and data integrity.
AIM: Write a query to show the data of a table with different clauses order by,
ascending and descending order.

1. Overview of the ORDER BY Clause

The ORDER BY clause is used in SQL to sort the result set of a query based on
one or more columns. By default, SQL sorts data in ascending order, but we can
also specify descending order. This clause is valuable for organizing data in a
readable format, especially when querying large datasets.

 Ascending Order (ASC): Sorts the results from smallest to largest


(e.g., A to Z, 0 to 9).
 Descending Order (DESC): Sorts the results from largest to
smallest (e.g., Z to A, 9 to 0).

1. Syntax of ORDER BY Clause

 column_name: The column(s) by which the result set will be sorted.


 ASC: Specifies ascending order (optional, as ascending is the default).
 DESC: Specifies descending order.

You can also sort by multiple columns by separating them with commas.

3. Example Table

Let’s assume we have a table named Employee with the following data:

4. Examples of Using ORDER BY Clause

1. Sorting by a Single Column in Ascending Order:


 Explanation: This query retrieves all columns from the Employee
table, sorting the rows in ascending order by Salary.

 Expected Output:

2. Sorting by a Single Column in Descending Order:

 Explanation: This query sorts the Employee table data in descending order
by the Age column.

Expected Output:

3. Sorting by Multiple Columns:


 Explanation: This query sorts the results first by Salary in descending
order. If two or more employees have the same salary, those rows are then
sorted by Age in ascending order.

Expected Output:

4. Sorting by EmployeeName in Alphabetical Order (Ascending):

 Explanation: This query sorts the Employee table in alphabetical order


by EmployeeName.

 Expected Output:

5. Explanation of Sorting Techniques

 Single Column Sorting: Useful when you only need the data ordered by
one criterion, such as sorting by Salary to identify the highest or lowest
earners.
 Multiple Column Sorting: Helpful in cases where sorting by a single
column isn’t sufficient. For example, if there are multiple employees
with the same Salary, you can then sort by Age to further organize the
data.
6. Use Cases for ORDER BY

 Organizing Reports: Present data in an ordered fashion, such as


sorting sales data by total sales amount.
 Filtering for Analysis: Quickly view top performers, lowest scores, or
rank employees based on multiple criteria.
 Enhanced Readability: Easier to read structured and sorted
data, especially in reports or dashboards.

7. Additional Notes on ORDER BY Clause

 Null Values: By default, NULL values are treated as the lowest possible
values. They will appear at the beginning in ascending order or at the
end in descending order, depending on the RDBMS.
 Index Optimization: Sorting on indexed columns can improve
query performance.
 Limit Clause: Often used with ORDER BY to limit the number of
results returned. For example:

o Explanation: This retrieves the top 5 highest-paid employees.

 Summary
 The ORDER BY clause is a versatile tool in SQL that allows you to
control the sorting of query results based on one or more columns in
ascending or descending order. This capability is crucial for organizing
and presenting data, making it a key component in SQL for reporting
and data analysis.
 This detailed guide to ORDER BY should help clarify its usage and
functionality for your practical file. Let me know if there’s anything
else you’d like to add!
AIM: Write a query to apply different constraint like primary key and foreign
key.

1. Overview and Purpose of Constraints in SQL

In SQL, constraints are rules applied to columns in a table to ensure the


accuracy, reliability, and integrity of the data. Constraints restrict the data that
can be stored in a column, preventing invalid data entries. Two key constraints
are Primary Key and Foreign Key.

 Primary Key: A unique identifier for each row in a table. It ensures that
no two rows have the same value in the specified column(s) and that
values are not NULL.
 Foreign Key: A link between two tables. It creates a relationship by
referencing a primary key in another table, enforcing referential
integrity between the tables.

2. Types of Constraints

1. Primary Key Constraint:


o Ensures that the column(s) uniquely identify each row in the table.
o Each table can have only one primary key, which may consist
of one or multiple columns (composite primary key).
2. Foreign Key Constraint:
o Establishes a relationship between two tables by linking a
column in one table to the primary key in another.
o Enforces referential integrity, ensuring that the value in the
foreign key column exists in the referenced primary key column.

3. Syntax for Primary Key and Foreign Key Constraints

1. Primary Key:
o Single Column:
Multiple Columns (Composite Primary Key):

2. Foreign Key:

Adding Foreign Key in an Existing Table:

4. Examples of Primary Key and Foreign Key Constraints

Let’s consider two tables: Department and Employee.

1. Department Table (where DepartmentID is the primary key):

2. Employee Table (where EmployeeID is the primary key and


DepartmentID is a foreign key referencing the Department
table):
Explanation of the Example:

 In the Department table:


o DepartmentID is the primary key, ensuring each department has
a unique identifier.
 In the Employee table:
o EmployeeID is the primary key, uniquely identifying
each employee.
o DepartmentID is a foreign key that links each employee to
a specific department by referencing the DepartmentID in
the Department table.
o The foreign key constraint ensures that any DepartmentID entered
in the Employee table exists in the Department table, maintaining
referential integrity.

5. Advantages and Importance of Constraints

 Data Integrity: Constraints enforce rules at the database


level, maintaining the accuracy and consistency of data.
 Relationship Management: Foreign keys help model real-world
relationships between entities, linking tables and enforcing
referential integrity.
 Data Uniqueness: Primary keys ensure each row is uniquely
identifiable, preventing duplicate records in a table.

6. Additional Examples and Use Cases

1. Composite Primary Key:


o A primary key that consists of multiple columns, commonly used
when a single column isn’t enough to uniquely identify a row.

o Example:
 Explanation: Here, EmployeeID and ProjectID together form the
primary key, meaning each employee can only be assigned to a project
once.

2. Foreign Key with ON DELETE CASCADE:

 This option automatically deletes rows in the child table (e.g.,


Employee) when the referenced row in the parent table (e.g.,
Department) is deleted.

Example:

Explanation: If a department is deleted from the Department table, all


employees associated with that department will also be removed from the
Employee table.

7. Error Prevention and Constraints

Using primary and foreign keys helps prevent common data entry errors:

 Primary Key Violation: Attempting to insert a duplicate value in


a primary key column will result in an error.
 Foreign Key Violation: Attempting to insert a value in a foreign key
column that does not exist in the referenced table will result in an
error, ensuring data consistency.
8. Summary

Constraints like Primary Key and Foreign Key are essential in SQL for
ensuring data integrity, enforcing uniqueness, and establishing relationships
between tables. By understanding and using these constraints, you can create
robust database structures that support data reliability and consistency across
various operations.

This detailed explanation covers the basics and practical applications of primary
and foreign keys to enhance your understanding and documentation in the
practical file. Let me know if you need further clarification or examples!
AIM: Write a query to show the following function. MIN MAX AVG SUM
1. Overview of Aggregate Functions in SQL

Aggregate functions in SQL perform calculations on a set of values and return a


single value. They are commonly used with the GROUP BY clause to group
data before performing calculations. Here, we’ll discuss four essential aggregate
functions:

 MIN: Finds the minimum value in a specified column.


 MAX: Finds the maximum value in a specified column.
 AVG: Calculates the average value of a numeric column.
 SUM: Calculates the total sum of values in a numeric column.

These functions are useful for analyzing and summarizing data in a database.

2. Definitions and Syntax of Each Aggregate Function

1. MIN Function:
o Definition: Returns the smallest value in a specified column.
o Syntax:

MAX Function:

 Definition: Returns the largest value in a specified column.


 Syntax:

AVG Function:

 Definition: Calculates the average (mean) of values in a


specified column.
 Syntax:
SUM Function:

 Definition: Adds up all the values in a specified numeric column.


 Syntax

3. Example Table for Demonstration

Let’s assume we have an Employee table with the following data:

4. Examples and Explanations for Each Function

1. Using the MIN Function:

 Explanation: This query finds the minimum salary among all employees.

 Expected Output:

 The MIN function scans the Salary column and returns the smallest
value, which is 48000 in this case.

2. Using the MAX Function:


 Explanation: This query finds the maximum salary in the Employee table.

 Expected Output:

 The MAX function checks the Salary column and returns the highest
value, which is 60000.

3. Using the AVG Function:

 Explanation: This query calculates the average salary of all employees.

 Expected Output:

 The AVG function computes the average by summing all the values in Salary
and dividing by the number of rows, resulting in an average of 53250.

4. Using the SUM Function:

 Explanation: This query calculates the total sum of salaries for all employees.

 Expected Output:

 The SUM function adds up all the values in the Salary column,
yielding 213000 as the total.
5. Using Aggregate Functions with the GROUP BY Clause

The GROUP BY clause groups records with similar values before applying
aggregate functions. This is helpful for calculating values based on categories.

Example with GROUP BY: Let’s modify the Employee table to include a
Department column:

Using GROUP BY to calculate the total salary by department:

 Explanation: This query groups employees by Department and calculates


the total salary for each department.

 Expected Output:

This output shows the total salary for employees in each department.

6. Practical Applications of Aggregate Functions

 MIN and MAX:


o Finding the minimum and maximum values is useful in
reporting. For example, you can use MIN to identify the lowest
price of a product or MAX to find the highest salary in a
department.
 AVG:
o The average function is commonly used for financial or
performance analysis, such as calculating the average salary,
rating, or price.
 SUM:
o The SUM function is essential for budget calculations, financial
summaries, and any scenario where a total count is needed, such as
total revenue or total quantity sold.

7. Important Considerations

 NULL Values: Aggregate functions typically ignore NULL values. For


instance, if a row in the Salary column contains NULL, it won’t affect the
result of SUM, AVG, MIN, or MAX.
 Data Types: Ensure that columns used in SUM and AVG contain numeric
data types, as these functions do not work with text or date columns.
 Performance: Using aggregate functions on large datasets may impact
performance. Indexed columns can improve the efficiency of queries
that use MIN or MAX.

Summary

The MIN, MAX, AVG, and SUM functions are essential for data analysis and
reporting in SQL. They allow you to find minimum and maximum values,
calculate averages, and add up values across rows. When combined with
GROUP BY, these functions become even more powerful, providing insights on
grouped data.

This detailed explanation should give you a solid understanding of how to use
these aggregate functions effectively. Let me know if you have questions or
need further clarification!
AIM: Write a query to use following operator. Like operator, Not Like
Operator, In and Not in operator, Between operator.

1. Overview of SQL Operators

SQL operators such as LIKE, NOT LIKE, IN, NOT IN, and BETWEEN are
used in WHERE clauses to filter data based on specific conditions. These
operators enhance the flexibility of SQL queries by allowing you to search for
patterns, match values from a list, and specify a range of values.

2. Definitions and Syntax of Each Operator

1. LIKE:
o Definition: The LIKE operator is used in SQL to search for a
specified pattern in a column. It’s commonly used with
wildcards (% and _).
 %: Represents zero, one, or multiple characters.
 _: Represents a single character.
o Syntax:

NOT LIKE:

 Definition: The NOT LIKE operator filters out rows that match
a specified pattern, effectively excluding those values.
 Syntax:

IN:

 Definition: The IN operator allows you to specify multiple values in


a WHERE clause, returning rows that match any of the listed values.
 Syntax:
NOT IN:

 Definition: The NOT IN operator filters out rows that match any value
in the specified list.
 Syntax:

BETWEEN:

 Definition: The BETWEEN operator is used to filter data within


a specified range. It includes the start and end values.
 Syntax:

3. Example Table

Let’s use the Employee table with the following data:

4. Examples and Explanations for Each Operator

1. Using the LIKE Operator:


 Explanation: This query retrieves employees whose names start with
the letter J.

 Expected Output:

 Pattern Matching:

o J%: Matches any name starting with J.


o %Doe: Matches any name ending with Doe.
o %o%: Matches any name containing the letter o.

 Using the NOT LIKE Operator:

 Explanation: This query retrieves employees whose names do not contain


the letter e.

 Expected Output:

 Pattern Exclusion:

o %e%: Excludes rows where EmployeeName contains e.

 Using the IN Operator:


 Explanation: This query retrieves employees who work in either the Sales
or Finance department.

 Expected Output:

Multiple Values:

 IN allows specifying multiple values, so rows matching any of the


values listed will be returned.

4. Using the NOT IN Operator:

 Explanation: This query retrieves employees who do not work in the HR


or Finance department.

 Expected Output:

 Exclusion of Values:

o NOT IN excludes any row with values in the specified list.

 Using the BETWEEN Operator:


 Explanation: This query retrieves employees whose ages fall between 28
and 35, inclusive of both values.

 Expected Output:

Range Filtering:

 BETWEEN is inclusive, meaning both the start and end values


are included in the result set.

5. Practical Use Cases of Each Operator

 LIKE and NOT LIKE:


o Useful for searching textual data patterns, such as finding
names starting with a particular letter, or excluding certain
character patterns.
o Example: Search for customers with email addresses ending in
a specific domain (e.g., LIKE '%@example.com').
 IN and NOT IN:
o Helpful when you need to filter rows based on a list of
specific values, especially when the values are non-sequential.
o Example: Select orders from specific regions or exclude
customers from certain states.
 BETWEEN:
o Ideal for filtering numeric or date ranges, making it a common
choice in financial reports, performance reviews, and
inventory counts.
o Example: Retrieve products within a price range or
employees within a certain age bracket.

6. Important Considerations

 Performance: LIKE searches with a leading wildcard (e.g., %pattern)


can be slower on large datasets, as they prevent the use of indexes.
 NULL Values: IN and NOT IN can yield unexpected results if
NULL values are involved. For example, NOT IN does not return
rows with NULL values unless explicitly handled.
 BETWEEN Inclusivity: Remember that BETWEEN includes both
endpoints. If exclusivity is required, use conditional operators (< and >)
instead.

Summary

Operators like LIKE, NOT LIKE, IN, NOT IN, and BETWEEN provide
powerful ways to filter data based on patterns, lists, or ranges. They enable
flexible data querying and support more nuanced data retrieval, making SQL
queries adaptable to various use cases.

This detailed guide should help you effectively understand and apply these
operators. Let me know if you have any questions!

You might also like