Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Mysql - unit-II (DML, DCL) Unit2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 61

DDL,DML,DCL,TCL

Category Full Form Common Commands

CREATE, ALTER, DROP,


DDL Data Definition Language
TRUNCATE, RENAME

SELECT, INSERT, UPDATE,


DML Data Manipulation Language
DELETE

DCL Data Control Language GRANT, REVOKE

COMMIT, ROLLBACK,
TCL Transaction Control Language
SAVEPOINT, SET TRANSACTION
SQL, which stands for Structured Query Language, is a powerful
language used for managing and manipulating relational databases.
• What is SQL Commands?
SQL commands are the fundamental building blocks for
communicating with a database management system (DBMS). These
commands perform various database operations, such as creating
tables, inserting data, querying information, and controlling access
and security. SQL commands can be categorized into different types,
each serving a specific purpose in the database management process.
DDL:-
• DDL, which stands for Data Definition Language, is a subset of
SQL (Structured Query Language) commands used to define and
modify the database structure. These commands are used to
create, alter, and delete database objects like tables, indexes,
and schemas.
The primary DDL commands in SQL include:
• CREATE: This command is used to create a new database
object. For example, creating a new table, a view, or a
database.
– Syntax for creating a table: CREATE TABLE table_name (column1
datatype, column2 datatype, ...);

– E.g. CREATE TABLE Student(rollno int,name varchar(255),address


varchar(255),contact int);
• ALTER: This command is used to modify an existing
database object, such as adding, deleting, or modifying
columns in an existing table.
– Syntax for adding a column in a table:
ALTER TABLE table_name ADD column_name datatype;
– Syntax for modifying a column in a table:
ALTER TABLE table_name MODIFY COLUMN column_name
datatype;
• E.g. 1. ALTER TABLE Student ADD email_id varchar(255);

• E.g. 2. ALTER TABLE Student MODIFY mobile int;


• ALTER TABLE table_name RENAME COLUMN
old_column_name to new_column_name;
• ALTER TABLE CUSTOMERS RENAME COLUMN name to
full_name;
ALTER TABLE: This statement is used to add/delete/modify table
structure/column.
- Also used to add/delete/modify constraints on columns
Syntax: ALTER TABLE table_Name ADD COLUMN column_Name datatype
constraints;
OR ALTER TABLE table_Name DROP COLUMN column_Name;
OR ALTER TABLE table_Name MODIFY COLUMN column_Name datatype
constraints;
OR ALTER TABLE table_Name RENAME COLUMN column_Name to
column_Name;
DROP:
• This command is used to delete an existing database object like a table, a view,
or other objects.
• The SQL DROP TABLE statement is a Data Definition Language (DDL) command
that is used to remove a table's definition, and its data, indexes, triggers,
constraints.
• The SQL DROP DATABASE statement is used to delete an existing database
along with all the data such as tables, views, indexes, stored procedures, and
constraints.
– Syntax for dropping a table:
DROP TABLE table_name;
Syntax for dropping a Database:
DROP DATABASE DatabaseName;
• Here, the DatabaseName is the name of the database that you
want to delete. A database name is always unique within the
RDBMS.
• TRUNCATE: This command is used to delete all data from a table,
but the structure of the table remains. It’s a fast way to clear large
data from a table.
– Syntax: TRUNCATE TABLE table_name;
• RENAME: Used to rename an existing database object.
- Syntax: RENAME TABLE old_table_name TO new_table_name;

• COMMENT: Used to add comments to the data dictionary.


– Syntax: COMMENT ON TABLE table_name IS 'This is a comment.';
DML(Data Manipulation Language):
• DML Commands in SQL:-
Data Manipulation Language (DML) is a subset of SQL commands used for
adding (inserting), deleting, and modifying (updating) data in a database.
DML commands are crucial for managing the data within the tables of a
database.
• INSERT: This command is used to add new rows (records) to a
table.
– Syntax: INSERT INTO table_name (column1, column2, column3, ...) VALUES
(value1, value2, value3, ...);

• UPDATE: This command is used to modify the existing records in a


table.
– Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
– The WHERE clause specifies which records should be updated. Without it,
all records in the table will be updated.
• DELETE: This command is used to remove one or more rows from a
table.
– Syntax: DELETE FROM table_name WHERE condition;
– Like with UPDATE, the WHERE clause specifies which rows should be deleted.
Omitting the WHERE clause will result in all rows being deleted.
– The DELETE command is identical to DDL’s TRUNCATE, but there is one
significant distinction. While TRUNCATE allows us to delete all of the records in
a table, DELETE allows you to specify exactly what you want to delete.

• SELECT: Although often categorized separately, the SELECT command


is sometimes considered part of DML as it is used to retrieve data
from the database.
– Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;
– The SELECT statement is used to query and extract data from a table, which
can then be used for various purposes.
DCL commands in SQL
• Data Control Language (DCL) is a subset of SQL commands
used to control access to data in a database. DCL is crucial for
ensuring security and proper data management, especially in
multi-user database environments.
• Privilege is a permission given by DBA.
• It provides rights to executes a perticular type of SQL
statements.
• It also gives right to connect the database and create a table
in your schema.
• Privileges can be divinded two parts:
• System privileges(DDL:create,alter,rename,drop,truncate)
• Object privileges(DQL,DML:select,insert,update,delete etc)
• GRANT: This command is used to give users access privileges to the
database. These privileges can include the ability to select, insert,
update, delete, and so on, over database objects like tables and
views.
• Assigns new privileges to a user account, allowing access to specific
database objects, actions, or functions
– Syntax: GRANT privilege_name ON object_name TO user_name;
– For example, GRANT SELECT ON employees TO
user123; gives user123 the permission to read data from
the employees table.
• REVOKE: This command is used to remove previously granted
access privileges from a user.
• Removes previously granted privileges from a user account, taking
away their access to certain database objects or actions.
– Syntax: REVOKE privilege_name ON object_name FROM user_name;
– For example, REVOKE SELECT ON employees FROM user123; would
remove user123‘s permission to read data from the employees table.
TCL (Transaction Control Language)
• Transactions group a set of tasks into a single execution unit. Each
transaction begins with a specific task and ends when all the tasks in
the group are successfully completed. If any of the tasks fail, the
transaction fails.
• Therefore, a transaction has only two results: success or failure.
• BEGIN TRANSACTION (or sometimes just BEGIN): This command is
used to start a new transaction. It marks the point at which the data
referenced in a transaction is logically and physically consistent.
– Syntax: BEGIN TRANSACTION;
– Note: In many SQL databases, a transaction starts implicitly with any SQL
statement that accesses or modifies data, so explicit use of BEGIN
TRANSACTION is not always necessary.
• COMMIT: This command is used to permanently save all changes
made in the current transaction.
– Syntax: COMMIT;
– When you issue a COMMIT command, the database system will ensure that all
changes made during the current transaction are saved to the database.
• Saves all changes made during the transaction to the database.

• ROLLBACK: This command is used to undo changes that have been


made in the current transaction.
– Syntax: ROLLBACK;
– If you issue a ROLLBACK command, all changes made in the current transaction
are discarded, and the state of the data reverts to what it was at the beginning
of the transaction.
Rollback command is used to undo transactions that have not
already been saved to the database.
• SAVEPOINT: This command creates points within a transaction to
which you can later roll back. It allows for partial rollbacks and
more complex transaction control.
– Syntax: SAVEPOINT savepoint_name;
– You can roll back to a savepoint using ROLLBACK TO savepoint_name;

• SET TRANSACTION: This command is used to specify


characteristics for the transaction, such as isolation level.
– Syntax: SET TRANSACTION [characteristic];
– This is more advanced usage and may include settings like isolation level
which controls how transaction integrity is maintained and how/when
changes made by one transaction are visible to other transactions.
• Select Statement with Clauses:-
WHERE Clause:-
WHERE keyword is used for fetching filtered data in a result set. It is used to
fetch data according to particular criteria. WHERE keyword can also be used
to filter data by matching patterns.
Where Clause: Where clause is used in Select/Update/Delete statement
to filter records based on conditions specified in statement.
• Syntax:
• SELECT column1,column2 FROM table_name WHERE column_name
operator value;
. Syntax :
A. SELECT * FROM table_Name WHERE condition;
B. SELECT column1_Name,column2_Name,…. From table_Name WHERE
condition;
Operators Used in Where Clause :
Example of WHERE CLAUSE
• CREATE TABLE Emp1(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)
VALUES (1, 'Shubham', 'India','23','738479734'),
(2, 'Aman ', 'Australia','21','436789555'),
(3, 'Naveen', 'Sri lanka','24','34873847'),
(4, 'Aditya', 'Austria','21','328440934'),
(5, 'Nishant', 'Spain','22','73248679');
Select * from Emp1;
Query:
• SELECT * FROM Emp1 WHERE Age=24;
• SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;
• Where Clause with BETWEEN Operator
• It is used to fetch filtered data in a given range inclusive of two values.
• Syntax:
• SELECT column1,column2 FROM table_name
• WHERE column_name BETWEEN value1 AND value2;
• BETWEEN: operator name
• value1 AND value2: exact value from value1 to value2 to get related data
in result set.
• To fetch records of Employees where Age is between 22 and 24 (inclusive).
• SELECT * FROM Emp1 WHERE Age BETWEEN 22 AND 24;
Where Clause with LIKE Operator
• It is used to fetch filtered data by searching for a particular pattern in the where
clause.
• Syntax:
• SELECT column1,column2 FROM
• table_name WHERE column_name LIKE pattern;
• Parameters Explanation:
• LIKE: operator name
• pattern: exact value extracted from the pattern to get related data in the result
set.
• Note: The character(s) in the pattern is case-insensitive.
• To fetch records of Employees where Name starts with the letter S.
Query:
• SELECT * FROM Emp1 WHERE Name LIKE 'S%';
The ‘%'(wildcard) signifies the later characters here which can be of any length and
value.
• To fetch records of Employees where Name contains the pattern ‘M’.
• Query:
• SELECT * FROM Emp1 WHERE Name LIKE '%M%';
Output:
Where Clause with IN Operator
• It is used to fetch the filtered data same as fetched by ‘=’ operator just the
difference is that here we can specify multiple values for which we can get the
result set.
• Syntax:
• SELECT column1,column2 FROM table_name WHERE column_name IN
(value1,value2,..);
• Parameters Explanation:
• IN: operator name
• value1,value2,..: exact value matching the values given and get related data in the
result set.
• To fetch the Names of Employees where Age is 21 or 23.
• Query:
• SELECT Name FROM Emp1 WHERE Age IN (21,23);
Output:
Having clause: This is used in place of where clause if condition is having
aggregate function.
Syntax : SELECT columnName1,…. FROM table_Name GROUP BY column_Name
HAVING column_Name;
OR SELECT columnName1,…. FROM table_Name GROUP BY column_Name
HAVING column_Name;
OR SELECT columnName1,…. FROM table_Name GROUP BY column_Name
HAVING column_Name ORDER
BY column_Name;
OR SELECT columnName1,…. FROM table_Name GROUP BY column_Name
HAVING
column_Name ORDER BY column_Name LIMIT No;
• The HAVING clause was introduced in SQL to allow the
filtering of query results based on aggregate functions and
groupings, which cannot be achieved using the WHERE clause
that is used to filter individual rows.

• In simpler terms MSSQL, the HAVING clause is used to apply a


filter on the result of GROUP BY based on the specified
condition. The conditions are Boolean type i.e. use of logical
operators (AND, OR). This clause was included in SQL as
the WHERE keyword failed when we use it with aggregate
expressions. Having is a very generally used clause in SQL.
Similar to WHERE it helps to apply conditions, but HAVING
works with groups. If you wish to filter a group, the HAVING
clause comes into action.
• Some points:
• Having clause is used to filter data according to the
conditions provided.
• Having a clause is generally used in reports of large
data.
• Having clause is only used with the SELECT clause.
• The expression in the syntax can only have constants.
• In the query, ORDER BY is to be placed after the
HAVING clause, if any.
• HAVING Clause is implemented in column operation.
• Having clause is generally used after GROUP BY.
Syntax:-
SELECT col_1, function_name(col_2)
FROM tablename
WHERE condition
GROUP BY column1, column2
HAVING Condition
ORDER BY column1, column2;
• Step 1: Creating a database
• CREATE DATABASE School;
• Step 2: To use this database
• USE School;
• Step 3: Creating a table
• CREATE TABLE Student( student Varchar(20), percentage int );
• Add value to the table:
• INSERT INTO Student VALUES ('Isha Patel', 98),
• ('Harsh Das', 94), ('Rachit Sha', 93),('Sumedha', 98),('Rahat Ali', 98)
• The final table is:
• SELECT * FROM Student;
Step 4: Execute Query
SELECT student, percentage FROM Student
GROUP BY student, percentage HAVING
percentage > 95;
SQL ORDER BY clause sorts the result of the SELECT statement either in
ascending or descending order.
• In this article, we’ll explore the ORDER BY clause, exploring its syntax,
functionality, and usage with detailed examples.
• ORDER BY in SQL
• The ORDER BY statement in SQL is used to sort the fetched data in either
ascending or descending according to one or more columns. It is very useful
to present data in a structured manner.
• SQL ORDER BY default mode is sorting data into ascending order. To sort data
in descending order use the DESC keyword with ORDER BY clause.
Syntax
• The syntax to use ORDER BY clause in SQL is:
• SELECT * FROM table_name ORDER BY column_name ASC | DESC
Key Terms:
• table_name: name of the table.
• column_name: name of the column according to which the data is needed to
be arranged.
• ASC: to sort the data in ascending order.

SQL Operators:-
• Operators are used to specify a condition in a statement in MySQL.
• An operator is a symbol specifying an action that is performed on one
or more expressions.
• Operators in SQL are symbols that help us to perform specific
mathematical and logical computations on operands. An operator can
either be unary or binary.
• The unary operator operates on one operand, and the binary operator
operates on two operands.
Types of Operator:-
• SQL Arithmetic Operators
• SQL Comparison Operators
• SQL Logical Operators
• SQL Bit-wise Operators
• SQL Unary Operators
• BETWEEN
• NOT BETWEEN
• LIKE
• IN
Operator Description

The addition is used to perform an addition operation on


+ the data values.

– This operator is used for the subtraction of the data values.

This operator works with the ‘ALL’ keyword and it calculates


/ division operations.

* This operator is used for multiplying data values.

Modulus is used to get the remainder when data is divided


% by another.
Arithmatic 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 .
• Create numbers Table:
• CREATE TABLE numbers ( num1 INT, num2 INT );
INSERT INTO numbers (num1, num2)
VALUES (5, 10), (15, 20);
• 1. Addition (+)
• The addition operator (+) in MySQL is used to add numeric values together.
• SELECT num1, num2, num1 + num2 AS sum FROM numbers;
2. Subtraction (-)
• The subtraction operator (-) in MySQL is used to subtract one numeric value from
another.
• 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.
• SELECT num1, num2, num1 - num2 AS difference FROM numbers;
3. Multiplication (*)
• The multiplication operator (*) in MySQL is used to multiply numeric values
together.
• 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.
• SELECT num1, num2, num1 * num2 AS product FROM numbers;
4. Division (/)
• 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.
• We can also perform the division operation on the stored numbers in the column
of the SQL table.
• SELECT num1, num2, num1 / num2 AS quotient FROM numbers;
5. Modulus (%)
• The modulus operator (%) in MySQL returns the remainder of dividing one
numeric value by another.
• SELECT num1, num2, num1 % num2 AS remainder FROM numbers;
Comparison operator:-in SQL are used to compare one expression’s value to
other expressions. SQL supports different types of comparison

Operator Description
• = Equal to.
• > Greater than.
• < Less than.
• >= Greater than equal to.
• <= Less than equal to.
• Equal to (=):-
• SELECT * FROM MATHS WHERE MARKS=50;

• Not Equal To Operator (<> or !=)


The not equal to the operator (<> or !=) is a Comparison operator in MySQL
used to compare two values and returns true if they are not equal.
Syntax
• value1 <> value2 OR value1 != value2

Greater Than Operator (>)
• The greater than operator (>) is a Comparison operator in MySQL used to compare
two values and returns true if the value on the left side is greater than the value on
the right side.
Syntax:
• value1 > value2
• SELECT * FROM employees WHERE age > 25;
Less Than Operator (<)
• The less than operator (<) is a Comparison operator in MySQL used to compare two
values and returns true if the value on the left side is less than the value on the right
side.
• Syntax
• value1 < value2
• SELECT * FROM employees WHERE age < 30;
• SELECT * FROM orders WHERE order_date < '2022-01-01';
Greater Than or Equal To Operator (>=)
• The greater than or equal to the operator (>=)is a Comparison operator in MySQL
used to compare two values and returns true if the value on the left side is greater
than or equal to the value on the right side.
• Syntax
value1 >= value2
• SELECT * FROM employees WHERE age >= 25;
• In this example, the query will return all rows from the employees table where
the age column is greater than or equal to 25.
Less Than or Equal To Operator (<=)
• The less than or equal to the operator (<=) is a Comparison operator in MySQL
used to compare two values and returns true if the value on the left side is less
than or equal to the value on the right side.
• Syntax
value1 <= value2
• SELECT * FROM employees WHERE age <= 35;
Logical Operator:-
• The logical operators in MySQL are fundamental components of SQL
statements that allow you to filter data from a table by combining
numerous conditions in a WHERE clause. Logical operators aid in the
creation of complicated queries that retrieve data based on specified
parameters.
• MySQL has three logical operators: AND, OR, and NOT.
• The AND operator returns true if both the left and right operands are true.
Otherwise, it returns false. The OR operator returns true if either the left
or right operand is true. The NOT operator is a unary operator that returns
the opposite of the operand. If the operand is true, NOT returns false, and
if the operand is false, NOT returns true.
• AND Operator (&&)
• The AND operator (&&) is one of the logical operators in MySQL that
allows you to filter data from a table by combining two or more conditions
in a WHERE clause. However, it only returns true if all the WHERE clause
conditions are met. In other words, the AND operator returns false if any
condition is false.
Syntax
• SELECT column1, column2, ... FROM table_name WHERE condition1 AND
condition2 AND condition3 ...;
• SELECT * FROM employees WHERE department = 'Sales' AND salary > 50000;
Table:

name age department salary


A 25 IT 60000
B 29 Sales 60000
C 35 Sales 45000
D 26 IT 52000

name age department salary


B 29 Sales 60000
OR Operator (|| or OR)
• The OR operator (|| or OR) is one of the logical operators in MySQL that allows
you to filter data from a table by combining two or more conditions in a WHERE
clause. When at least one of the conditions in the WHERE clause is met, it
returns true. In other words, the OR operator returns true if any of the
conditions are met.
syntax
• SELECT column1, column2, ... FROM table_name WHERE condition1 OR
condition2 OR condition3 ...;
• The conditions that must be met for the query to respond are denoted
by condition1, condition2, and condition3.
• E.g.
• SELECT * FROM employees WHERE department = 'Sales' OR department =
'Marketing';

name age department salary


A 25 Marketing 60000
B 29 Sales 60000
NOT Operator (! or NOT)
• The NOT operator (! or NOT) is one of the logical operators in MySQL that lets you
negate a condition in the WHERE clause to filter data from a table. It will return
only those records for which the condition in the WHERE clause is false.
syntax
• SELECT column1, column2, ... FROM table_name WHERE NOT condition;
• The condition in this case is the condition that must be negated for the query to
provide a result.
• SELECT * FROM employees WHERE NOT department = 'Sales';

name age department salary


A 25 Marketing 60000
D 26 IT 52000
E.g.1:
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000 OR department =
'Marketing';

• Find out the output:


Table:

name age department salary


A 25 Marketing 60000
B 29 Sales 60000
C 35 Sales 45000
D 26 IT 52000
Output:

name age department salary


B 29 Sales 60000
A 25 Marketing 60000

The AND operator takes priority over the OR operator in this expression. As a result,
the conditions department = 'Sales' AND salary > 50000 will be considered first,
followed by the OR condition with department = 'Marketing'.

The order in which logical operators in MySQL are evaluated in a SQL query is called
logical operator precedence in MySQL. The precedence of logical operators is: NOT >
AND > OR.
E.g:2
SELECT * FROM employees WHERE department = 'Sales' OR department = 'Marketing'
AND salary > 50000;
name age department salary
A 25 Marketing 60000
B 29 Sales 60000
C 35 Sales 45000
• MySQL analyses the AND condition first in this query, followed by the OR
condition because the OR condition has lesser precedence. As a result, only
employees in the Marketing department earning more than $50,000 per year or
all employees in the Sales department will be returned.
• E.g.3:-
• SELECT * FROM employees WHERE NOT department = 'Sales' OR salary > 50000;
• The NOT operator takes precedence over the OR operator. As a result, the
condition NOT department = 'Sales' is evaluated first. This condition returns all
employees who do not work in the Sales department. The OR condition is then
reviewed, and those employees earning more than $50,000 are returned.

name age department salary


A 25 Marketing 60000
D 26 IT 52000
B 29 Sales 60000
Table:

name age department salary


A 25 Marketing 60000
B 49 Sales 60000
C 35 Sales 45000
D 26 IT 52000

Example 1:
Query:
SELECT * FROM employees WHERE (salary > 55000 OR department = 'IT') AND age < 40;

name age department salary


A 25 Marketing 60000
D 26 IT 52000

In this query, we are looking for employees who are under the age of 40 and either earn
over $55,000 per year or work in the IT department. By grouping them with parenthesis,
we ensure that the first two conditions are evaluated together before using the AND
operator for the third condition. As a result, the query is clearer and easier to interpret
with the parentheses.
Query:
• SELECT * FROM employees WHERE (department = 'IT' OR department =
'Sales' OR department = 'Marketing'

• Find out output:


Output:

name age department salary


A 25 Marketing 60000
D 26 IT 52000
B 49 Sales 60000

• The logical operators in MySQL are used to combine numerous conditions


in a WHERE clause to filter data from a table.
• MySQL's three logical operators are AND, OR, and NOT.
• When both conditions are true, the AND operator returns a record,
whereas the OR operator returns a record if at least one of the conditions
is true.
• The NOT operator is used to negate a condition.
• To build complex conditions, logical operators are typically combined with
comparison operators such as =, >, and LIKE.
• The order in which logical operators are evaluated in a SQL query is called
logical operator precedence in MySQL. The precedence is: NOT > AND >
OR.
• Bitwise operators convert two integer values to binary bits, perform the
AND , OR , or NOT operation on each bit, producing a result. Then
converts the result to an integer. For example, the integer 170 converts to
binary 1010 1010 . The integer 75 converts to binary 0100 1011 .
• Bitwise operators in SQL are used to perform bitwise operations on binary
values in SQL queries, manipulating individual bits to perform logical
operations at the bit level. Some SQL Bitwise Operators are:
Operator Description

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise XOR (exclusive OR) operator

~ Bitwise NOT (complement) operator

<< Left shift operator

>> Right shift operator


Unary Operators:-
• The SQL Unary operators are used to perform the unary operations on an operand
or a single data of the database table. The Unary Positive + operator is used to
make the numeric values of a SQL table positive. The Unary Negative - operator is
used to make the numeric values of a SQL table negative.
BETWEEN
• in SQL is a logical operator that is used to select a range of values from the
database table. The BETWEEN operator first validates whether a record lies in the
provided range. After the validation, it returns the records that lie within the given
range.
• The BETWEEN operator in MySQL, or in short "BETWEEN", is a logical operator
that is used to select a range of values from the database table. Using BETWEEN,
we can also check whether a value is in the provided range or not. Between query
in MySQL is generally used with the SELECT statements. It can also be used
with INSERT, DELETE, and UPDATE queries.
Syntax:
• expression BETWEEN first_value AND second_value;
• expression: Expression specifies a column.
• first_value, second value: These values are used to define the range for validating
the expression. The range is inclusive.
ID Name Physics Chemistry
1 Aman 86 92
2 Sushant 91 91
3 Saumya 98 98
4 Kausiki 76 76
5 Aditya 67 67

SELECT Name FROM students


WHERE Physics BETWEEN 75 AND 95;

Output:

Aman
Sushant
Kausiki

The above query is similar to saying WHERE Physics >= 75 AND Physics <= 95
Using NOT BETWEEN Operator:-
• We can reverse the working of between query in MySQL using
the NOT operator. We can combine the NOT operator with
the BETWEEN operator to exclude the records that lie in the provided range or
values. Let's use an example to understand the working of NOT BETWEEN.
Example:-
• SELECT Name FROM students WHERE Physics NOT BETWEEN 75 AND 95;

Output:-
• Saurabh
• Aditya
LIKE Operatores:-
• The SQL LIKE operator within a WHERE clause serves to search for a specific pattern
within a column.
• Two commonly utilized wildcards in association with the SQL LIKE operator are:
• The percent sign (%), which signifies zero, one, or multiple characters.
• The underscore sign (_), representing a single character.
Example:-
• SELECT *FROM studentsWHERE student_name LIKE 'A%';
• This query will return all rows from the students table where the student_name
column starts with "A", followed by zero or more characters.
Example 2:
• SELECT * FROM words WHERE word LIKE '_e_';
• This query retrieves rows from the "words" table where the "word" column
contains exactly three characters, with "e" positioned as the second character, and
any characters occupying the first and third positions.
Wildcard characters Description
The percent sign (%) in SQL serves to denote
% the presence of zero, one, or multiple
characters in a pattern.
The underscore (_) in SQL denotes the
_ existence of a single character or number
within a pattern.
Examples

Expression Description

LIKE ‘a%’ Find any values that start with "a"

LIKE ‘%a’
Find any values that contain “a" in end position

LIKE ‘%or%’
Find any values that have "def" in the between

LIKE ‘_r%’
R in the second position

LIKE ‘a_%’
Starts with ‘a’ and are at least 2 characters in length

LIKE ‘a__%’ Starts with ‘a’ and are at least 3 characters in length

LIKE ‘a%o’
Start with ‘a’ and ends with ‘o’
Like Operator in SQL with OR
• The SQL LIKE operator allows us to specify multiple string patterns for selecting rows
by utilizing the OR operators.
Syntax
• SELECT column1, column2, ... FROM table_name WHERE column1 LIKE pattern1 OR
column2 LIKE pattern2 OR ...;

ID Student_Name Marks

1 Sameer 95
2 Shyam 90
3 Pinki 88
4 Soni 80
5 Samar 67

SELECT *FROM student WHERE Student_Name LIKE 'S%r' OR name LIKE 'P%i';
ID Student_name Marks
1 Sameer 95
3 Pinki 88
5 Samar 67
• The SQL LIKE operator offers powerful capabilities for pattern matching within
column data, enabling flexible search functionalities in queries.
• With the percent sign (%) and underscore (_) as wildcards, SQL LIKE facilitates
searches for patterns with variable and fixed character positions, respectively.

SQL IN operator
• The SQL IN operator allows testing a list of values in the where clause. The values
are separated using a comma(,). It signifies multiple OR conditions in a SELECT,
INSERT, UPDATE or DELETE statement in the SQL Query.
Syntax
• SELECT column_name(s) FROM table_name WHERE column_name IN (value1,
value2, ...);
company_id company_name city state
1 Microsoft Bangalore Karnataka
2 Oracle Gurgaon Uttar Pradesh
3 Amazon Chennai Tamil Nadu
4 Adobe Pune Maharastra
5 PayPal Kolkata West Bengal
6 Codenation Patna Bihar

SELECT * FROM companies WHERE company_name IN ('Microsoft', 'Oracle',


'PayPal');

company_id company_name city state


1 Microsoft Bangalore Karnataka
3 Oracle Gurgaon Uttar Pradesh
8 PayPal Kolkata West Bengal
SELECT * FROM companies WHERE company_id IN (1, 3, 6);
The output of the following code is:

company_id company_name city state


1 Microsoft Bangalore Karnataka
3 Amazon Chennai Tamil Nadu
6 Codenation Patna Bihar

SELECT * FROM companies WHERE company_name = 1OR company_name = 3


OR company_name = 6;

You might also like