0% found this document useful (0 votes)
2 views

unit 1 sql

The document provides an overview of SQL and PL/SQL, focusing on relational databases, their structure, and the principles of RDBMS as defined by Codd's rules. It discusses SQL's capabilities, advantages, and limitations, as well as essential database objects and data types used in SQL. Additionally, it highlights the importance of SQL in data management and its role in various applications across industries.

Uploaded by

vavemos441
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 1 sql

The document provides an overview of SQL and PL/SQL, focusing on relational databases, their structure, and the principles of RDBMS as defined by Codd's rules. It discusses SQL's capabilities, advantages, and limitations, as well as essential database objects and data types used in SQL. Additionally, it highlights the importance of SQL in data management and its role in various applications across industries.

Uploaded by

vavemos441
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

SQL AND PL/SQL

UNIT I

Relational Database:
A relational database is a collection of information that organizes data in predefined relationships
where data is stored in one or more tables (or "relations") of columns and rows, making it easy to
see and understand how different data structures relate to each other.
Database:
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database management
system (DBMS).
Data Table:
A data table is a document comprising columns, rows and cells that contain specific values. They
store information that people can retrieve later and update as needed. The data table title, column
headers and row headers can help a user understand the information in the table more clearly.
Data:
In computing, data is information that has been translated into a form that is efficient for movement
or processing. Data, in the context of databases, refers to all the single items that are stored in a
database, either individually or as a set. Data in a database is primarily stored in database tables,
which are organized into columns and rows.

Introduction to RDBMS:
RDBMS (Relational Database Management System)
RDBMS stands for Relational Database Management System.
All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE, My-
SQL, and Microsoft Access are based on RDBMS.
It is called Relational Database Management System (RDBMS) because it is based on the
relational model introduced by E.F. Codd. (Edgar F. Codd)

How it works :
Data is represented in terms of tuples (rows) in RDBMS.
A relational database is the most commonly used database. It contains several tables, and each
table has its primary key.
Due to a collection of an organized set of tables, data can be accessed easily in RDBMS.

12 Codd's Rules:
Every database has tables and constraints cannot be referred to as a rational database system.
And if any database has only relational data model, it cannot be a Relational Database System
(RDBMS). So, some rules define a database to be the correct RDBMS. These rules were
developed by Dr Edgar F. Codd (E.F. Codd) in 1985, who has vast research knowledge on the
Relational Model of database Systems. Codd presents his 13 rules for a database to test the
concept of DBMS against his relational model, and if a database follows the rule, it is called a true
relational database (RDBMS). These 13 rules are popular in RDBMS, known as Codd's 12 rules.
Rule 0: The Foundation Rule -The database must be in relational form. So that the system can
handle the database through its relational capabilities.
Rule 1: Information Rule -A database contains various information, and this information must be
stored in each cell of a table in the form of rows and columns.
Rule 2: Guaranteed Access Rule -Every single or precise data (atomic value) may be accessed
logically from a relational database using the combination of primary key value, table name, and
column name.
Rule 3: Systematic Treatment of Null Values -This rule defines the systematic treatment of Null
values in database records. The null value has various meanings in the database, like missing the
data, no value in a cell, inappropriate information, unknown data and the primary key should not
be null.
Rule 4: Active/Dynamic Online Catalog based on the relational model - It represents the
entire logical structure of the descriptive database that must be stored online and is known as a
database dictionary. It authorizes users to access the database and implement a similar query
language to access the database.
Rule 5: Comprehensive Data Sub Language Rule- The relational database supports various
languages, and if we want to access the database, the language must be the explicit, linear or
well-defined syntax, character strings and supports the comprehensive: data definition, view
definition, data manipulation, integrity constraints, and limit transaction management operations. If
the database allows access to the data without any language, it is considered a violation of the
database.
Rule 6: View Updating Rule - All views table can be theoretically updated and must be practically
updated by the database systems.
Rule 7: Relational Level Operation (High-Level Insert, Update and delete) Rule -A database
system should follow high-level relational operations such as insert, update, and delete in each
level or a single row. It also supports union, intersection and minus operation in the database
system.
Rule 8: Physical Data Independence Rule- All stored data in a database or an application must
be physically independent to access the database. Each data should not depend on other data or
an application. If data is updated or the physical structure of the database is changed, it will not
show any effect on external applications that are accessing the data from the database.
Rule 9: Logical Data Independence Rule-It is similar to physical data independence. It means, if
any changes occurred to the logical level (table structures), it should not affect the user's view
(application). For example, suppose a table either split into two tables, or two table joins to create
a single table, these changes should not be impacted on the user view application.
Rule 10: Integrity Independence Rule -A database must maintain integrity independence when
inserting data into table's cells using the SQL query language. All entered values should not be
changed or rely on any external factor or application to maintain integrity. It is also helpful in
making the database-independent for each front-end application.
Rule 11: Distribution Independence Rule-The distribution independence rule represents a
database that must work properly, even if it is stored in different locations and used by different
end-users. Suppose a user accesses the database through an application; in that case, they
should not be aware that another user uses particular data, and the data they always get is only
located on one site. The end users can access the database, and these access data should be
independent for every user to perform the SQL queries.
Rule 12: Non-Subversion Rule - The non-submersion rule defines RDBMS as a SQL language
to store and manipulate the data in the database. If a system has a low-level or separate language
other than SQL to access the database system, it should not subvert or bypass integrity to
transform data.

STURUCTURED QUERY LANGUAGE (SQL)


It enables you to create and operate on a relation database by storing the information in the form
of a table. Basically, SQL is used to query data from the database storage structures such as
tables and views. SQL is a powerful and widely used programming language designed for
managing and manipulating relational databases. It was first developed in the 1970s by IBM
researchers, and has since become a standard language for managing and querying databases
across various platforms and industries. SQL enables users to perform complex operations such
as querying, inserting, updating, and deleting data in a database. It’s simple and user-friendly
syntax allows even non-technical users to interact with databases and retrieve data without having
to write lengthy lines of code. SQL also provides a standardized way of communicating with
databases, ensuring that data is consistent and uniform across different systems. Its popularity
and versatility have made it a must-have skill for data professionals and developers, as it is used
extensively in various applications such as web development, data analytics, business
intelligence, and more.

Limitations of SQL:
It is able to execute only one SQL command at a time
It is not possible to express all sorts of user queries using SQL as it does not support the full
flagged capability of procedural language.

Using SQL, it is not possible to perform the following set of actions.


Printing a customize report
Formatting query result in the GUI (Graphical User Interface) format

Need of SQL:
● It is widely used in the Business Intelligence tool.
● Data Manipulation and data testing are done through SQL.
● Data Science tools depend highly on SQL. Big data tools such as Spark, Impala are
dependent on SQL.
● It is one of the demanding industrial skills.

Advantages of SQL:
SQL has many advantages which makes it popular and highly demanded. It is a reliable and
efficient language used for communicating with the database. Some advantages of SQL are as
follows:

1. Faster Query Processing: Large amount of data is retrieved quickly and efficiently.
Operations like Insertion, deletion, manipulation of data is also done in almost no time.
2. No Coding Skills: For data retrieval, large number of lines of code is not required. All basic
keywords such as SELECT, INSERT INTO, UPDATE, etc are used and also the syntactical
rules are not complex in SQL, which makes it a user-friendly language.
3. Standardized Language: Due to documentation and long establishment over years, it
provides a uniform platform worldwide to all its users.
4. Portable: It can be used in programs in PCs, server, laptops independent of any platform
(Operating System, etc). Also, it can be embedded with other applications as per
need/requirement/use.
5. Interactive Language: Easy to learn and understand, answers to complex queries can be
received in seconds.
6. Multiple data views
7. Scalability: SQL databases can handle large volumes of data and can be scaled up or down
as per the requirements of the application.
8. Security: SQL databases have built-in security features that help protect data from
unauthorized access, such as user authentication, encryption, and access control.
9. Data Integrity: SQL databases enforce data integrity by enforcing constraints such as
unique keys, primary keys, and foreign keys, which help prevent data duplication and
maintain data accuracy.
10. Backup and Recovery: SQL databases have built-in backup and recovery tools that help
recover data in case of system failures, crashes, or other disasters.
11. Data Consistency: SQL databases ensure consistency of data across multiple tables
through the use of transactions, which ensure that changes made to one table are
reflected in all related tables.

Disadvantages of SQL:
Although SQL has many advantages, still there are a few disadvantages.
Various Disadvantages of SQL are as follows:

1. Complex Interface: SQL has a difficult interface that makes few users uncomfortable while
dealing with the database.
2. Cost: Some versions are costly and hence, programmers cannot access it.
3. Partial Control: Due to hidden business rules, complete control is not given to the
database.
4. Limited Flexibility: SQL databases are less flexible than NoSQL databases when it comes
to handling unstructured or semi-structured data, as they require data to be structured into
tables and columns.
5. Lack of Real-Time Analytics: SQL databases are designed for batch processing and do not
support real-time analytics, which can be a disadvantage for applications that require real-
time data processing.
6. Limited Query Performance: SQL databases may have limited query performance when
dealing with large datasets, as queries may take longer to process than in-memory
databases.
7. Complexity: SQL databases can be complex to set up and manage, requiring skilled
database administrators to ensure optimal performance and maintain data integrity.

Elements of SQL
Following are the major elements of SQL, which we will discuss in the subsequent chapters,
1) Database Objects
2) Keywords/Reserved Words
3) Operators
4) Expression
5) Variables
6) Constants
For Ex. Consider the following query
SQL> SELECT EMPNO, ENAME, 12 * SAL FROM EMP WHERE JOB=’MANAGER’ AND
SAL>&VSAL;
Here,
EMP is a table that is a database object.
SELECT, FROM, WHERE are keywords.
*,> are operators.
12 * SAL is an Expression.
VSAL is variable.
12,’MANAGER’ are constant value.

DATABASE OBJECTS
Physical database design consists of defining database objects and their relationships.
You can create the following database objects in a DB2 database:
Tables
Constraints
Indexes
Triggers
Sequences
Views

You can use Data Definition Language (DDL) statements or tools such as IBM® Data Studio to
create these database objects. The DDL statements are generally prefixed by the keywords
CREATE or ALTER.
Understanding the features and functionality that each of these database objects provides is
important to implement a good database design that meets your current business's data storage
needs while remaining flexible enough to accommodate expansion and growth over time.
Concepts Common To Most Database Objects :

Tables: Tables are logical structures maintained by the database manager and are made up of
columns and rows. DB2 databases store persistent data in tables, but there are also tables that
are used for presenting results, summary tables and temporary tables.
Constraints Within any business, data must often adhere to certain restrictions or rules. For
example, an employee number must be unique. The database manager provides constraints as a
way to enforce such rules.

Indexes: An index is a set of pointers that are logically ordered by the values of one or more keys.
The pointers can refer to rows in a table, blocks in an MDC or ITC table, XML data in an XML
storage object, and so on.

Triggers: A trigger defines a set of actions that are performed in response to an insert, update, or
delete operation on a specified table. When such an SQL operation is executed, the trigger is said
to have been activated. Triggers are optional and are defined using the CREATE TRIGGER
statement.

Sequences: A sequence is a database object that allows the automatic generation of values, such
as cheque numbers. Sequences are ideally suited to the task of generating unique key values.
Applications can use sequences to avoid possible concurrency and performance problems
resulting from column values used to track numbers. The advantage that sequences have over
numbers created outside the database is that the database server keeps track of the numbers
generated. A crash and restart will not cause duplicate numbers from being generated.

Views: A view is an efficient way of representing data without the need to maintain it. A view is not
an actual table and requires no permanent storage. A "virtual table" is created and used.
Cursors: A cursor is used in an application program to select a set of rows and then process that
returned data one row at a time. When a SELECT statement in an embedded SQL application
returns multiple rows of data, you need a mechanism that makes this returned data or result set
available to your application program, one row after another.

Reserved words:
Microsoft SQL Server uses reserved keywords for defining, manipulating, and accessing
databases. Reserved keywords are part of the grammar of the Transact-SQL language that is
used by SQL Server to parse and understand Transact-SQL statements and batches. Although it
is syntactically possible to use SQL Server reserved keywords as identifiers and object names in
Transact-SQL scripts, you can do this only by using delimited identifiers.
The following table lists SQL Server and Azure Synapse Analytics reserved keywords.
ADD EXTERNAL PROCEDURE
ALL FETCH PUBLIC

DATA TYPES:
A data type helps the user to know what kind of data the column or field of table or cluster or
variable can hold. When we create a procedure or function. We must specify a data type for each
of its arguments. Oracle supports the following Internal Data Types.

1.NUMBER(P,S): variable length numeric having precision (P) in the range 1-38 and scale(S) in
the range -84 to 127, Specification of precision (P) and scale is optional as Oracle assumes the
maximum range of both the values. It is also used to store signed integers, Fixed point numbers ,
and the floating point numbers.
Eg. 1) empno number(2)
2) sal number(7,2)
Points to remember while working with number data type:
1) If precision and scale are not specified then it assumes a maximum range for both the values i.e
for P and S.
2) Scale (s) rounds the value after the decimal point to S digits.
3) If the scale is negative, S number of zeros are placed left of the decimal.
4) If the scale value is greater than precision value, (S-P) zeros are required after decimal.
5) If the value exceeds the precision an error is generated.

NUMBER SUBTYPES: the following subtypes can be used during defining a Number of Data
types.
INTEGER, SMALLINT, INT are used to insert integer values.
FLOAT, REAL is used to insert floating values.

2. DATE: this data type is used to store data and time information. Oracle software is the year
2000(Y2K) complaint i.e when a new row is inserted into the table for a data column , the century
information is picked up from the SYSDATE function . Oracle stores date data a number in an
internal numeric format, representing the Century, Year, Month, Day, Hours Minutes and Seconds
and store date in a fixed-length of & bytes. The default format of date is DD/MON/YY and it can be
modified by changing the NLS_DATE_FORMAT parameters in init.ora file. Using date conversion
function users can view the date in different formats.
Valid dates are between 1-JAN-4712 B.C to 31-DEC-9999 A.D

3. RAW(size): It is useful to store binary data and is used to store a graphic or digitized picture.
Maximum 2000 bytes can be allotted for the RAW type column. One must specify
The size . Only storage and retrieval of data are possible using this data type and one cannot
manipulate the data but it can be indexed
4. LONG RAW: it is the same as the RAW data type but it can store raw binary data type up to 2
Gigabytes.

5. ROWID and UROWID: It is binary representation of the physical address of a row, which is
displayed in hexadecimal format. UROWID(Universal Rowid) data type can store physical, Logical
and foreign (Non-Oracle) rowids.

6. LONG: it is used to store variable-length character datatype up-to 2 GB


Restrictions on use of LONG datatype
A table can have only one column having a long datatype.
It cannot be indexed.
It can’t appear in where groups by and order by clause of the select statement.
Procedure and stores procedure cannot accept the long datatype as arguments.

7.CHAR(size): It is a fixed length character datatype of length size bytes. The Maximum size is
2000 bytes. The default and minimum size is 1 byte when size is not specified. A value ‘ram’ is not
the same as ‘RAM’ or Ram i.e data/vales are case sensitive in Oracle.

8. VARCHAR2 (size) OR VARCHAR(size): it is a variable length character string data type of


length Size bytes. The maximum size is 4000 bytes while the minimum size is 1 byte. One must
specify the size. A value ‘ram’ is not same as ‘RAM’ or ‘Ram’ i.e., data are case sensitive,
Varchar data type is synonym of varchar2 data type.

9. LOB data type: Oracle 8 onwards supports the LOB data type. It is known as large Object data
types. It is used to store un-structured information like sound clips, videos files, etc. upto 4 GB.
It stores the location of large objects, The DBMS _LOB package can be used to manipulate
LOB

SQL Data Types


An SQL developer must be aware of what type of data will be stored inside each column while
creating a table. The data type guideline for SQL is to understand what type of data is expected
inside each column and it also identifies how SQL will interact with the stored data.
For every database, data types are primarily classified into three categories.
● Numeric Data types
● Date and Time Database
● String Database
Like in other programming languages, SQL also has certain data types available. A brief idea of all
the data types is discussed below.

Numeric Data Types in MYSQL: Exact Numeric Data type


There are nine subtypes which are given below in the table. The table contains the range of data
in a particular type.
Data Type From To

BigInt -263 (-9,223,372,036,854,775,808) 263 -1 (9,223,372,036,854,775,807)

Int -231 (-2,147,483,648) 231-1 (2,147,483,647)


smallint -215 (-32,768) 215-1 (32,767)

tinyint 0 28-1 (255)

bit 0 1

decimal -1038+1 1038-1

numeric -1038+1 1038-1

money -922,337,203,685,477.5808 922,337,203,685,477.5807

Small money -214,748.3648 214,748.3647

Approximate Numeric Data type


The subtypes of this data type are given in the table with the range.
Data Type From To

Float -1.79E+308 1.79E+308

Real -3.40E+38 3.40E+38

String Data Types in MYSQL: Character String Data type


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 231 characters(SQL Server 2005 only).(Variable


varchar(max)
Length non-Unicode data)

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


text
Unicode data)

Unicode Character String Data type


The details are given in below table –
Data Type Description

nchar The maximum length of 4000 characters(Fixed-Length Unicode Characters)


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

The maximum length of 231 characters(SQL Server 2005 only).(Variable


nvarchar(max)
Length Unicode data)

Server String Data Type in SQL


There are four subtypes of this data type which are given below:
Data types Description

Binary The maximum length of 8000 bytes(Fixed-Length binary data)

varbinary The maximum length of 8000 bytes(Variable Length binary data)

The maximum length of 231 bytes(SQL Server 2005 only).(Variable Length


varbinary(max)
binary data)

text Maximum Length of 2,147,483,647 bytes(Variable Length binary data)

Server Date and Time Data Type in SQL


The details are given in the below table.
Data Type Description

DATE A data type is used to store the data of date in a record

TIME A data type is used to store the data of time in a record

DATETIME A data type is used to store both the data, date, and time in the record.

SQL Constraints

A constraint refers to a condition or check that is applied on a column or a table to maintain data
integrity and helps in inserting valid values for a column. SQL constraints are used to specify rules
for data in a table.Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE statement. Constraints are
used to limit the type of data that can go into a table. This ensures the accuracy and reliability of
the data in the table. If there is any violation between the constraint and the data action, the action
is aborted. Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.

Syntax: CREATE TABLE table_name (column1 datatype constraint,column2


datatype constraint,column3 datatype constraint,....);

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
SQL NOT NULL Constraint:
The SQL NOT NULL forces particular values or records should not to hold a null value. It is
somewhat similar to the primary key condition as the primary key can’t have null values in the
table although both are completely different things.
In SQL, constraints are some set of rules that are applied to the data type of the specified table,
Or we can say that using constraints we can apply limits on the type of data that can be stored in
the particular column of the table.
Constraints are typically placed specified along with CREATE statement. By default, a column
can hold null values.
Query:
CREATE TABLE Emp(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Salary int(10)
);
Output:

If you don’t want to have a null column or a null value you need to define constraintslike NOT
NULL. NOT NULL constraints make sure that a column does not hold null values, or in other
words, NOT NULL constraints make sure that you cannot insert a new record or update a record
without entering a value to the specified column(i.e., NOT NULL column).

Unique constraint in SQL is used to check whether the sub-query has duplicate tuples in its
result. It returns a Boolean value indicating the presence/absence of duplicate tuples. Unique
construct returns true only if the subquery has no duplicate tuples, else it returns false.
Syntax:
CREATE TABLE table_name (column1 datatype UNIQUE, column2 datatype,…);
It means that in that particular column, the data should be unique.We can directly calculate the
unique data in the column without using unique data words in SQL but the UNIQUE keyword
ease the complexity.Suppose that we have one table in which we have to calculate the unique
data in the ID column.
Query:
SELECT table.IDFROMtableWHERE UNIQUE (SELECT table2.IDFROM table2WHERE table.ID
= table2.ID);
SQL Unique Constraint on ALTER Table
We can add a unique column in a table using ALTER.Suppose that we have one table with the
named instructor and we want to insert one unique column in the instructor.
Syntax:
ALTER TABLE Instructor ADD UNIQUE(ID);
To DROP a Unique Constraint
Suppose we have to DROP that column, particularly in the table.
Syntax:
ALTER TABLE InstructorDROP INDEX ID;

The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will
be added to all new records when no other value is provided.
Syntax
CREATE TABLE tablename (Columnname DEFAULT ‘defaultvalue’);
Using DEFAULT on CREATE TABLE
To set a DEFAULT value for the “Location” column when the “Geeks” table is created.
Query:
CREATE TABLE Geeks (ID int NOT NULL, Name varchar(255),Age int,Location varchar(255)
DEFAULT 'Noida');
INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi');
INSERT INTO Geeks VALUES (5, 'Hema', 27,DEFAULT);
INSERT INTO Geeks VALUES (6, 'Neha', 25, 'Delhi');
INSERT INTO Geeks VALUES (7, 'Khushi', 26,DEFAULT);
Select * from Geeks;
Output:

DROP a DEFAULT Constraint


Syntax
ALTER TABLE tablenameALTER COLUMN columnname DROP DEFAULT;
Query:
ALTER TABLE GeeksALTER COLUMN LocationDROP DEFAULT;
Let us add 2 new rows in the Geeks table:
Query:
INSERT INTO Geeks VALUES (8, 'Komal', 24, 'Delhi');
INSERT INTO Geeks VALUES (9, 'Payal', 26,NULL);

Foreign Key is a column that refers to the primary key/unique key of other table. So it
demonstrates relationship between tables and act as cross reference among them. Table in
which foreign key is defined is called Foreign table/Referencing table. Table that defines
primary/unique key and is referenced by foreign key is called primary table/master table/
Referenced Table. It is Defined in Create table/Alter table statement.
For the table that contains Foreign key, it should match the primary key in referenced table for
every row. This is called Referential Integrity. Foreign key ensures referential integrity.
Properties:
 Parent that is being referenced has to be unique/Primary Key.
 Child may have duplicates and nulls.
 Parent record can be deleted if no child exists.
 Master table cannot be updated if child exists.
 Must reference PRIMARY KEY in primary table.
 Foreign key column and constraint column should have matching data types.
 Records cannot be inserted in child table if corresponding record in master table do not
exist.
 Records of master table cannot be deleted if corresponding records in child table exits.
1. SQL Foreign key At column level :
Syntax –
Create table people (no int references person, Fname varchar2(20));
OR
Create table people (no int references person(id), Fname varchar2(20));
Here Person table should have primary key with type int. If there is single columnar Primary key
in table, column name in syntax can be omitted. So both the above syntax works correctly.
To check the constraint,
 If Parent table doesn’t have primary key.
 OUTPUT :
 Error at line 1 : referenced table does not have a primary key.
 If Parent table has Primary Key of different datatype.
 OUTPUT :
 Error at line 1 : column type incompatible with referenced column type.
2. SQL Foreign key At table level :
Syntax –
create table people(no varchar2(10),fname varchar2(20), foreign key(no) references person);
OR
create table people(no varchar2(10), fname varchar2(20), foreign key(no) references person(id));
Column name of referenced table can be ignored.

Check Constraint is used to specify a predicate that every tuple must satisfy in a given relation.
It limits the values that a column can hold in a relation.
 The predicate in check constraint can hold a sub query.
 Check constraint defined on an attribute restricts the range of values for that attribute.
 If the value being added to an attribute of a tuple violates the check constraint, the check
constraint evaluates to false and the corresponding update is aborted.
 Check constraint is generally specified with the CREATE TABLE command in SQL.
Syntax:
CREATE TABLE pets(ID INT NOT NULL,Name VARCHAR(30) NOT NULL,Breed
VARCHAR(20) NOT NULL,Age INT,GENDER VARCHAR(9),PRIMARY
KEY(ID),check(GENDER in ('Male', 'Female', 'Unknown')));
Note: The check constraint in the above SQL command restricts the GENDER to belong to only
the categories specified. If a new tuple is added or an existing tuple in the relation is updated
with a GENDER that doesn’t belong to any of the three categories mentioned, then the
corresponding database update is aborted.
Query: Constraint: Only students with age >= 17 are can enroll themselves in a
CREATE TABLE student (Student_ID INT NOT NULL,Name VARCHAR(30) NOT NULL,Age INT
NOT NULL,GENDER VARCHAR(9),PRIMARY KEY(ID),check(Age >= 17));
Student relation:
Ag
StudentID Name e Gender
1001 Ron 18 Male
1002 Sam 17 Male
1003 Georgia 17 Female
1004 Erik 19 Unknown
1005 Christine 17 Female

A primary key constraint depicts a key comprising one or more columns that will help uniquely
identify every tuple/record in a table.
Properties:
1. No duplicate values are allowed, i.e. Column assigned as primary key should have
UNIQUE values only.
2. NO NULL values are present in column with Primary key. Hence there is Mandatory value
in column having Primary key.
3. Only one primary key per table existalthough Primary key may have multiple columns.
4. No new row can be inserted with the already existing primary key.
5. Classified as: a) Simple primary key that has a Single column 2) Composite primary key
has Multiple column.
6. Defined in Create table / Alter table statement.
The primary key can be created in a table using PRIMARY KEY constraint. It can be created at
two levels.
1. Column
2. Table.
SQL PRIMARY KEY at Column Level:
If Primary key contains just one column, it should be defined at column level. The following code
creates the Primary key “ID” on the person table.
Syntax:
Create Table Person
(
Id int NOT NULL PRIMARY KEY,
Name varchar2(20),
Address varchar2(50)
);
Here NOT NULL is added to make sure ID should have unique values. SQL will automatically
set null values to the primary key if it is not specified.
Example-1:
To verify the working of Primary key:
Insert into Person values(1, 'Ajay', 'Mumbai');
Output:
1 row created
Example-2:
Let’s see if you will insert the same values again.
Insert into Person values(1, 'Ajay', 'Mumbai');
Output:
Error at line 1: unique constraint violated
Since we are inserting duplicate values, an error will be thrown since the Primary key “Id” can
contain only unique values.
Example-3:
Insert into Person values('', 'Ajay', 'Mumbai');
Output:
Error at line 1: cannot insert Null into<"user"."Person"."ID">
Primary Key cannot contain Null Values so That too will throw an error.

SQL Sub Languages: SQL commands are like instructions to a table. 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.
These SQL commands are mainly categorized into five categories:
1. DDL – Data Definition Language
1. DQL – Data Query Language
1. DML – Data Manipulation Language
1. DCL – Data Control Language
1. TCL – Transaction Control Language
DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. It simply deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database. DDL is a set of SQL commands used to create, modify, and
delete database structures but not data. These commands are normally not used by a general user, who
should be accessing the database via an application.

Here are some key features of Structured Query Language (SQL):


1. Data Definition Language (DDL): SQL provides a set of commands to define and modify the
structure of a database, including creating tables, modifying table structure, and dropping tables.
2. Data Manipulation Language (DML): SQL provides a set of commands to manipulate data within a
database, including adding, modifying, and deleting data.
3. Query Language: SQL provides a rich set of commands for querying a database to retrieve data,
including the ability to filter, sort, group, and join data from multiple tables.
4. Transaction Control: SQL supports transaction processing, which allows users to group a set of
database operations into a single transaction that can be rolled back in case of failure.
5. Data Integrity: SQL includes features to enforce data integrity, such as the ability to specify
constraints on the values that can be inserted or updated in a table, and to enforce referential integrity
between tables.
6. User Access Control: SQL provides mechanisms to control user access to a database, including the
ability to grant and revoke privileges to perform certain operations on the database.
7. Portability: SQL is a standardized language, meaning that SQL code written for one database
management system can be used on another system with minimal modification.

List of DDL commands:


 CREATE: This command is used to create the database or its objects (like table, index, function,
views, store procedure, and triggers).
*sql>Create table emp (emp_no number (3) primary key, emp_name varchar (15), emp_address
varchar (15));

 DROP: This command is used to delete objects from the database.


*sql>Drop table emp;

 ALTER: This is used to alter the structure of the database.


*sql>Alter table emp Add (emp_age number (1));
*sql>Alter table emp Modify (emp_age number (2));
 TRUNCATE: This is used to remove all records from a table, including all spaces allocated for the
records are removed.
*sql>Truncate table emp;

 COMMENT: This is used to add comments to the data dictionary.


*sql>Desc emp; --Describe the structure of emp table

 RENAME: This is used to rename an object existing in the database.


*sql>Rename emp to emp1;

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. We can define DQL as follows it
is a component of SQL statement that allows getting data from the database and imposing order upon it. It
includes the SELECT statement. 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 i.e. a front-end.
List of DQL:
 SELECT: It is used to retrieve data from the database.
*sql>Select * from emp1;
*sql>Select * from emp1 WHERE emp_no=1;

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.
List of DML commands:
 INSERT: It is used to insert data into a table.
*sql>Insert into emp1 (emp_no, emp_name, emp_address, emp_age) values (1, ‘Ankit Patil’, ‘Shanti
Nagar’, 18);
*sql>Insert into emp1 values (1, ‘Ankit Patil’, ‘Shanti Nagar’, 18);

 UPDATE: It is used to update existing data within a table.


*sql>Update emp1 SET emp_no = emp_no + 1;
*sql>Update emp1 SET emp_name=’Ankita’ WHERE emp_name=’Ankit Patil’;

 DELETE: It is used to delete records from a database table.


*sql>Delete from emp1 WHERE emp_no = 1;
*sql>Delete from emp1; OR *sql>Delete emp1;

 LOCK: Table control concurrency.


 CALL: Call a PL/SQL or JAVA subprogram.

DCL (Data Control Language)


DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions,
and other controls of the database system.
List of DCL commands:

GRANT: This command gives users access privileges to the database.


Syntax:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
*sql>Grant select, insert on emp to Akhil;
REVOKE: This command withdraws the user’s access privileges given by using the GRANT command.
Syntax:
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
*sql>Revoke insert on emp from Akhil;

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.

COMMIT: Commits a Transaction. (Saving all DML operations permanently)


Syntax:
COMMIT;

ROLLBACK: Rollbacks a transaction in case of any error occurs. (To undo all DML operations up to last
save)
Syntax:
ROLLBACK;

SAVEPOINT: Sets a save point within a transaction.


Syntax:
SAVEPOINT SAVEPOINT_NAME;

Example: Create table blood and insert 3 records and delete one record. Set a Save point after every
insertion and deletion of a record into the table. At the end, view the result of each rollback up to Save Point.

SQL>Create table blood (dno number (4), dname varchar (10));


SQL>Insert into blood values (110, ‘RAM’);
SQL>SAVEPOINT A;
SQL>Insert into blood values (111, ‘RAMU’);
SQL> SAVEPOINT B;
SQL>Insert into blood values (112, ‘RAMOJI’);
SQL> SAVEPOINT C;
SQL>Select * from blood;
110 RAM
111 RAMU
112 RAMOJI
SQL>Delete from blood where dno=110;
SQL>SAVEPOINT D;
SQL>Select * from blood;
111 RAMU
112 RAMOJI
SQL>ROLLBACK TO C;
SQL>Select * from blood;
110 RAM
111 RAMU
112 RAMOJI
SQL>ROLLBACK TO A;
SQL>Select * from blood;
110 RAM
Aggregate Functions:
Aggregate functions are used to perform calculations on a set of values and return a single result. Some of
the most commonly used aggregate functions in SQL include −
 COUNT() - Returns the number of rows in a table or the number of non-NULL values in a column
 SUM() - Returns the sum of all non-NULL values in a column
 AVG() - Returns the average of all non-NULL values in a column
 MIN() - Returns the minimum value in a column
 MAX() - Returns the maximum value in a column
Here's an example of using the COUNT() function to find the number of rows in a table called "orders" −
SELECTCOUNT(*)FROM orders;
And here's an example of using the SUM() function to find the total cost of all orders in the table −
SELECTSUM(total_cost)FROM orders;

Logical Functions:
SQL provides a set of logical functions that return a Boolean value, which can be either true or false. Some
examples of logical functions in SQL include −
 AND - Returns true if both the conditions are true
 OR - Returns true if at least one of the conditions is true
 NOT - Negates a Boolean value
Here's an example of using the AND function to find all customers who live in a specific city and have an
account balance greater than a certain amount −
SELECT customer_name, city, account_balance
FROM customers
WHERE city ='New York' AND account_balance>1000;

SQL Clauses
o SQL clause helps us to retrieve a set or bundles of records from the table.
o SQL clause helps us to specify a condition on the columns or the records of a table.
Different clauses available in the Structured Query Language are as follows:
1. WHERE CLAUSE
2. GROUP BY CLAUSE
3. HAVING CLAUSE
4. ORDER BY CLAUSE
Let's see each clause one by one with an example.

1. WHERE CLAUSE
A WHERE clause in SQL is used with the SELECT query, which is one of the data manipulation language
commands. WHERE clauses can be used to limit the number of rows to be displayed in the result set, it
generally helps in filtering the records. It returns only those queries which fulfill the specific conditions of
the WHERE clause. WHERE clause is used in SELECT, UPDATE, DELETE statement, etc.
WHERE clause with SELECT Query
Asterisk symbol is used with a WHERE clause in a SELECT query to retrieve all the column values for
every record from a table.
Syntax of where clause with a select query to retrieve all the column values for every record from a
table:
SELECT * FROM TABLENAME WHERE CONDITION;
If according to the requirement, we only want to retrieve selective columns, then we will use below
syntax:
SELECT COLUMNNAME1, COLUMNNAME2 FROM TABLENAME WHERE CONDITION;
Consider the employee table with the following data:

Date_of_Joi
E_ID Name Salary City Designation Age
ning
1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24

2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23

3 Anuja Sharma 40000 Jaipur Manager 2021-08-15 26

4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24

5 Rucha Jagtap 45000 Bangalore Project Manager 2020-08-09 23

6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26

7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24

8 Sana Sheik 45000 Pune Software Engineer 2020-09-10 26

9 Swati Kumari 50000 Pune Software Tester 2021-01-01 25

10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24

11 Simran Khanna 45500 Kolhapur HR 2019-01-02 26

12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25

13 Kiran Maheshwari 50000 Nashik HR 2013-12-12 23

14 Tejal Jain 40000 Delhi Project Manager 2017-11-10 25

15 Mohini Shah 38000 Pune Software Developer 2019-03-05 20


Example 1:
Write a query to retrieve all those records of an employee where employee salary is greater than 50000.
Query: sql> SELECT * FROM employees WHERE Salary > 50000;
The above query will display all those records of an employee where an employee's salary is greater than
50000. Below 50000 Salary will not be displayed as per the conditions.
You will get the following output:

As per the expected output, only those records are displayed where an employee's salary is greater than
50000. There are six records in the employee's table which satisfy the given condition.

2. GROUP BY CLAUSE
The Group By clause is used to arrange similar kinds of records into the groups in the Structured Query
Language. The Group by clause in the Structured Query Language is used with Select Statement. Group by
clause is placed after the where clause in the SQL statement. The Group By clause is specially used with the
aggregate function, i.e., max (), min (), avg (), sum (), count () to group the result based on one or more than
one column.
The syntax of Group By clause:
SELECT * FROM TABLENAME GROUP BY COLUMNNAME;
The above syntax will select all the data or records from the table, but it will arrange all those data or records
in the groups based on the column name given in the query.
The syntax of Group By clause with Aggregate Functions:
SELECT COLUMNNAME1, Aggregate_FUNCTION (COLUMNNAME) FROM TABLENAME GROUP
BY COLUMNNAME;
Let's understand the Group By clause with the help of examples.
Consider the employees table with the following data:

E_ID Name Salary City Designation Date_of_Joining Age

1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24

2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23

3 Anuja Sharma 40000 Jaipur Manager 2021-08-15 26

4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24

5 Rucha Jagtap 45000 Bangalore Project Manager 2020-08-09 23

6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26

7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24

8 Sana Sheik 45000 Pune Software Engineer 2020-09-10 26

9 Swati Kumari 50000 Pune Software Tester 2021-01-01 25

10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24

11 Simran Khanna 45500 Kolhapur HR 2019-01-02 26

12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25

13 Kiran Maheshwari 50000 Nashik HR 2013-12-12 23

14 Tejal Jain 40000 Delhi Project Manager 2017-11-10 25

15 Mohini Shah 38000 Pune Software Developer 2019-03-05 20


Example 1:
Write a query to display all the records of the employees table but group the results based on the age
column.
Query:
mysql> SELECT * FROM employees GROUP BY Age;
The above query will display all the records of the employees table but grouped by the age column.
You will get the following output:

Examples of Group By clause using aggregate functions


Example 1:
Write a query to list the number of employees working on a particular designation and group the results by
designation of the employee.
Query:
mysql> SELECT COUNT (E_ID) AS Number_of_Employees, Designation FROM employees GROUP BY
Designation;
The above query will display the designation with the respective number of employees working on that
designation. All these results will be grouped by the designation column.
You will get the following output:

As per the expected output, the designation with the respective employee count is displayed.

3. HAVING CLAUSE:
When we need to place any conditions on the table's column, we use the WHERE clause in SQL. But if we
want to use any condition on a column in Group By clause at that time, we will use the HAVING clause
with the Group By clause for column conditions.
Syntax: TABLENAME GROUP BY COLUMNNAME HAVING CONDITION;
Consider the employees table with the following data:

E_ID Name Salary City Designation Date_of_Joining Age

1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24

2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23

3 Anuja Sharma 40000 Jaipur Manager 2021-08-15 26

4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24


5 Rucha Jagtap 45000 Bangalore Project Manager 2020-08-09 23

6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26

7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24

8 Sana Sheik 45000 Pune Software Engineer 2020-09-10 26

9 Swati Kumari 50000 Pune Software Tester 2021-01-01 25

10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24

11 Simran Khanna 45500 Kolhapur HR 2019-01-02 26

12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25

13 Kiran Maheshwari 50000 Nashik HR 2013-12-12 23

14 Tejal Jain 40000 Delhi Project Manager 2017-11-10 25

15 Mohini Shah 38000 Pune Software Developer 2019-03-05 20


Example 1:
Write a query to display the name of employees, salary, and city where the employee's maximum salary is
greater than 40000 and group the results by designation.
Query:
mysql> SELECT Name, City, MAX (Salary) AS Salary FROM employees GROUP BY Designation HAVI
NG MAX (Salary) > 40000;
You will get the following output:

The above output shows that the employee name, salary, and city of an employee where employee salary is
greater than 40000 grouped by designation. (Employees with a similar designation are placed in one group,
and those with other designation are placed separately).

4. ORDER BY CLAUSE
Whenever we want to sort anything in SQL, we use the ORDER BY clause. The ORDER BY clause in SQL
will help us to sort the data based on the specific column of a table. This means that all the data stored in the
specific column on which we are executing the ORDER BY clause will be sorted. The corresponding
column values will be displayed in the sequence in which we have obtained the values in the earlier step.
As we all know, sorting means either in ASCENDING ORDER or DESCENDING ORDER. In the same
way, ORDER BY CLAUSE sorts the data in ascending or descending order as per our requirement. The data
will be sorted in ascending order whenever the ASC keyword is used with ORDER by clause, and
the DESC keyword will sort the records in descending order.
By default, sorting in the SQL will be done using the ORDER BY clause in ASCENDING order if we didn't
mention the sorting order.
Before moving towards the example of the ORDER BY clause to sort the records, first, we will look at
syntax so it will be easy for us to go through the example.
Syntax of ORDER BY clause without asc and desc keyword:
SELECT COLUMN_NAME1, COLUMN_NAME2 FROM TABLE_NAME ORDER BY COLUMNAME;

Syntax of ORDER BY clause to sort in ascending order:


SELECT COLUMN_NAME1, COLUMN_NAME2 FROM TABLE_NAME ORDER BY COLUMN_NA
ME ASC;
Syntax of ORDER BY clause to sort in descending order:
SELECT COLUMN_NAME1, COLUMN_NAME2 FROM TABLE_NAME ORDER BY COLUMN_NA
ME DESC;
Consider we have an employees table with the following data:

Date_of_J
E_ID Name Salary City Designation Age
oining

1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24

2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23

3 Anuja Sharma 40000 Jaipur Manager 2021-08-15 26

4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24

5 Rucha Jagtap 45000 Bangalore Project Manager 2020-08-09 23

6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26

7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24

8 Sana Sheik 45000 Pune Software Engineer 2020-09-10 26

9 Swati Kumari 50000 Pune Software Tester 2021-01-01 25

10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24

11 Simran Khanna 45500 Kolhapur HR 2019-01-02 26

12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25

13 Kiran Maheshwari 50000 Nashik HR 2013-12-12 23

14 Tejal Jain 40000 Delhi Project Manager 2017-11-10 25

15 Mohini Shah 38000 Pune Software Developer 2019-03-05 20


Example 1:
Write a query to sort the records in the ascending order of the employee designation from the employees
table.
Query:mysql> SELECT * FROM employees ORDER BY Designation;
Here in a SELECT query, an ORDER BY clause is applied on the column 'Designation' to sort the records,
but we didn't use the ASC keyword after the ORDER BY clause to sort in ascending order. So, by default,
data will be sorted in ascending order if we don't specify asc keyword.You will get the following output:

As per the expected output, the records are displayed in ascending order of the employee's designation.

SQL Arithmetic Operators


The Arithmetic Operators perform the mathematical operation on the numerical data of the SQL tables.
These operators perform addition, subtraction, multiplication, and division operations on the numerical
operands.
Following are the various arithmetic operators performed on the SQL data:
1. SQL Addition Operator (+)
2. SQL Subtraction Operator (-)
3. SQL Multiplication Operator (+)
4. SQL Division Operator (-)
5. SQL Modulus Operator (+)

SQL Addition Operator (+): The Addition Operator in SQL performs the addition on the numerical data of
the database table. In SQL, we can easily add the numerical values of two columns of the same table by
specifying both the column names as the first and second operand. We can also add the numbers to the
existing numbers of the specific column.
Syntax of SQL Addition Operator:
1. SELECT operand1 + operand2;
Let's understand the below example which explains how to execute Addition Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Emp Monthly bonus

101 Tushar 25000 4000

102 Anuj 30000 200


o Suppose, we want to add 20,000 to the salary of each employee specified in the table. Then, we have to
write the following query in the SQL:
1. SELECT Emp_Salary + 20000 as Emp_New_Salary FROM Employee_details;
In this query, we have performed the SQL addition operation on the single column of the given table.
o Suppose, we want to add the Salary and monthly bonus columns of the above table, then we have to
write the following query in SQL:
1. SELECT Emp_Salary + Emp_Monthlybonus as Emp_Total_Salary FROM Employee_details;
In this query, we have added two columns with each other of the above table.

SQL Subtraction Operator (-): The Subtraction Operator in SQL performs the subtraction on the numerical
data of the database table. In SQL, we can easily subtract the numerical values of two columns of the same
table by specifying both the column names as the first and second operand. We can also subtract the number
from the existing number of the specific table column.
Syntax of SQL Subtraction Operator:
1. SELECT operand1 - operand2;
Let's understand the below example which explains how to execute Subtraction Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Penalty

201 Abhay 25000 200

202 Sumit 30000 500


o Suppose we want to subtract 5,000 from the salary of each employee given in
the Employee_details table. Then, we have to write the following query in the SQL:
1. SELECT Emp_Salary - 5000 as Emp_New_Salary FROM Employee_details;
In this query, we have performed the SQL subtraction operation on the single column of the given table.
o If we want to subtract the penalty from the salary of each employee, then we have to write the
following query in SQL:
1. SELECT Emp_Salary - Penalty as Emp_Total_Salary FROM Employee_details;

SQL Multiplication Operator (*): The Multiplication Operator in SQL performs the Multiplication on the
numerical data of the database table. In SQL, we can easily multiply the numerical values of two columns of
the same table by specifying both the column names as the first and second operand.
Syntax of SQL Multiplication Operator:
1. SELECT operand1 * operand2;
Let's understand the below example which explains how to execute Multiplication Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Penalty

201 Abhay 25000 200

202 Sumit 30000 500


o Suppose, we want to double the salary of each employee given in the Employee_details table. Then,
we have to write the following query in the SQL:
1. SELECT Emp_Salary * 2 as Emp_New_Salary FROM Employee_details;
In this query, we have performed the SQL multiplication operation on the single column of the given table.
o If we want to multiply the Emp_Id column to Emp_Salary column of that employee
whose Emp_Id is 202, then we have to write the following query in SQL:
1.

SELECT Emp_Id * Emp_Salary as Emp_Id * Emp_Salary FROM Employee_details WHERE Emp_


Id = 202;
In this query, we have multiplied the values of two columns by using the WHERE clause.
SQL Division Operator (/): The Division Operator in SQL divides the operand on the left side by the
operand on the right side.
Syntax of SQL Division Operator:
1. 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.
Let's understand the below example which explains how to execute Division Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 25000

202 Sumit 30000


o Suppose, we want to half the salary of each employee given in the Employee_details table. For this
operation, we have to write the following query in the SQL:
1. SELECT Emp_Salary / 2 as Emp_New_Salary FROM Employee_details;
In this query, we have performed the SQL division operation on the single column of the given table.

SQL Modulus Operator (%): The Modulus Operator in SQL provides the remainder when the operand on
the left side is divided by the operand on the right side.
Syntax of SQL Modulus Operator:
1. SELECT operand1 % operand2;
Let's understand the below example which explains how to execute Modulus Operator in SQL query:
This example consists of a Division table, which has three columns Number, First_operand, and
Second_operand.
Number First operand Second operand

1 56 4

2 32 8

3 89 9

4 18 10

5 10 5
o If we want to get the remainder by dividing the numbers of First_operand column by the numbers of
Second_operand column, then we have to write the following query in SQL:
1. SELECT First_operand % Second_operand as Remainder FROM Employee_details;

SQL Comparison Operators


The Comparison Operators in SQL compare two different data of SQL table and check whether they are the
same, greater, and lesser. The SQL comparison operators are used with the WHERE clause in the SQL
queries
Following are the various comparison operators which are performed on the data stored in the SQL database
tables:
1. SQL Equal Operator (=)
2. SQL Not Equal Operator (!=)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)
5. SQL Less Than Operator (<)\
6. SQL Less Than Equals to Operator (<=)

SQL Equal Operator (=): This operator is highly used in SQL queries. The Equal Operator in SQL shows
only data that matches the specified value in the query.
This operator returns TRUE records from the database table if the value of both operands specified in the
query is matched.
Let's understand the below example which explains how to execute Equal Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 30000

202 Ankit 40000

203 Bheem 30000

204 Ram 29000

205 Sumit 30000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose salary is 30000. Then, we have to write the following query in the SQL database:
1. SELECT * FROM Employee_details WHERE Emp_Salary = 30000;
In this example, we used the SQL equal operator with WHERE clause for getting the records of those
employees whose salary is 30000.

SQL Equal Not Operator (!=): The Equal Not Operator in SQL shows only those data that do not match the
query's specified value.
This operator returns those records or rows from the database views and tables if the value of both operands
specified in the query is not matched with each other.
Let's understand the below example which explains how to execute Equal Not Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose salary is not 45000. Then, we have to write the following query in the SQL database:
1. SELECT * FROM Employee_details WHERE Emp_Salary != 45000;
In this example, we used the SQL equal not operator with WHERE clause for getting the records of those
employees whose salary is not 45000.

SQL Greater Than Operator (>): The Greater Than Operator in SQL shows only those data which are greater
than the value of the right-hand operand.
Let's understand the below example which explains how to execute Greater ThanOperator (>) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose employee id is greater than 202. Then, we have to write the following query in the SQL
database:
1. SELECT * FROM Employee_details WHERE Emp_Id > 202;
Here, SQL greater than operator displays the records of those employees from the above table whose
Employee Id is greater than 202.

SQL Greater Than Equals to Operator (>=): The Greater Than Equals to Operator in SQL shows those data
from the table which are greater than and equal to the value of the right-hand operand.
Let's understand the below example which explains how to execute greater than equals to the operator (>=)
in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose employee id is greater than and equals to 202. For this, we have to write the following query
in the SQL database:
1. SELECT * FROM Employee_details WHERE Emp_Id >= 202;
Here,SQL greater than equals to operator' with WHERE clause displays the rows of those employees from
the table whose Employee Id is greater than and equals to 202.

SQL Less Than Operator (<): The Less Than Operator in SQL shows only those data from the database
tables which are less than the value of the right-side operand.
This comparison operator checks that the left side operand is lesser than the right-side operand. If the
condition becomes true, then this operator in SQL displays the data which is less than the value of the right-
side operand.
Let's understand the below example which explains how to execute less than operator (<) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose employee id is less than 204. For this, we have to write the following query in the SQL
database:
1. SELECT * FROM Employee_details WHERE Emp_Id < 204;
Here,SQL less than operator with WHERE clause displays the records of those employees from the above
table whose Employee Id is less than 204.

SQL Less Than Equals to Operator (<=): The Less Than Equals to Operator in SQL shows those data from
the table which are lesser and equal to the value of the right-side operand.
This comparison operator checks that the left side operand is lesser and equal to the right side operand.
Let's understand the below example which explains how to execute less than equals to the operator (<=) in
SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary

201 Abhay 45000

202 Ankit 45000

203 Bheem 30000

204 Ram 29000

205 Sumit 29000


o Suppose, we want to access all the records of those employees from the Employee_details table
whose employee id is less and equals 203. For this, we have to write the following query in the SQL
database:
1. SELECT * FROM Employee_details WHERE Emp_Id <= 203;
Here, SQL less than equals to the operator with WHERE clause displays the rows of those employees from
the table whose Employee Id is less than and equals 202.

SQL Logical Operators


The Logical Operators in SQL perform the Boolean operations, which give two results True and
False. These operators provide True value if both operands match the logical condition.
Following are the various logical operators which are performed on the data stored in the SQL database
tables:
1. SQL ALL operator
2. SQL AND operator
3. SQL OR operator
4. SQL BETWEEN operator
5. SQL IN operator
6. SQL NOT operator
7. SQL ANY operator
8. SQL LIKE operator

SQL ALL Operator: The ALL operator in SQL compares the specified value to all the values of a column
from the sub-query in the SQL database.
This operator is always used with the following statement:
1. SELECT,
2. HAVING, and
3. WHERE.
Syntax of ALL operator:
1.

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


perator ALL (SELECT column FROM tablename2)
Let's understand the below example which explains how to execute ALL logical operators in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Gurgaon

202 Ankit 45000 Delhi

203 Bheem 30000 Jaipur

204 Ram 29000 Mumbai

205 Sumit 40000 Kolkata


o If we want to access the employee id and employee names of those employees from the table whose
salaries are greater than the salary of employees who lives in Jaipur city, then we have to type the
following query in SQL.
1.

SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salary > ALL ( SELECT E
mp_Salary FROM Employee_details WHERE Emp_City = Jaipur)
Here, we used the SQL ALL operator with greater than the operator.

SQL AND Operator: The AND operator in SQL would show the record from the database table if all the
conditions separated by the AND operator evaluated to True. It is also known as the conjunctive operator
and is used with the WHERE clause.
Syntax of AND operator:
1.

SELECT column1, ...., columnN FROM table_Name WHERE condition1 AND condition2 AND co
ndition3 AND ....... AND conditionN;
Let's understand the below example which explains how to execute AND logical operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi


204 Ram 25000 Delhi

205 Sumit 40000 Kolkata


o Suppose, we want to access all the records of those employees from the Employee_details table
whose salary is 25000 and the city is Delhi. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR Emp_City = 'Delhi';
Here, SQL AND operator with WHERE clause shows the record of employees whose salary is 25000 and
the city is Delhi.

SQL OR Operator: The OR operator in SQL shows the record from the table if any of the conditions
separated by the OR operator evaluates to True. It is also known as the conjunctive operator and is used with
the WHERE clause.
Syntax of OR operator:
1.

SELECT column1, ...., columnN FROM table_Name WHERE condition1 OR condition2 OR conditi
on3 OR ....... OR conditionN;
Let's understand the below example which explains how to execute OR logical operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata


o If we want to access all the records of those employees from the Employee_details table whose
salary is 25000 or the city is Delhi. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR Emp_City = 'Delhi';
Here, SQL OR operator with WHERE clause shows the record of employees whose salary is 25000 or the
city is Delhi.

SQL BETWEEN Operator: The BETWEEN operator in SQL shows the record within the range mentioned
in the SQL query. This operator operates on the numbers, characters, and date/time operands.
If there is no value in the given range, then this operator shows NULL value.
Syntax of BETWEEN operator:
1.

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


n_nameBETWEEN value1 and value2;
Let's understand the below example which explains how to execute BETWEEN logical operator in SQL
query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi


202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata


o Suppose, we want to access all the information of those employees from the Employee_details table
who is having salaries between 20000 and 40000. For this, we have to write the following query in
SQL:
1. SELECT * FROM Employee_details WHERE Emp_Salary BETWEEN 30000 AND 45000;
Here, we used the SQL BETWEEN operator with the Emp_Salary field.

SQL IN Operator: The IN operator in SQL allows database users to specify two or more values in a
WHERE clause. This logical operator minimizes the requirement of multiple OR conditions.
This operator makes the query easier to learn and understand. This operator returns those rows whose values
match with any value of the given list.
Syntax of IN operator:
1.

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


n_name IN (list_of_values);
Let's understand the below example which explains how to execute IN logical operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata


o Suppose, we want to show all the information of those employees from the Employee_details table
whose Employee Id is 202, 204, and 205. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Id IN (202, 204, 205);
Here, we used the SQL IN operator with the Emp_Id column.
o Suppose, we want to show all the information of those employees from the Employee_details table
whose Employee Id is not equal to 202 and 205. For this, we have to write the following query in
SQL:
1. SELECT * FROM Employee_details WHERE Emp_Id NOT IN (202,205);
Here, we used the SQL NOT IN operator with the Emp_Id column.

SQL NOT Operator: The NOT operator in SQL shows the record from the table if the condition evaluates to
false. It is always used with the WHERE clause.
Syntax of NOT operator:
1. SELECT column1, column2 ...., columnN FROM table_Name WHERE NOT condition;
Let's understand the below example which explains how to execute NOT logical operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Abhay 25000 Delhi

202 Ankit 45000 Chandigarh

203 Bheem 30000 Delhi

204 Ram 25000 Delhi

205 Sumit 40000 Kolkata


o Suppose, we want to show all the information of those employees from the Employee_details table
whose Cityis not Delhi. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' ;
In this example, we used the SQL NOT operator with the Emp_City column.
o Suppose, we want to show all the information of those employees from the Employee_details table
whose Cityis not Delhi and Chandigarh. For this, we have to write the following query in SQL:
1.

SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' AND NOT Emp_City = 'Ch
andigarh';
In this example, we used the SQL NOT operator with the Emp_City column.

SQL ANY Operator: The ANY operator in SQL shows the records when any of the values returned by the
sub-query meet the condition.
The ANY logical operator must match at least one record in the inner query and must be preceded by any
SQL comparison operator.
Syntax of ANY operator:
1.

SELECT column1, column2 ...., columnN FROM table_Name WHERE column_name comparison_
operator ANY (SELECT column_name FROM table_name WHERE condition(s)) ;

SQL LIKE Operator: The LIKE operator in SQL shows those records from the table which match with the
given pattern specified in the sub-query.
The percentage (%) sign is a wildcard which is used in conjunction with this logical operator.
This operator is used in the WHERE clause with the following three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement
Syntax of LIKE operator:
1.

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


n_name LIKE pattern;
Let's understand the below example which explains how to execute LIKE logical operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Chandigarh


203 Saket 30000 Delhi

204 Abhay 25000 Delhi

205 Sumit 40000 Kolkata


o If we want to show all the information of those employees from the Employee_details whose name
starts with ''s''. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%' ;
In this example, we used the SQL LIKE operator with Emp_Name column because we want to access the
record of those employees whose name starts with s.
o If we want to show all the information of those employees from the Employee_details whose name
ends with ''y''. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Name LIKE '%y' ;
o If we want to show all the information of those employees from the Employee_details whose name
starts with ''S'' and ends with ''y''. For this, we have to write the following query in SQL:
1. SELECT * FROM Employee_details WHERE Emp_Name LIKE 'S%y' ;

SQL Set Operators


The Set Operators in SQL combine a similar type of data from two or more SQL database tables. It mixes
the result, which is extracted from two or more SQL queries, into a single result.
Set operators combine more than one select statement in a single query and return a specific result set.
Following are the various set operators which are performed on the similar data stored in the two SQL
database tables:
1. SQL Union Operator
2. SQL Union ALL Operator
3. SQL Intersect Operator
4. SQL Minus Operator
SQL Union Operator: The SQL Union Operator combines the result of two or more SELECT statements and
provides the single output.
The data type and the number of columns must be the same for each SELECT statement used with the
UNION operator. This operator does not show the duplicate records in the output table.
Syntax of UNION Set operator:
1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions
2. UNION
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute Union operator in Structured Query
Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary, and
Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh


Table: Employee_details1
Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi


205 Ram 30000 Kerala

201 Sanjay 25000 Delhi


Table: Employee_details2
o Suppose, we want to see the employee name and employee id of each employee from both tables in a
single output. For this, we have to write the following query in SQL:
1. SELECT Emp_ID, Emp_Name FROM Employee_details1
2. UNION
3. SELECT Emp_ID, Emp_Name FROM Employee_details2 ;

SQL Union ALL Operator: The SQL Union Operator is the same as the UNION operator, but the only
difference is that it also shows the same record.
Syntax of UNION ALL Set operator:
1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
2. UNION ALL
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];

Let's understand the below example which explains how to execute Union ALL operator in Structured
Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary, and
Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh


Table: Employee_details1
Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi


Table: Employee_details2
o If we want to see the employee name of each employee of both tables in a single output. For this, we
have to write the following query in SQL:
1. SELECT Emp_Name FROM Employee_details1
2. UNION ALL
3. SELECT Emp_Name FROM Employee_details2 ;

SQL Intersect Operator: The SQL Intersect Operator shows the common record from two or more SELECT
statements. The data type and the number of columns must be the same for each SELECT statement used
with the INTERSECT operator.
Syntax of INTERSECT Set operator:
1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
2. INTERSECT
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute INTERSECT operator in Structured
Query Language:

In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary,
and Emp_City.

Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh


Table: Employee_details1
Emp Id Emp Name Emp Salary Emp City

203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi


Table: Employee_details2
Suppose, we want to see a common record of the employee from both the tables in a single output. For this,
we have to write the following query in SQL:
1. SELECT Emp_Name FROM Employee_details1
2. INTERSECT
3. SELECT Emp_Name FROM Employee_details2 ;

SQL Minus Operator: The SQL Minus Operator combines the result of two or more SELECT statements
and shows only the results from the first data set.
Syntax of MINUS operator:
1. SELECT column1, column2 ...., columnN FROM First_tablename [WHERE conditions]
2. MINUS
3. SELECT column1, column2 ...., columnN FROM Second_tablename [WHERE conditions];
Let's understand the below example which explains how to execute INTERSECT operator in Structured
Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary, and
Emp_City.
Emp Id Emp Name Emp Salary Emp City

201 Sanjay 25000 Delhi

202 Ajay 45000 Delhi

203 Saket 30000 Aligarh


Table: Employee_details1
Emp Id Emp Name Emp Salary Emp City
203 Saket 30000 Aligarh

204 Saurabh 40000 Delhi

205 Ram 30000 Kerala

201 Sanjay 25000 Delhi


Table: Employee_details2
Suppose, we want to see the name of employees from the first result set after the combination of both tables.
For this, we have to write the following query in SQL:
1. SELECT Emp_Name FROM Employee_details1
2. MINUS
3. SELECT Emp_Name FROM Employee_details2 ;

SQL Joins
SQL Join statement is used to combine data or rows from two or more tables based on a common field
between them. Different types of Joins are as follows:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
 NATURAL JOIN
Consider the two tables below as follows:
Student

StudentCourse

The simplest Join is INNER JOIN.

A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This
keyword will create the result-set by combining all rows from both the tables where the condition satisfies
i.e. value of the common field will be the same.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

Example Queries (INNER JOIN)


This query will show the names and age of students enrolled in different courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the table on the
right side of the join. For the rows for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

Example Queries (LEFT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join
and matching rows for the table on the left side of the join. For the rows for which there is no matching row
on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.

Example Queries (RIGHT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set
will contain all the rows from both tables. For the rows for which there is no matching, the result-set will
contain NULL values.

Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Example Queries (FULL JOIN):
SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID

HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4
E. Natural join (?)
Natural join can join tables based on the common columns in the tables being joined. A natural join returns
all rows by matching values in common columns having same name and data type of columns and that
column should be present in both tables.
Both tables must have at list one common column with same column name and same data type.
The two table are joined using Cross join.
DBMS will look for a common column with same name and data type Tuples having exactly same values in
common columns are kept in result.
Example:

Department
Employee

Dept_id
Emp_id Dept_name
Emp_name Dept_id

1 10 Ram IT 10

2 30 Jon HR 30

3 40 Bob TIS 50

Query: Find all Employees and their respective departments.


Solution: (Employee) ? (Department)

Emp_id Emp_name Dept_id Dept_id Dept_name

1 Ram 10 10 IT

2 Jon 30 30 HR

Employee data Department data

SQL Subqueries

An SQL Subquery, is a SELECT query within another query. It is also known as Inner query or Nested
query and the query containing it is the outer query. The outer query can contain the SELECT, INSERT,
UPDATE, and DELETE statements. We can use the subquery as a column expression, as a condition in
SQL clauses, and with operators like =, >, <, >=, <=, IN, BETWEEN, etc.
Rules to be followed: Following are the rules to be followed while writing subqueries −
 Subqueries must be enclosed within parentheses.
 Subqueries can be nested within another subquery.
 A subquery must contain the SELECT query and the FROM clause always.
 A subquery consists of all the clauses an ordinary SELECT clause can contain: GROUP BY,
WHERE, HAVING, DISTINCT, TOP/LIMIT, etc. However, an ORDER BY clause is only used
when a TOP clause is specified. It can't include COMPUTE or FOR BROWSE clause.
 A subquery can return a single value, a single row, a single column, or a whole table. They are called
scalar subqueries.

Subqueries with the SELECT Statement: Subqueries are most frequently used with the SELECT
statement. The basic syntax is as follows −
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ] [WHERE]);
Example: In the following query, we are creating a table named CUSTOMERS −
CREATETABLE CUSTOMERS (
ID INT NOTNULL,
NAME VARCHAR (20) NOTNULL,
AGE INT NOTNULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Here, we are inserting records into the above-created table using INSERT INTO statement −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00),
(4, 'Chaitali', 25, 'Mumbai', 6500.00),
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);
Select * from customers;
ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Now, let us check the following subquery with a SELECT statement.


SELECT*FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY >4500);
This would produce the following result −
ID NAME AGE ADDRESS SALARY

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

7 Muffy 24 Indore 10000.00

Subqueries with the INSERT Statement: We can also use the subqueries along with the INSERT
statements. The data returned by the subquery is inserted into another table. In the following example, we
are creating another table CUSTOMERS_BKP with similar structure as CUSTOMERS table −
CREATETABLE CUSTOMERS_BKP (
ID INT NOTNULL,
NAME VARCHAR (20) NOTNULL,
AGE INT NOTNULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Now to copy the complete records of CUSTOMERS table into the CUSTOMERS_BKP table, we can use
the following query −
INSERTINTO CUSTOMERS_BKP
SELECT*FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);

Subqueries with the UPDATE Statement: A subquery can also be used with the UPDATE statement. You
can update single or multiple columns in a table using a subquery.
Example: We have the CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The
following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose
AGE is greater than or equal to 27.

UPDATE CUSTOMERS
SET SALARY = SALARY *0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 );

Subqueries with the DELETE Statement: The subquery can be used with the DELETE statement as well;
like with any other statements mentioned above.
Example: We have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The
following example deletes the records from the CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27.
DELETEFROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 );

You might also like