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

What is SQL

SQL (Structured Query Language) is a programming language used for managing and interacting with relational databases, allowing efficient data querying, updating, and management. It consists of various components such as databases, tables, and queries, and includes commands categorized into DDL, DML, DQL, DCL, and TCL for different functionalities. SQL also has characteristics like user-friendliness and standardization, but faces limitations in handling advanced operations and unstructured data.

Uploaded by

Vaishnavi Dubey
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)
2 views22 pages

What is SQL

SQL (Structured Query Language) is a programming language used for managing and interacting with relational databases, allowing efficient data querying, updating, and management. It consists of various components such as databases, tables, and queries, and includes commands categorized into DDL, DML, DQL, DCL, and TCL for different functionalities. SQL also has characteristics like user-friendliness and standardization, but faces limitations in handling advanced operations and unstructured data.

Uploaded by

Vaishnavi Dubey
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/ 22

UNIT 2 SQL

What is SQL?
Data is at the core of every application, and SQL (Structured Query Language) manages and
interacts with this data. Whether we’re handling a small user database or
analyzing terabytes of sales records, SQL allows efficient querying, updating,
and management of relational databases.
When data needs to be retrieved from a database, SQL is used to construct and send the
request. The Database Management System (DBMS) processes the SQL query, retrieves the
requested data, and returns it to the user or application. Instead of specifying step-by-step
procedures, SQL statements describe what data should be retrieved, organized, or modified,
allowing the DBMS to handle how the operations are executed efficiently.
In common usage, SQL encompasses DDL and DML commands
for CREATE, UPDATE, MODIFY, or other operations on database structure.
SQL History
 SQL was invented in 1970s and was first commercially distributed by Oracle.
 The original name was given by IBM as Structured English Query Language, abbreviated
by the acronym SEQUEL.
Components of a SQL System
A SQL system consists of several key components that work together to enable efficient data
storage, retrieval, and manipulation. Understanding these components is crucial for
mastering SQL and its role in relational database systems. Some of the Key components of a
SQL System are:
 Databases: Databases are structured collections of data organized into tables, rows, and
columns. Databases serve as repositories for storing information efficiently and provide a
way to manage and access data.
 Tables: Tables are the fundamental building blocks of a database, consisting of rows
(records) and columns (attributes or fields). Tables ensure data integrity and consistency by
defining the structure and relationships of the stored information.
 Queries: Queries are SQL commands used to interact with databases. They enable users to
retrieve, update, insert, or delete data from tables, allowing for efficient data manipulation
and retrieval.
 Constraints: Constraints are rules applied to tables to maintain data
integrity. Constraints define conditions that data must meet to be stored in the database,
ensuring accuracy and consistency.
 Stored Procedures: Stored procedures are pre-compiled SQL statements stored in the
database. Stored procedures can accept parameters, execute complex operations, and return
results, enhancing efficiency, reusability, and security in database management.
 Transactions: Transactions are groups of SQL statements that are executed as a single unit
of work. Transactions ensure data consistency and integrity by allowing for the rollback of
changes if any part of the transaction fails.
Some other important components include:
 Data Types
 Indexes
 Views
 Security and Permissions
 Joins
SQL Injection is a cyberattack where malicious SQL queries are injected into input fields to
manipulate a database, enabling unauthorized access, data modification, or corruption. Using
parameterized queries and input validation helps prevent such attacks.
What are the Characteristics of SQL?
 User-Friendly and Accessible: SQL is designed for a broad range of users, including
those with minimal programming experience, making it approachable for non-technical
individuals.
 Declarative Language: As a non-procedural language, SQL allows users to specify what
data is needed rather than how to retrieve it, focusing on the desired results rather than the
retrieval process.
 Efficient Database Management: SQL enables the creation, modification, and
management of databases efficiently, saving time and simplifying complex database
operations.
 Standardized Language: Based on ANSI (American National Standards Institute) and
ISO (International Organization for Standardization) standards, SQL ensures consistency
and stability across various database management systems (DBMS).
 Command Structure: SQL does not require a continuation character for multi-line
queries, allowing flexibility in writing commands across one or multiple lines.
 Execution Mechanism: Queries are executed using a termination character (e.g., a
semicolon ;), enabling immediate and accurate command processing.
 Built-in Functionality: SQL includes a rich set of built-in functions for data manipulation,
aggregation, and formatting, empowering users to handle diverse data-processing needs
effectively.
How SQL Works?
Structured Query Language (SQL) operates on a server machine, where it processes database
queries and returns results efficiently. Below are the key software components involved in the
SQL execution process.
1. Input: The process begins when a user submits an SQL query through a database interface
or application. This query typically specifies the desired operation, such as data retrieval,
insertion, updating, or deletion.
2. Parsing: The query is passed to the query processor, which breaks it into smaller units
called tokens. These tokens represent keywords, table names, column names, and other
elements of the query. The processor then validates the syntax against SQL standards and
the database schema to ensure the query is well-formed and executable.
3. Optimization: After parsing, the query is handed to the optimizer, which evaluates
multiple ways to execute the query. The optimizer considers factors like indexes, table
statistics, and available resources to generate the most efficient execution plan. This step
ensures that the query runs with minimal resource consumption and maximum
performance.
4. Execution: The execution engine follows the plan provided by the optimizer. It interacts
with the storage engine, which retrieves, manipulates, or updates the required data from the
database tables. During this step, SQL statements like SELECT, INSERT, UPDATE, or
DELETE are translated into actions performed on the underlying data.
5. Output: Once the execution engine processes the query, the result is formatted and
returned to the user. Depending on the query type, the output could be a result set (for
SELECT queries) or an acknowledgment of the operation (for INSERT, UPDATE, or
DELETE queries).
By combining these steps, SQL ensures the seamless interaction between users and relational
databases, enabling efficient data manipulation and retrieval.
Rules for Writing SQL Queries
There are certain rules for SQL which would ensure consistency and functionality across
databases. By following these rules, queries will be well formed and well executed in any
database.
 Statement Termination: Every SQL statement ends with a semicolon (;), signaling the
DBMS to execute the command.
 Case Insensitivity: SQL keywords (e.g., SELECT, INSERT) are case-insensitive, but
database names and column names may be case-sensitive depending on the DBMS.
 Whitespace Flexibility: SQL statements can span multiple lines, but keywords and
identifiers must be separated by at least one space.
 Unique Identifiers: Reserved words (e.g., SELECT, FROM) cannot be used as table or
column names unless enclosed in double quotes (") or backticks (`), depending on the
DBMS.
 Comments: Comments enhance readability:
o Single-line comments: --
o Multi-line comments: /* ... */
 Data Integrity: Constraints like NOT NULL, UNIQUE, and PRIMARY KEY must be
defined correctly to maintain data consistency.
 String Literals: String values must be enclosed in single quotes (').
 Valid Identifiers: Table and column names must:
o Begin with an alphabetic character.
o Contain up to 30 characters.
o Avoid special characters except underscores (_).
By following these rules, SQL users ensure reliable query execution and maintainable database
structures.
What are SQL Commands?
Structured Query Language (SQL) commands are standardized instructions used by developers
to interact with data stored in relational databases. These commands allow for the creation,
manipulation, retrieval, and control of data, as well as database structures. SQL commands
are categorized based on their specific functionalities:
1. Data Definition Language
These commands are used to define the structure of database objects by creating, altering,
and dropping the database objects. Based on the needs of the business, database engineers
create and modify database objects using DDL. The CREATE command, for instance, is used
by the database engineer to create database objects like tables, views, and indexes.
Command Description

CREATE Creates a new table, a view on a table, or some other object in the database.

ALTER Modifies an existing database object, such as a table


Command Description

DROP Deletes an entire table, a view of a table, or other objects in the database

2. Data Manipulation Language


A relational database can be updated with new data using data manipulation language (DML)
statements. The INSERT command, for instance, is used by an application to add a new record
to the database.
Command Description

INSERT Creates a record.

UPDATE Modifies records.

DELETE Deletes records.

3. Data Query Language


Data retrieval instructions are written in the data query language (DQL), which is used to
access relational databases. The SELECT command is used by software programs to filter and
return particular results from a SQL table.
4. Data Control language
DCL commands manage user access to the database by granting or revoking permissions.
Database administrators use DCL to enforce security and control access to database objects.
Command Description

GRANT Gives a privilege to the user.

REVOKE Takes back privileges granted by the user.

5. Transaction Control Language


TCL commands manage transactions in relational databases, ensuring data integrity and
consistency. These commands are used to commit changes or roll back operations in case of
errors.
Command Description

Saves all changes made during the current transaction on a permanent basis.
Some databases provide an auto-commit feature, which can be configured
COMMIT using settings.

Reverts changes made during the current transaction, ensuring no unwanted


ROLLBACK changes are saved.
Command Description

Sets a point within a transaction to which changes can be rolled back, allowing
SAVEPOINT partial rollbacks

Benefits of SQL
 Efficiency: SQL is designed to handle complex queries and large datasets with optimal
performance, making data retrieval and manipulation seamless.
 Standardization: As an ANSI and ISO standard language, SQL provides a universal
method to interact with relational databases across platforms.
 Scalability: SQL supports databases ranging from small-scale applications to enterprise-
level systems, ensuring smooth operations regardless of size.
 Flexibility: SQL can be extended with procedural programming (e.g., PL/SQL, T-SQL) to
build complex business logic and custom functions.
Limitations of SQL
 Complexity in Advanced Operations: Advanced functionalities such as indexing, query
optimization, and performance tuning require in-depth technical knowledge.
 Scalability Concerns: SQL performs best with structured data; handling unstructured data
or massive distributed systems can pose challenges.
 Platform-Specific Variations: While SQL is standardized, many databases implement
unique extensions, leading to portability and compatibility issues.
SQL Use Cases
 E-Commerce: Manage customer orders, product catalogs, and inventory.
 Healthcare: Maintain patient records and appointment schedules.
 Banking: Analyze transaction histories and generate financial reports.
 Web Development: Power dynamic websites with user-specific content.
 Machine Learning and Data Science: Combine SQL databases with tools like Python, R,
and TensorFlow to streamline machine learning workflows.
Conclusion
SQL(Structured Query Language) is a programming language designed for managing and
manipulating data stored in relational databases. It is used for interacting with DBMS like
MySQL, SQL Server, Oracle, and PostgreSQL.
MySQL Data Types (Version 8.0) What are SQL Data Types?
SQL data types define the kind of data a column can store, dictating how the database
manages and interacts with the data. Each data type in SQL specifies a set of allowed values,
as well as the operations that can be performed on the values.
SQL data types are broadly categorized into several groups:
 Numeric Data Types
 Character and String Data Types
 Date and Time Data Types
 Binary Data Types
 Boolean Data Types
 Special Data Types
1. Numeric Data Types
Numeric data types are fundamental to database design and are used to store numbers, whether
they are integers, decimals, or floating-point numbers. These data types allow for mathematical
operations like addition, subtraction, multiplication, and division, which makes them
essential for managing financial, scientific, and analytical data.
Exact Numeric Datatype
Exact numeric types are used when precise numeric values are needed, such as for financial
data, quantities, and counts. Some common exact numeric types include:
Data Type Description Range

-9,223,372,036,854,775,808 to
BIGINT Large integer numbers
9,223,372,036,854,775,807

INT Standard integer values -2,147,483,648 to 2,147,483,647

SMALLINT Small integers -32,768 to 32,767

TINYINT Very small integers 0 to 255

Exact fixed-point numbers


DECIMAL -10^38 + 1 to 10^38 - 1
(e.g., for financial values)

Similar to DECIMAL, used


NUMERIC -10^38 + 1 to 10^38 - 1
for precision data

-922,337,203,685,477.5808 to
MONEY For storing monetary values
922,337,203,685,477.5807

SMALLMONEY Smaller monetary values -214,748.3648 to 214,748.3647

Approximate Numeric Datatype


These types are used to store approximate values, such as scientific measurements or large
ranges of data that don't need exact precision.
Data Type Description Range

FLOAT Approximate numeric values -1.79E+308 to 1.79E+308

REAL Similar to FLOAT, but with less precision -3.40E+38 to 3.40E+38

2. Character and String Data Types


Character data types are used to store text or character-based data. The choice between fixed-
length and variable-length data types depends on the nature of your data.
Character String Data Types
Data Type Description

The maximum length of 8000 characters.(Fixed-Length non-Unicode


Char
Characters)

The maximum length of 8000 characters.(Variable-Length non-Unicode


Varchar
Characters)

The maximum length of 2^31 - 1 characters(SQL Server 2005 only).


Varchar(max)
(Variable Length non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable Length non-


Text
Unicode data)

Unicode Character String Data Types


Unicode data types are used to store characters from any language, supporting a wider variety
of characters. These are given in below table.
Data Type Description

The maximum length of 4000 characters(Fixed-Length Unicode


Nchar
Characters)

The maximum length of 4000 characters.(Variable-Length Unicode


Nvarchar
Characters)

The maximum length of 2^31 - 1 characters(SQL Server 2005 only).


Nvarchar(max)
(Variable Length Unicode data)
3. Date and Time Data Type
SQL provides several data types for storing date and time information. They are essential for
managing timestamps, events, and time-based queries. These are given in the below table.
Data Type Description Storage
Size

DATE stores the data of date (year, month, day) 3 Bytes

TIME stores the data of time (hour, minute,second) 3 Bytes

store both the data and time (year, month, day, hour, minute,
DATETIME 8 Bytes
second)

4. Binary Data Types in SQL


Binary data types are used to store binary data such as images, videos, or other file types.
These include:
Data Type Description Max Length

Binary Fixed-length binary data. 8000 bytes

VarBinary Variable-length binary data. 8000 bytes

Image Stores binary data as images. 2,147,483,647 bytes

5. Boolean Data Type in SQL


The BOOLEAN data types are used to store logical values, typically TRUE or FALSE. It's
commonly used for flag fields or binary conditions.
Data Type Description

BOOLEAN Stores a logical value (TRUE/FALSE).

6. Special Data Types


SQL also supports some specialized data types for advanced use cases:
XML Data Type
The XML data type allows for the storage of XML documents and fragments in a SQL Server
database.
DataType Description

XML Datatype Used to store XML data and manipulate XML structures in the database

Spatial Data Type


A datatype is used for storing planar spatial data, such as points, lines, and polygons, in a
database table.
DataType Description

Geometry stores planar spatial data, such as points, lines, and polygons, in a database table.

Conclusion
SQL Data Types are the fundamental building blocks of relational database design.
Understanding which data type to use for each column is essential for ensuring data
integrity, optimizing storage, and improving performance. Whether we are working
with numerical data, text, dates, or binary data, choosing the appropriate data type will help
maintain a well-structured and efficient database. By mastering SQL data types, we can build
robust, high-performance databases that meet the needs of any application.
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided
into categories such as Data Definition Language (DDL), Data Manipulation Language (DML),
Data Control Language (DCL), Data Query Language (DQL), and Transaction Control
Language (TCL).
In this article, we will explain the different types of SQL commands,
including DDL, DML, DCL, DQL, and TCL. These SQL sublanguages serve specific
purposes and are important for effective database management.
What are SQL Commands?
SQL commands are the fundamental building blocks for communicating with a database
management system (DBMS). It is used to interact with the database with some operations. It is
also used to perform specific tasks, functions, and queries of data. SQL can perform various
tasks like creating a table, adding data to tables, dropping the table, modifying the table, set
permission for users.
SQL Commands are mainly categorized into five categories:
 DDL – Data Definition Language
 DQL – Data Query Language
 DML – Data Manipulation Language
 DCL – Data Control Language
 TCL - Transaction Control Language
1. DDL - Data Definition Language
DDL or Data Definition Language actually consists of the SQL commands that can be used
for defining, altering, and deleting database structures such as tables, indexes, and schemas. It
simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database
Common DDL Commands
Command Description Syntax

Create database or its objects CREATE TABLE table_name


CREATE (table, index, function, views, (column1 data_type, column2
store procedure, and triggers) data_type, ...);

Delete objects from the


DROP DROP TABLE table_name;
database

ALTER Alter the structure of the ALTER TABLE table_name ADD


Command Description Syntax

database COLUMN column_name data_type;

Remove all records from a


table, including all spaces
TRUNCATE TRUNCATE TABLE table_name;
allocated for the records are
removed

Add comments to the data COMMENT 'comment_text' ON


COMMENT
dictionary TABLE table_name;

Rename an object existing in RENAME TABLE old_table_name


RENAME
the database TO new_table_name;

Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
In this example, a new table called employees is created with columns for employee ID, first
name, last name, and hire date.
2. DQL - Data Query Language
DQL statements are used for performing queries on the data within schema objects. The
purpose of the DQL Command is to get some schema relation based on the query passed to
it. This command allows getting the data out of the database to perform operations with it. When
a SELECT is fired against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program.
DQL Command
Command Description Syntax

It is used to retrieve data from SELECT column1, column2, ...FROM


SELECT
the database table_name WHERE condition;

Example:
SELECT first_name, last_name, hire_date
FROM employees
WHERE department = 'Sales'
ORDER BY hire_date DESC;
This query retrieves employees' first and last names, along with their hire dates, from the
employees table, specifically for those in the 'Sales' department, sorted by hire date.
3. DML - Data Manipulation Language
The SQL commands that deal with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements. It is the
component of the SQL statement that controls access to data and to the database. Basically, DCL
statements are grouped with DML statements.
Common DML Commands
Command Description Syntax

Insert data into a INSERT INTO table_name (column1, column2, ...)


INSERT
table VALUES (value1, value2, ...);

Update existing data UPDATE table_name SET column1 = value1,


UPDATE
within a table column2 = value2 WHERE condition;

Delete records from


DELETE DELETE FROM table_name WHERE condition;
a database table

Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency

Call a PL/SQL or
CALL CALL procedure_name(arguments);
JAVA subprogram

EXPLAIN Describe the access EXPLAIN PLAN FOR SELECT * FROM


PLAN path to data table_name;

Example:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Jane', 'Smith', 'HR');
This query inserts a new record into the employees table with the first name 'Jane', last name
'Smith', and department 'HR'.
4. DCL - Data Control Language
DCL (Data Control Language) includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions, and other controls of the database system. These
commands are used to control access to data in the database by granting or revoking
permissions.
Common DCL Commands
Command Description Syntax

Assigns new privileges to a


GRANT privilege_type [(column_list)]
user account, allowing access
GRANT ON [object_type] object_name TO user
to specific database objects,
[WITH GRANT OPTION];
actions, or functions.

Removes previously granted


REVOKE [GRANT OPTION FOR]
privileges from a user
privilege_type [(column_list)] ON
REVOKE account, taking away their
[object_type] object_name FROM user
access to certain database
[CASCADE];
objects or actions.

Example of DCL
GRANT SELECT, UPDATE ON employees TO user_name;
This command grants the user user_name the permissions to select and update records in the
employees table.
5. 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. We can explore more about transactions here.
Common TCL Commands
Command Description Syntax

BEGIN BEGIN TRANSACTION


Starts a new transaction
TRANSACTION [transaction_name];

COMMIT Saves all changes made during COMMIT;


Command Description Syntax

the transaction

Undoes all changes made


ROLLBACK ROLLBACK;
during the transaction

Creates a savepoint within the


SAVEPOINT SAVEPOINT savepoint_name;
current transaction

Example:
BEGIN TRANSACTION;
UPDATE employees SET department = 'Marketing' WHERE department = 'Sales';
SAVEPOINT before_update;
UPDATE employees SET department = 'IT' WHERE department = 'HR';
ROLLBACK TO SAVEPOINT before_update;
COMMIT;
In this example, a transaction is started, changes are made, and a savepoint is set. If needed, the
transaction can be rolled back to the savepoint before being committed.
Most Important SQL Commands
There are also a few other SQL Commands we often rely on when writing powerful queries.
While they don’t fit neatly into the five main categories, they’re absolutely essential for working
with data effectively.
Command Description

SELECT Retrieves data from one or more tables.

INSERT Adds new rows (records) to a table.

UPDATE Modifies existing data in a table.

DELETE Removes specific rows from a table.


Command Description

CREATE TABLE Creates a new table in the database.

Modifies the structure of an existing table (e.g., add or remove


ALTER TABLE
columns).

DROP TABLE Permanently deletes a table and its data.

TRUNCATE TABLE Removes all rows from a table but keeps its structure intact.

WHERE Filters records based on a condition.

ORDER BY Sorts the result set in ascending or descending order.

GROUP BY Groups rows that have the same values in specified columns.

HAVING Filters grouped data (used with GROUP BY).

JOIN Combines rows from two or more tables based on a related column.

DISTINCT Removes duplicate values from the result set.

IN / BETWEEN /
Used for advanced filtering conditions.
LIKE

UNION Combines the result of two or more SELECT queries.


Command Description

GRANT Gives user privileges or permissions.

REVOKE Removes user privileges.

COMMIT Saves all changes made in the current transaction.

ROLLBACK Undoes changes if something goes wrong in a transaction.

SAVEPOINT Sets a point in a transaction to roll back to if needed.

Conclusion
SQL commands such as DDL, DML, DCL, DQL, and TCL are foundational for
effective database management. From creating and modifying tables with DDL commands to
managing transactions with TCL commands in SQL, understanding each type of command
enhances our database skills. Whether we are manipulating data, or managing data, SQL
provides all sets of tools. Now, with this detailed guide, we hope you have gained a deep
understanding of SQL commands, their categories, and syntax with examples.

SQL Operators



SQL operators are important in database management systems (DBMS) as they allow us to
manipulate and retrieve data efficiently. Operators in SQL perform arithmetic, logical,
comparison, bitwise, and other operations to work with database values. Understanding SQL
operators is crucial for performing complex data manipulations, calculations, and filtering
operations in queries.
In this guide, we’ll explain the different types of SQL operators, including arithmetic
operators, comparison operators, logical operators, bitwise operators, and more. We’ll provide
clear examples to demonstrate how they work, helping you optimize your SQL queries for better
performance and accuracy.
Operators in SQL
SQL operators are symbols or keywords used to perform operations on data in SQL queries.
These operations can include mathematical calculations, data comparisons, logical
manipulations, other data-processing tasks. Operators help in filtering, calculating, and updating
data in databases, making them crucial for query optimization and accurate data management.
Types of SQL Operators
SQL operators can be categorized based on the type of operation they perform. Here are the
primary types of SQL operators:
 Arithmetic Operator
 Comparison Operator
 Logical Operator
 Bitwise Operators
 Compound Operators
 Special Operators
Each of these operators is essential for performing different types of operations on data in SQL
databases.
SQL Arithmetic Operators
Arithmetic operators in SQL are used to perform mathematical operations on numeric data
types in SQL queries. Some common arithmetic operators:
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.

Example: Arithmetic Operations


In this example, we calculates a 5% increment on employee salaries and returns both the original
and updated salary values.
Query:
SELECT emp_salary, emp_salary * 1.05 AS "Revised Salary" FROM employee;
Output:
Arithmetic Operation Example

SQL Comparison Operators


Comparison Operators in SQL are used to compare one expression's value to other
expressions. SQL supports different types of comparison operator, which are described below:
Operator Description

= Equal to.

> Greater than.

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.

Example: Comparison Operation


In this example, we will retrieve all records from the "MATHS" table where the value in the
"MARKS" column is equal to 50.
Query:
SELECT * FROM MATHS WHERE MARKS=50;
Output:
SQL Logical Operators
Logical Operators in SQL are used to combine or manipulate conditions in SQL queries to
retrieve or manipulate data based on specified criteria..
Operator Description

AND Logical AND compares two Booleans as expressions and returns true when both
expressions are true.

OR Logical OR compares two Booleans as expressions and returns true when one of the
expressions is true.

NOT Not takes a single Boolean as an argument and change its value from false to true or
from true to false.

Example: Logical Operation


In this example, retrieve all records from the "employee" table where the "emp_city" column is
equal to 'Allahabad' and the "emp_country" column is equal to 'India'.
Query:
SELECT * FROM employee WHERE emp_city =
'Allahabad' AND emp_country = 'India';
Output:
SQL Bitwise Operators
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:
Operato
r Description

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise XOR (exclusive OR) operator

~ Bitwise NOT (complement) operator

<< Left shift operator

>> Right shift operator

SQL Compound Operators


Compound operators combine an operation with assignment. These operators modify the value
of a column and store the result in the same column in a single step. Some Compound operators
are:
Operato
r Description

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulo and assign

&= Bitwise AND and assign


Operato
r Description

^= Bitwise XOR and assign

|= Bitwise OR and assign

SQL Special Operators


SQL also provides several special operators that serve specific functions such as filtering data
based on a range, checking for existence, and comparing sets of values.
Operators Description

ALL is used to select all records of a SELECT STATEMENT. It compares a


ALL value to every value in a list of results from a query. The ALL must be
preceded by the comparison operators and evaluated to TRUE if the query
returns no rows.

ANY ANY compares a value to each value in a list of results from a query and
evaluates to true if the result of an inner query contains at least one row.

BETWEEN The SQL BETWEEN operator tests an expression against a range. The range
consists of a beginning, followed by an AND keyword and an end expression.

IN The IN operator checks a value within a set of values separated by commas and
retrieves the rows from the table that match.

The EXISTS checks the existence of a result of a subquery. The EXISTS


EXISTS subquery tests whether a subquery fetches at least one row. When no data is
returned then this operator returns 'FALSE'.

SOME operator evaluates the condition between the outer and inner tables and
SOME evaluates to true if the final result returns any one row. If not, then it evaluates
to false.

UNIQUE The UNIQUE operator searches every unique row of a specified table.

Example: Special Operator (BETWEEN)


In this example, we will retrieve all records from the "employee" table where the "emp_id"
column has a value that falls within the range of 101 to 104 (inclusive).
Query:
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output:

Conclusion
SQL operators are essential tools for working with data in a relational database. Whether you're
performing arithmetic operations, logical comparisons, bitwise manipulations, or using special
operators to filter data, understanding these operators is key to writing efficient and
effective SQL queries. By mastering SQL operators, we can simplify complex data operations,
enhance query performance, and manipulate data more effectively. Whether you're a beginner or
an advanced SQL user, the knowledge of operators will help you unlock the full potential of
SQL queries and database management systems.

You might also like