0% found this document useful (0 votes)
35 views67 pages

DBMS Unit-8 9

SQL was originally developed in the 1970s at IBM under the name SEQUEL and later renamed SQL. It has since become the standard language for querying and managing data in relational database management systems. The SQL standard is developed and regulated by ANSI and ISO and has gone through numerous revisions and updates since the 1980s. SQL code can be used to perform tasks like data retrieval, insertion, updating, and deletion on databases like MySQL, Oracle, and Microsoft SQL Server.

Uploaded by

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

DBMS Unit-8 9

SQL was originally developed in the 1970s at IBM under the name SEQUEL and later renamed SQL. It has since become the standard language for querying and managing data in relational database management systems. The SQL standard is developed and regulated by ANSI and ISO and has gone through numerous revisions and updates since the 1980s. SQL code can be used to perform tasks like data retrieval, insertion, updating, and deletion on databases like MySQL, Oracle, and Microsoft SQL Server.

Uploaded by

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

Overview

Pronounced “S-Q-L” by some and “sequel” by others, SQL has become the de facto
standard language for creating and querying relational databases.
SQL, the most common language for relational systems. It has been accepted as a U.S. standard
by the American National Standards Institute (ANSI) and is a Federal Information Processing
Standard (FIPS). It is also an international standard recognized by the International
Organization for Standardization (ISO). ANSI has accredited the International Committee for
Information Technology Standards (INCITS) as a standards development organization;
INCITS is working on the next version of the SQL standard to be released.

The ANSI SQL standards were first published in 1986 and updated in 1989, 1992 (SQL-92),
1999 (SQL:1999), 2003 (SQL:2003), 2006 (SQL:2006), 2008 (SQL:2008), and 2011
(SQL:2011). (See http:// en.wikipedia.org/wiki/SQL for a summary of this history.) The
standard is now generally referred to as SQL:2011.

SQL has been implemented in both mainframe and personal computer systems, so this
chapter is relevant to both computing environments. Although many of the PC-database
packages use a query-by-example (QBE) interface, they also include SQL coding as an
option. QBE interfaces use graphic presentations and translate the QBE actions into SQL
code before query execution occurs. In Microsoft Access, for example, it is possible to
switch back and forth between the two interfaces; a query that has been built using a QBE
interface can be viewed in SQL by clicking a button. This feature may aid you in learning
SQL syntax. In client/ server architectures, SQL commands are executed on the server, and
the results are returned to the client workstation.

The first commercial DBMS that supported SQL was Oracle in 1979. Oracle
is now available in mainframe, client/server, and PC-based platforms for many
operating systems, including various UNIX, Linux, and Microsoft Windows operating
systems. IBM’s DB2, Informix, and Microsoft SQL Server are available for this range
of operating systems also.

Origins of the SQL Standard

The concepts of relational database technology were first articulated in 1970, in


E. F. Codd’s classic paper “A Relational Model of Data for Large Shared Data Banks.”
Workers at the IBM Research Laboratory in San Jose, California, undertook development of
System R, a project whose purpose was to demonstrate the feasibility of implementing the
relational model in a database management system. They used a language called Sequel, also
developed at the San Jose IBM Research Laboratory. Sequel was renamed SQL during the
project, which took place from 1974 to 1979. The knowledge gained was applied in the
development of SQL/DS, the first relational database management system available
commercially (from IBM). SQL/DS was first available in 1981, running on the DOS/VSE
operating system. A VM version followed in 1982, and the MVS version, DB2, was
announced in 1983.
When System R was well received at the user sites where it was installed, other
vendors began developing relational products that used SQL. One product, Oracle, from
Relational Software, was actually on the market before SQL/DS (1979). Other products
included INGRES from Relational Technology (1981), IDM from Britton-Lee (1982),
DG/SQL from Data General Corporation (1984), and Sybase from Sybase, Inc. (1986).
To provide some directions for the development of relational DBMSs, ANSI and the
ISO approved a standard for the SQL relational query language (functions and syntax) that
was originally proposed by the X3H2 Technical Committee on Database (Technical
Committee X3H2—Database, 1986; ISO, 1987), often referred to as SQL/86. For a more
detailed history of the SQL standard, see the documents available at www.wiscorp.com.

The following were the original purposes of the SQL standard:

1. To specify the syntax and semantics of SQL data definition and manipulation languages
2. To define the data structures and basic operations for designing, accessing, maintaining,
controlling, and protecting an SQL database
3. To provide a vehicle for portability of database definition and application
Modules between conforming DBMSs
4. To specify both minimal (Level 1) and complete (Level 2) standards, which permit
different degrees of adoption in products
5. To provide an initial standard, although incomplete, that will be enhanced later to include
specifications for handling such topics as referential integrity, transaction management, user-
defined functions, join operators beyond the equi-join, and national character sets

In terms of SQL, when is a standard not a standard? As explained earlier, most


vendors provide unique, proprietary features and commands for their SQL database
management system. So what are the advantages and disadvantages of having an SQL
standard, when there are such variations from vendor to vendor?

Many products are available that support SQL, and they run on machines of
all sizes, from small personal computers to large mainframes. The database market
is maturing, and the rate of significant changes in products may slow, but they will
continue to be SQL based. The number of relational database vendors with significant
market share has continued to consolidate. Gartner Group reports that Oracle controlled
almost 49 percent of the overall relational database management system market
in 2011, IBM was in second place, and Microsoft came in a close third.

Many products are available that support SQL, and they run on machines of
all sizes, from small personal computers to large mainframes. The database market
is maturing, and the rate of significant changes in products may slow, but they will
continue to be SQL based. The number of relational database vendors with significant
market share has continued to consolidate. Gartner Group reports that Oracle controlled
almost 49 percent of the overall relational database management system market
in 2011, IBM was in second place, and Microsoft came in a close third.

Here are some important parts of SQL standards:


Part Description
Part 1 – SQL/Framework It offers logical concepts.
Part 2 – SQL/Foundation It includes central elements of SQL.
Part 3 – SQL/CLI This standard includes central elements of SQL.
Part 4 – Persistent Stored Stored routines, external routines, and procedural language
Modules extensions to SQL.
Part 9 – Management of Adds syntax and definitions to SQL/Foundation, which allow SQL
External Data access to non-SQL data sources (files).
Part 10 – Object Object Language Bindings: This part specifies the syntax and
Language Bindings semantics of embedding SQL in Java™.
Part 11 – SQL/Schema Information and Definition Schemas
This project began in 2000. This part helps to define the syntax
Part 12 –
and semantics to allow the definition of replication schemes and
SQL/Replication
rules.
Part 13 – Java Routines Java Routines and Types: This part of routines using the Java
and Type Programming Language.
Part 14 – SQL/XML SQL and XML
Part 15 – SQL/MDA Provide SQL support for Multi-Dimensional Arrays
What is Database?
A database is an organized collection of data or information that is stored electronically in a
computer system. It enables us to store any type and huge volumes of data for easy accessibility and
use.

For example:- MYSQL, oracle.

History of SQL
"A Relational Model of Data for Large Shared Data Banks" was a paper which was published by the
great computer scientist "E.F. Codd" in 1970.

The IBM researchers Raymond Boyce and Donald Chamberlin originally developed the SEQUEL
(Structured English Query Language) after learning from the paper given by E.F. Codd. They both
developed the SQL at the San Jose Research laboratory of IBM Corporation in 1970.

At the end of the 1970s, relational software Inc. developed their own first SQL using the concepts of
E.F. Codd, Raymond Boyce, and Donald Chamberlin. This SQL was totally based on RDBMS.
Relational Software Inc., which is now known as Oracle Corporation, introduced the Oracle V2 in
June 1979, which is the first implementation of SQL language. This Oracle V2 version operates on
VAX computers.

Here are important landmarks from the history of SQL:

 1970 – Dr. Edgar F. “Ted” Codd described a relational model for databases.
 1974 – Structured Query Language appeared.
 1978 – IBM released a product called System/R.
 1986 – IBM developed the prototype of a relational database, which is standardized
by ANSI.
 1989 – First ever version launched of SQL
 1999 – SQL 3 launched with features like triggers, object-orientation, etc.
 SQL 2003 – window functions, XML-related features, etc.
 SQL 2006 – Support for XML Query Language
 SQL 2011 -improved support for temporal databases

What is SQL?

Structured Query Language or SQL is the language that is used to store and manage data in RDBMS. Using
SQL, we can query a database to add, modify, alter, update, or delete data relational databases. The
language also helps us to create and modify database schemas.
It can help users manage multiple relational database management systems, such as MySQL, Oracle, and
MS Access. Most of the database queries for retrieving, adding, or manipulating data are based on the
standard SQL syntax, except for a few minor syntax changes.
According to the American National Standards Institute (ANSI), SQL is the standard language for managing
a relational database management system. One key benefit of SQL is that it allows users to retrieve
multiple records in a database with a single command.
What is MySQL?

MySQL is an open-source RDBMS (relational database management system). It uses SQL queries to
perform specific operations in a database. It is written in the C and C++ programming languages and is
compatible with all major platforms, such as Windows, Linux, macOS X, etc.
Developed in 1995 by MySQL AB, MySQL is now owned and managed by Oracle Corporation. MySQL is
used by many top companies such as Netflix, Amazon, and Uber to manage a large volume of data.

Key Difference Between SQL and MySQL

SQL is a language which is used to operate your database whereas MySQL was one of the first open-source
database available in the market
SQL is used in the accessing, updating, and manipulation of data in a database while MySQL is an RDBMS
that allows keeping the data that exists in a database organized
SQL is a Structured Query Language and MySQL is a RDBMS to store, retrieve, modify and administrate a
database. SQL is a query language while MYSQL is a database software

Basic Of SQL

SQL (Structured Query Language) is used to perform operations on the records stored in the database, such
as updating records, inserting records, deleting records, creating and modifying database tables, views, etc.

SQL is not a database system, but it is a query language.

Suppose you want to perform the queries of SQL language on the stored data in the database. You are
required to install any database management system in your systems, for
example, Oracle, MySQL, MongoDB, PostgreSQL, SQL Server, DB2, etc.

The recent ISO standard version of SQL is SQL:2019.

What is SQL?
SQL is a short-form of the structured query language, and it is pronounced as S-Q-L or sometimes
as See-Quell.

This database language is mainly designed for maintaining the data in relational database
management systems. It is a special tool used by data professionals for handling structured data
(data which is stored in the form of tables). It is also designed for stream processing in RDSMS.

You can easily create and manipulate the database, access and modify the table rows and columns,
etc. This query language became the standard of ANSI in the year of 1986 and ISO in the year of
1987.
If you want to get a job in the field of data science, then it is the most important query language to
learn. Big enterprises like Facebook, Instagram, and LinkedIn, use SQL for storing the data in the
back-end.

Why SQL?
Nowadays, SQL is widely used in data science and analytics. Following are the reasons which explain
why it is widely used:

o The basic use of SQL for data professionals and SQL users is to insert, update, and delete the
data from the relational database.
o SQL allows the data professionals and users to retrieve the data from the relational database
management systems.
o It also helps them to describe the structured data.
o It allows SQL users to create, drop, and manipulate the database and its tables.
o It also helps in creating the view, stored procedure, and functions in the relational database.
o It allows you to define the data and modify that stored data in the relational database.
o It also allows SQL users to set the permissions or constraints on table columns, views, and
stored procedures.

Process of SQL
When we are executing the command of SQL on any Relational database management system, then
the system automatically finds the best routine to carry out our request, and the SQL engine
determines how to interpret that particular command.

Structured Query Language contains the following four components in its process:

o Query Dispatcher
o Optimization Engines
o Classic Query Engine
o SQL Query Engine, etc.

A classic query engine allows data professionals and users to maintain non-SQL queries. The
architecture of SQL is shown in the following diagram
SQL Language elements
Here are important elements of SQL language:

 Keywords: Each SQL statement contains single or multiple keywords.


 Identifiers: Identifiers are names of objects in the database, like user IDs, tables, and
columns.
 Strings: Strings can be either literal strings or expressions with VARCHAR or CHAR
data types.
 Expressions: Expressions are formed from several elements, like constants, SQL
operators, column names, and subqueries.
 Search Conditions: Conditions are used to select a subset of the rows from a table or
used to control statements like an IF statement to determine control of flow.
 Special Values: Special values should be used in expressions and as column defaults
when building tables.
 Variables: Sybase IQ supports local variables, global variables, and connection-level
variables.
 Comments: Comment is another SQL element which is used to attach explanatory
text to SQL statements or blocks of statements. The database server does not
execute any comment.
 NULL Value: Use NULL, which helps you to specify a value that is unknown, missing,
or not applicable.

Types of SQL Statements


Here are five types of widely used SQL queries.

 Data Definition Language (DDL)


 Data Manipulation Language (DML)
 Data Control Language (DCL)
 Transaction Control Language (TCL)
 Data Query Language (DQL)

DDL: Data Definition Language (DDL)


DDL Commands: Create, Alter, Drop, Rename, Truncate

The data definition language is used to create an object, alter the structure of an object and also drop
already created object. The Data Definition Languages used for table definition can be classified
into following:

CREATE - to create objects in the database


ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records
are removed
RENAME - rename an object

The set of relations in a database must be specified to the system by means of a data-definition
language (DDL). The SQL DDL allows specification of not only a set of relations, but also
information about each relation, including:

The schema for each relation.


• The types of values associated with each attribute.
• The integrity constraints.
• The set of indices to be maintained for each relation.
• The security and authorization information for each relation.
• The physical storage structure of each relation on disk.

DDL: Data Definition Language (DDL)

SQL CREATE DATABASE Statement


Syntax
CREATE DATABASE databasename;

Example
CREATE DATABASE demo;
SQL DROP DATABASE Statement
Syntax
DROP DATABASE databasename;

Example
DROP DATABASE demo;

SQL CREATE TABLE Statement


Syntax
CREATE TABLE table_name (
column1 datatype, column2
datatype, column3 datatype,
....
);

Example
CREATE TABLE students (
rollno int,
stdname varchar(255),
DOB date,
Address text,
City varchar(255) );

SQL DROP TABLE Statement


Syntax
DROP TABLE table_name;

Example
DROP TABLE students;

SQL TRUNCATE TABLE


The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.

Syntax
TRUNCATE TABLE table_name;

Example
TRUNCATE TABLE students;

SQL ALTER TABLE Statement


ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:

ALTER TABLE table_name ADD column_name datatype;


Example:

ALTER TABLE students ADD Email VARCHAR(255);

ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

Example:-
ALTER TABLE table_name
DROP COLUMN Email;

ALTER Data Type


To change the data type of the column , use the following

ALTER TABLE students


MODIFY COLUMN column_name datatype;

Example:-
ALTER TABLE students
MODIFY COLUMN rollno int(3);

ALTER TABLE - RENAME COLUMN

To rename a column in a table, use the following syntax:

ALTER TABLE table_name


RENAME COLUMN old_name to new_name;

Example:-

ALTER TABLE students


RENAME COLUMN stdname to name;

DML: Data Manipulation Language (DML)


DML Commands: Insert, Update, Delete, Select
DML statements are used for managing data within schema objects and to manipulate data of a database
objects.

INSERT - insert data into a table


UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
SELECT - retrieve data from the a database

o DML commands are used to modify the database. It is responsible for all form of changes in
the database.
o The command of DML is not auto-committed that means it can't permanently save all the
changes in the database. They can be rollback

SQL INSERT INTO Statement

INSERT INTO Syntax


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the same
order as the columns in the table. The INSERT INTO syntax would be as follows:

INSERT INTO table_name VALUES (value1, value2, value3, ...);

Example
INSERT INTO department (dept_no , dept_name, location) VALUES (10, 'Account', 'NY');

SQL SELECT Statement


SELECT Syntax
SELECT * FROM table_name;

SELECT column1, column2, ... FROM table_name;

Example
SELECT * FROM students;

SELECT stdName, mobileno FROM students;

SQL SELECT DISTINCT Statement


The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want
to list the different (distinct) values.

The SELECT DISTINCT statement is used to return only distinct (different) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...FROM table_name;

Example
SELECT DISTINCT rollno FROM students;

Example
SELECT COUNT(DISTINCT rollno) FROM students;

SQL WHERE Clause


The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...FROM table_name WHERE condition;

SELECT * FROM Students WHERE stdname='XYZ';

SELECT * FROM Students WHERE rollno=1;

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:
Operator Description

= Equal

<> Not equal. Note: In some versions of SQL this operator may be written
as !=
> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern


IN To specify multiple possible values for a column

SQL AND, OR and NOT Operators


AND Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 AND condition2 AND
condition3 ...;

Example
SELECT * FROM Students WHERE stdname='patel' AND rollno=5;

OR Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 OR condition2 OR condition3
...;

Example
SELECT * FROM Students WHERE stdname ='patel' OR stdname ='shah';

NOT Syntax
SELECT column1, column2, ...FROM table_name WHERE NOT condition;

Example
SELECT * FROM Students WHERE NOT stdname ='patel';

Combining AND, OR and NOT


Example
SELECT * FROM Students WHERE stdname ='patel' AND (rollno=3 OR rollno =5);

Example

SELECT * FROM Students WHERE NOT stdname ='patel' AND NOT rollno=3;

SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|DESC;
Example
SELECT * FROM Students ORDER BY stdname;

Example
SELECT * FROM Students ORDER BY stdname DESC;

Example
SELECT * FROM Students ORDER BY rollno, stdname;

Example
SELECT * FROM Students ORDER BY rollno ASC, stdname DESC;

SQL UPDATE Statement


The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

Example
UPDATE department SET , dept_name = 'Clerk', location = 'USA' WHERE dept_no = 10;

Example
UPDATE department SET dept_name ='Account' WHERE location ='USA';

Example
UPDATE department SET location ='IND';

SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Example
DELETE FROM department WHERE location ='USA';

Delete All Records


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_name; or DELETE * FROM table_name;


DCL: Data Control Language (DCL)
DCL Commands: Grant, Revoke
DCL statements are used to create roles, permissions, and referential integrity as well it is used to control
access to database by securing it. To control the data of a database.

GRANT - gives user's access privileges to database


REVOKE -withdraw access privileges given with the GRANT command .

Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;


STRUCTURE OF DBMS

DBMS (Database Management System) acts as an interface between the user and the database. The
user requests the DBMS to perform various operations (insert, delete, update and retrieval) on the
database. The components of DBMS perform these requested operations on the database and provide
necessary data to the users. The various components of DBMS are shown below: -

1. DDL Compiler - Data Description Language compiler processes schema definitions


specified in the DDL. It includes metadata information such as the name of the files, data items,
storage details of each file, mapping information and constraints etc.

2. DML Compiler and Query optimizer - The DML commands such as insert, update, delete,
retrieve from the application program are sent to the DML compiler for compilation into object code for
database access. The object code is then optimized in the best way to execute a query by the query
optimizer and then send to the data manager.

3. Data Manager - The Data Manager is the central software component of the DBMS also
knows as Database Control System.

The Main Functions Of Data Manager Are: –

• Convert operations in user's Queries coming from the application programs or combination of DML
Compiler and Query optimizer which is known as Query Processor from user's logical view to physical
file system.

• Controls DBMS information access that is stored on disk.

• It also controls handling buffers in main memory.

• It also enforces constraints to maintain consistency and integrity of the data.

• It also synchronizes the simultaneous operations performed by the concurrent users.

• It also controls the backup and recovery operations.

4. Data Dictionary - Data Dictionary is a repository of description of data in the database. It


contains information about
• Data - names of the tables, names of attributes of each table, length of attributes, and number of
rows in each table.

• Relationships between database transactions and data items referenced by them which is useful in
determining which transactions are affected when certain data definitions are changed.

• Constraints on data i.e. range of values permitted.

• Detailed information on physical database design such as storage structure, access paths, files and
record sizes.

• Access Authorization - is the Description of database users their responsibilities and their access
rights.

• Usage statistics such as frequency of query and transactions.

Data dictionary is used to actually control the data integrity, database operation and accuracy. It
may be used as a important part of the DBMS.

Importance of Data Dictionary -

Data Dictionary is necessary in the databases due to following reasons:

• It improves the control of DBA over the information system and user's understanding of use of the
system.

• It helps in documentating the database design process by storing documentation of the result of
every design phase and design decisions.

• It helps in searching the views on the database definitions of those views.

• It provides great assistance in producing a report of which data elements (i.e. data values)
are used in all the programs.

• It promotes data independence i.e. by addition or modifications of structures in the database


application program are not effected.

5. Data Files - It contains the data portion of the database.

6. Compiled DML - The DML complier converts the high level Queries into low level file access
commands known as compiled DML.

7. End Users - user

Constraints in SQL
Constraints in SQL means we are applying certain conditions or restrictions on the database. This
further means that before inserting data into the database, we are checking for some conditions. If
the condition we have applied to the database holds true for the data which is to be inserted, then
only the data will be inserted into the database tables.
Constraints in SQL can be categorized into two types:
1. Column Level Constraint:
Column Level Constraint is used to apply a constraint on a single column.
2. Table Level Constraint:
Table Level Constraint is used to apply a constraint on multiple columns.

Some of the real-life examples of constraints are as follows:


1. Every person has a unique email id. This is because while creating an email account for any user, the
email providing services such as Gmail, Yahoo or any other email providing service will always check
for the availability of the email id that the user wants for himself. If some other user already takes the
email id that the user wants, then that id cannot be assigned to another user. This simply means that
no two users can have the same email ids on the same email providing service. So, here the email id
is the constraint on the database of email providing services.
2. Whenever we set a password for any system, there are certain constraints that are to be followed.
These constraints may include the following:
o There must be one uppercase character in the password.
o Password must be of at least eight characters in length.
o Password must contain at least one special symbol.

Constraints available in SQL are:


1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. CREATE INDEX

1. NOT NULL
o NULL means empty, i.e., the value is not available.
o Whenever a table's column is declared as NOT NULL, then the value for that column cannot be empty
for any of the table's records.
o There must exist a value in the column to which the NOT NULL constraint is applied.

CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), Student_LastName V


ARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

Syntax to apply the NOT NULL constraint on an existing table's column:


1. ALTER TABLE TableName CHANGE Old_ColumnName New_ColumnName Datatype NOT N
ULL;

Example:
ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;

2. UNIQUE
o Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.
o The column with the unique constraint will always contain a unique value.
o This constraint can be applied to one or more than one column of a table, which means more than
one unique constraint can exist on a single table.
o Using the UNIQUE constraint, you can also modify the already created tables.

Syntax to apply the UNIQUE constraint on a single column:


1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,….,
ColumnNameN datatype);
Example
CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(20), Student_LastName VA
RCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

Syntax to apply the UNIQUE constraint on more than one column:

1. CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,…., Column


NameN datatype, UNIQUE (ColumnName1, ColumnName 2));

CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), UNIQUE(StudentID, Student_P
honeNumber));

Syntax to apply the UNIQUE constraint on an existing table's column:

1. ALTER TABLE TableName ADD UNIQUE (ColumnName);

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided
to apply a UNIQUE constraint to one of the table's column. Then we will execute the following query:

1. mysql> ALTER TABLE student ADD UNIQUE (StudentID);


PRIMARY KEY
o PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.
o NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY constraint.
o The column to which we have applied the primary constraint will always contain a unique
value and will not allow null values.

Syntax of primary key constraint during table creation:


CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,….,
ColumnNameN datatype);

Example:

Create a student table and apply the PRIMARY KEY constraint while creating a table.

CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20), Student_LastNa


me VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

Syntax to apply the primary key constraint on an existing table's column:


ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);

Example:
ALTER TABLE student ADD PRIMARY KEY (StudentID);

FOREIGN KEY
o A foreign key is used for referential integrity.
o When we have two tables, and one table takes reference from another table, i.e., the same
column is present in both the tables and that column acts as a primary key in one table. That
particular column will act as a foreign key in another table.

Syntax to apply a foreign key constraint during table creation:

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatyp


e(SIZE), FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_Column
Name));

Example:

Create an employee table and apply the FOREIGN KEY constraint while creating a table.

To create a foreign key on any table, first, we need to create a primary key on a table.
CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_Salary
VARCHAR (40));

CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID IN
T NOT NULL, FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));

Syntax to apply the foreign key constraint on an existing table's column:

ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES Child_TableName (Col
umnName);

Example

ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES employee (Emp_ID);

Syntax to apply the foreign key constraint with constraint name:

CREATE TABLE tablename(ColumnName1 Datatype PRIMARY KEY, ColumnNameN Datatype(SIZE), CONS


TRAINT ConstraintName FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_
ColumnName));

Example

CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID
INT NOT NULL, CONSTRAINT emp_id_fk FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));

5. CHECK

o Whenever a check constraint is applied to the table's column, and the user wants to insert
the value in it, then the value will first be checked for certain conditions before inserting the
value into that column.
o For example: if we have an age column in a table, then the user will insert any value of his
choice. The user will also enter even a negative value or any other invalid value. But, if the
user has applied check constraint on the age column with the condition age greater than 18.
Then in such cases, even if a user tries to insert an invalid value such as zero or any other
value less than 18, then the age column will not accept that value and will not allow the user
to insert it due to the application of check constraint on the age column.

Syntax to apply check constraint on a single column:

CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition), Colu


mnName2 datatype,…., ColumnNameN datatype);

Example : Create a student table and apply CHECK constraint to check for the age less than or equal to 15
while creating a table.
CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2
0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT CHECK( Age <= 15));

Syntax to apply check constraint on multiple columns:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK (ColumnNa


me1 Condition AND ColumnName2 Condition),…., ColumnNameN datatype);
Example
Create a student table and apply CHECK constraint to check for the age less than or equal to 15 and a
percentage greater than 85 while creating a table.

CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT, Percentage INT, CHE
CK( Age <= 15 AND Percentage > 85));

Example:

Consider we have an existing table student. Later, we decided to apply the CHECK constraint on the
student table's column. Then we will execute the following query:

ALTER TABLE student ADD CHECK ( Age <=15 );

6. DEFAULT
Whenever a default constraint is applied to the table's column, and the user has not specified the value to be
inserted in it, then the default value which was specified while applying the default constraint will be inserted
into that particular column.

Syntax to apply default constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., Column
NameN datatype);

Example:

Create a student table and apply the default constraint while creating a table.

CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40) DEFAULT "[email protected]
");

Syntax to apply default constraint on an existing table's column:

ALTER TABLE TableName ALTER ColumnName SET DEFAULT Value;


Example:

Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on
the student table's column. Then we will execute the following query:

ALTER TABLE student ALTER Student_Email_ID SET DEFAULT "[email protected]";

7. CREATE INDEX
CREATE INDEX constraint is used to create an index on the table. Indexes are not visible to the user,
but they help the user to speed up the searching speed or retrieval of data from the database.

Syntax to create an index on single column:

CREATE INDEX IndexName ON TableName (ColumnName 1);

Example:

Create an index on the student table and apply the default constraint while creating a table.

CREATE INDEX idx_StudentID ON student (StudentID);

Syntax to create an index on multiple columns:

CREATE INDEX IndexName ON TableName (ColumnName 1, ColumnName 2, ColumnName N);

Example:

CREATE INDEX idx_Student ON student (StudentID, Student_PhoneNumber);

Syntax to create an index on an existing table:

ALTER TABLE TableName ADD INDEX (ColumnName);

Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on
the student table's column. Then we will execute the following query:

ALTER TABLE student ADD INDEX (StudentID);


IN Operator
To specify a list of values, IN operator is used. The IN operator selects value that match
any value in a given list of values.
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.

IN() function finds a match in the given arguments.

Syntax

SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);


OR
SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT);

For example:-

SELECT * FROM EMPLOYEE WHERE GRADE IN (‘A1’ , ‘A2’);

SELECT * FROM EMPLOYEE WHERE ECODE IN (SELECT ECODE FROM EMPLOYEE WHERE GROSS>40000);
The NOT IN operator finds rows that do not match in the list. E.g.

SELECT * FROM EMPLOYEE WHERE GRADE NOT IN (‘A1’ , ‘A2’);

Aggregate functions
o SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
o It is also used to summarize the data.
o Aggregate / Group functions work upon groups of rows , rather than on single row, and return
one single output. Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) ,
SUM ( )
AVG( )
This function computes the average of given data.
e.g.
SELECT AVG(SAL) FROM EMPL ;

COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN is
not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
e.g.
SELECT COUNT(*) FROM EMPL ;

e.g.2
SELECT COUNT(JOB) FROM EMPL ;

MAX( )
This function returns the maximum value from a given column or expression.
e.g.
SELECT MAX(SAL) FROM EMPL ;

MIN( )
This function returns the minimum value from a given column or expression.
e.g.
SELECT MIN(SAL) FROM EMPL ;
SUM( )
This function returns the sum of values in given column or expression.
e.g.
SELECT SUM(SAL) FROM EMPL ;

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or
a group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.

e.g. Calculate the number of employees in each JOB.

SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB ;

e.g.2. Calculate the sum of salary for each department.

SELECT DEPTNO , SUM(SAL) FROM EMPL GROUP BY DEPTNO ;

e.g.3. find the average salary of each department.


NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields in the GROUP BY
expression. e.g. To group records job wise within Deptno wise, you need to issue a query statement like :

SELECT DEPTNO , JOB , COUNT(EMPNO) FROM EMPL GROUP BY DEPTNO , JOB ;

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on individual rows.
While WHERE conditions cannot include aggregate functions, HAVING conditions can do so.
- e.g.
To display the jobs where the number of employees is less than 2,

SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB HAVING COUNT(*) < 2 ;

SQL Server String Functions


Function Description

ASCII Returns the ASCII value for the specific character

Return the ASCII value of the first character in "CustomerName":

SELECT ASCII(CustomerName) AS NumCodeOfFirstChar FROM Customers;

CHAR Returns the character based on the ASCII code

Return the character based on the number code 65:

SELECT CHAR(65) AS CodeToCharacter;


CHARINDEX Returns the position of a substring in a string

CONCAT Adds two or more strings together

Add two strings together:

SELECT CONCAT(‘SSASIT’, ‘.com’);


SELECT CONCAT(‘SQL’, ‘ is’, ‘ fun!’);

Concat with + Adds two or more strings together

CONCAT_WS Adds two or more strings together with a separator

DATALENGTH Returns the number of bytes used to represent an expression

DIFFERENCE Compares two SOUNDEX values, and returns an integer value

FORMAT Formats a value with the specified format

LEFT Extracts a number of characters from a string (starting from left)

Extract 3 characters from a string (starting from left):

SELECT LEFT('SQL Tutorial', 3) AS ExtractString;


SELECT LEFT(CustomerName, 5) AS ExtractString FROM Customers;
LEN Returns the length of a string

LOWER Converts a string to lower-case

SELECT LOWER(CustomerName) AS LowercaseCustomerName FROM Customers;

LTRIM Removes leading spaces from a string

NCHAR Returns the Unicode character based on the number code

PATINDEX Returns the position of a pattern in a string

Returns a Unicode string with delimiters added to make the string a valid SQL Server
QUOTENAME
delimited identifier

REPLACE Replaces all occurrences of a substring within a string, with a new substring

REPLICATE Repeats a string a specified number of times

REVERSE Reverses a string and returns the result

SELECT REVERSE(CustomerName) FROM Customers;

RIGHT Extracts a number of characters from a string (starting from right)

RTRIM Removes trailing spaces from a string

SOUNDEX Returns a four-character code to evaluate the similarity of two strings

SPACE Returns a string of the specified number of space characters


STR Returns a number as string

Deletes a part of a string and then inserts another part into the string, starting at a
STUFF
specified position

SUBSTRING Extracts some characters from a string

Extract 5 characters from the "CustomerName" column, starting in position 1:

SELECT SUBSTRING(CustomerName, 1, 5) AS ExtractString FROM Customers;

Returns the string from the first argument after the characters specified in the second
TRANSLATE
argument are translated into the characters specified in the third argument.

Return the string from the first argument AFTER the characters specified in the second argument
are translated into the characters specified in the third argument:

SELECT TRANSLATE('Monday', 'Monday', 'Sunday'); // Results in Sunday

TRIM Removes leading and trailing spaces (or other specified characters) from a string

Remove leading and trailing spaces from a string:

SELECT TRIM(' SQL Tutorial! ') AS TrimmedString;

UNICODE Returns the Unicode value for the first character of the input expression

Return an integer value (the Unicode value), for the first character of the input expression:

SELECT UNICODE('Atlanta');

OUTPUT

65

UPPER Converts a string to upper-case

SQL Server Math/Numeric Functions


Function Description

ABS Returns the absolute value of a number

Return the absolute value of a number:

SELECT Abs(-243.5) AS AbsNum;


AbsNum
243.5
ACOS Returns the arc cosine of a number

ASIN Returns the arc sine of a number

ATAN Returns the arc tangent of a number

ATN2 Returns the arc tangent of two numbers

AVG Returns the average value of an expression

CEILING Returns the smallest integer value that is >= a number

SELECT CEILING(25.75) AS CeilValue;

CeilValue
26
COUNT Returns the number of records returned by a select query

COS Returns the cosine of a number

COT Returns the cotangent of a number

DEGREES Converts a value in radians to degrees

EXP Returns e raised to the power of a specified number

FLOOR Returns the largest integer value that is <= to a number

SELECT FLOOR(25.75) AS FloorValue;

Returns the natural logarithm of a number, or the logarithm of a number to a specified


LOG
base

LOG10 Returns the natural logarithm of a number to base 10

MAX Returns the maximum value in a set of values

find the price of the Max product in the "Products" table:

SELECT MAX(Price) AS LargestPrice FROM Products;

MIN Returns the minimum value in a set of values

find the price of the cheapest product in the "Products" table:

SELECT MIN(Price) AS SmallestPrice FROM Products;

PI Returns the value of PI

POWER Returns the value of a number raised to the power of another number

RADIANS Converts a degree value into radians


RAND Returns a random number

ROUND Rounds a number to a specified number of decimal places

SELECT ROUND(235.415, 2, 1) AS RoundValue;

RoundValue
235.410
SIGN Returns the sign of a number

SIN Returns the sine of a number

SQRT Returns the square root of a number

SQUARE Returns the square of a number

SUM Calculates the sum of a set of values

TAN Returns the tangent of a number

SQL Server Date Functions


Function Description

CURRENT_TIMESTAMP Returns the current date and time

SELECT CURRENT_TIMESTAMP;

2023-04-10 06:46:52.087

DATEADD Adds a time/date interval to a date and then returns the date

SELECT DATEADD(month, 2, '2017/08/25') AS DateAdd;

2017-10-25 00:00:00.000

DATEDIFF Returns the difference between two dates

DATEFROMPARTS Returns a date from the specified parts (year, month, and day values)

DATENAME Returns a specified part of a date (as string)

DATEPART Returns a specified part of a date (as integer)

DAY Returns the day of the month for a specified date

Return the day of the month for a date:

SELECT DAY('2017/08/25') AS DayOfMonth;

GETDATE Returns the current database system date and time


SELECT GETDATE();

2023-04-10 06:49:28.167

GETUTCDATE Returns the current database system UTC date and time

ISDATE Checks an expression and returns 1 if it is a valid date, otherwise 0

Check if the expression is a valid date:

SELECT ISDATE('2017-08-25');
The ISDATE() function checks an expression and returns 1 if it is a valid date, otherwise 0.

MONTH Returns the month part for a specified date (a number from 1 to 12)

SYSDATETIME Returns the date and time of the SQL Server

YEAR Returns the year part for a specified date

Return the year part of a date:

SELECT YEAR('2017/08/25') AS Year;

SQL Set Operation


The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union

 The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
 In the union operation, all the number of datatype and columns must be same in both the tables on which
UNION operation is being applied.
 The union operation eliminates the duplicate rows from its resultset.

Example of UNION

The First table,

ID Name

1 abhi
2 adam

The Second table,

ID Name
2 adam
3 Chester

SELECT * FROM First


UNION
SELECT * FROM Second;

The resultset table will look like,

ID NAME
1 abhi
2 adam
3 Chester

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing duplication and
sorting the data.

Example of Union All

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME
2 adam
3 Chester

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

The resultset table will look like,


ID NAME
1 abhi
2 adam
2 adam
3 Chester

3. Intersect

 It is used to combine two SELECT statements. The Intersect operation returns the common rows from both
the SELECT statements.
 In the Intersect operation, the number of datatype and columns must be the same.
 It has no duplicates and it arranges the data in ascending order by default.

Example of Intersect

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

The resultset table will look like

ID NAME

2 adam

4. Minus

 It combines the result of two SELECT statements. Minus operator is used to display the rows which are
present in the first query but absent in the second query.
 It has no duplicates and data arranged in ascending order by default.
Example of Minus

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like,

ID NAME
1 abhi

SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE clause.

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns are in
the main query for the subquery to compare its selected columns.
 An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the
ORDER BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator
can be used within the subquery.

1. Subqueries with the Select Statement


SQL subqueries are most frequently used with the Select statement.

SELECT column_name FROM table_name WHERE column_name expression operator ( SELECT colum
n_name from table_name WHERE ... );

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00


2. Subqueries with the INSERT Statement
o SQL subquery can also be used with the Insert statement. In the insert statement, data
returned from the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.

Syntax:

INSERT INTO table_name (column1, column2, column3....) SELECT * FROM table_name


WHERE VALUE OPERATOR

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update statement. When a subquery is
used with the Update statement, then either single or multiple columns in a table can be updated.

Syntax

UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT COLUMN_NAME
FROM TABLE_NAME WHERE condition);

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The
given example updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE
is greater than or equal to 29.

UPDATE EMPLOYEE SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM EMPLOYEE
_BKP WHERE AGE >= 29);

4. Subqueries with the DELETE Statement


The subquery of SQL can be used in conjunction with the Delete statement just like any other
statements mentioned above.

Syntax

DELETE FROM TABLE_NAME WHERE VALUE OPERATOR (SELECT COLUMN_NAME FROM TABLE_NA
ME WHERE condition);
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The
given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is greater
than or equal to 29.

DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

SQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

In real life, we store our data in multiple logical tables that are linked together by a common key value in
relational databases like SQL Server, Oracle, MySQL, and others. As a result, we constantly need to get data
from two or more tables into the desired output based on some conditions. We can quickly achieve this
type of data in SQL Server using the SQL JOIN clause. This article gives a complete overview of JOIN and its
different types with an example.

The join clause allows us to retrieve data from two or more related tables into a meaningful result
set. We can join the table using a SELECT statement and a join condition. It indicates how SQL
Server can use data from one table to select rows from another table. In general, tables are related
to each other using foreign key constraints.

In a JOIN query, a condition indicates how two tables are related:

o Choose columns from each table that should be used in the join. A join condition indicates a
foreign key from one table and its corresponding key in the other table.
o Specify the logical operator to compare values from the columns like =, <, or >.

Types of JOINS in SQL Server


SQL Server mainly supports four types of JOINS, and each join type defines how two tables are
related in a query. The following are types of join supports in SQL Server:

1. INNER JOIN
2. SELF JOIN
3. CROSS JOIN
4. OUTER JOIN

INNER JOIN
This JOIN returns all records from multiple tables that satisfy the specified join condition. It is the
simple and most popular form of join and assumes as a default join. If we omit the INNER keyword
with the JOIN query, we will get the same output.

The following visual representation explains how INNER JOIN returns the matching records
from table1 and table2:

INNER JOIN Syntax

The following syntax illustrates the use of INNER JOIN in SQL Server:

SELECT columns
FROM table1
INNER JOIN table2 ON condition1
INNER JOIN table3 ON condition2

Table: Student
Table: Fee

We can demonstrate the INNER JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_


paid FROM Student INNER JOIN Fee ON Student.admission_no = Fee.admission_no;

This command gives the below result:

SELF JOIN
A table is joined to itself using the SELF JOIN. It means that each table row is combined with
itself and with every other table row. The SELF JOIN can be thought of as a JOIN of two copies of
the same tables. We can do this with the help of table name aliases to assign a specific name to
each table's instance. The table aliases enable us to use the table's temporary name that we are
going to use in the query. It's a useful way to extract hierarchical data and comparing rows inside a
single table.

SELF JOIN Syntax

The following expression illustrates the syntax of SELF JOIN in SQL Server. It works the same as the
syntax of joining two different tables. Here, we use aliases names for tables because both the table
name are the same.
SELECT T1.col_name, T2.col_name...
FROM table1 T1, table1 T2
WHERE join_condition;

Example

We can demonstrate the SELF JOIN using the following command:

SELECT S1.first_name, S2.last_name, S2.city


FROM Student S1, Student S2
WHERE S1.id <> S2.iD AND S1.city = S2.city
ORDER BY S2.city;

This command gives the below result:

CROSS JOIN
CROSS JOIN in SQL Server combines all of the possibilities of two or more tables and returns a result
that includes every row from all contributing tables. It's also known as CARTESIAN JOIN because it
produces the Cartesian product of all linked tables. The Cartesian product represents all rows
present in the first table multiplied by all rows present in the second table.

The below visual representation illustrates the CROSS JOIN. It will give all the records
from table1 and table2 where each row is the combination of rows of both tables:

CROSS JOIN Syntax

The following syntax illustrates the use of CROSS JOIN in SQL Server:
SELECT column_lists
FROM table1
CROSS JOIN table2;

Example

We can demonstrate the CROSS JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_


paid
FROM Student
CROSS JOIN Fee
WHERE Student.admission_no = Fee.admission_no;

This command gives the below result:

OUTER JOIN
OUTER JOIN in SQL Server returns all records from both tables that satisfy the join condition. In
other words, this join will not return only the matching record but also return all unmatched rows
from one or both tables.

We can categories the OUTER JOIN further into three types:

o LEFT OUTER JOIN


o RIGHT OUTER JOIN
o FULL OUTER JOIN

LEFT OUTER JOIN


The LEFT OUTER JOIN retrieves all the records from the left table and matching rows from the
right table. It will return NULL when no matching record is found in the right side table. Since
OUTER is an optional keyword, it is also known as LEFT JOIN.

The below visual representation illustrates the LEFT OUTER JOIN:


LEFT OUTER JOIN Syntax

The following syntax illustrates the use of LEFT OUTER JOIN in SQL Server:

SELECT column_lists
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;

Example

We can demonstrate the LEFT OUTER JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_


paid
FROM Student
LEFT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;

This command gives the below result:

This output shows that the unmatched row's values are replaced with NULLs in the respective
columns.

RIGHT OUTER JOIN


The RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched rows
from the left-hand table. It will return NULL when no matching record is found in the left-hand
table. Since OUTER is an optional keyword, it is also known as RIGHT JOIN.
The below visual representation illustrates the RIGHT OUTER JOIN:

RIGHT OUTER JOIN Syntax

The following syntax illustrates the use of RIGHT OUTER JOIN in SQL Server:

SELECT column_lists
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;

Example

The following example explains how to use the RIGHT OUTER JOIN to get records from both tables:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_


paid
FROM Student
RIGHT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;

This command gives the below result:

In this output, we can see that no column has NULL values because all rows in the Fee table are
available in the Student table based on the specified condition.

FULL OUTER JOIN


The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both tables. The
columns of the right-hand table return NULL when no matching records are found in the left-hand
table. And if no matching records are found in the right-hand table, the left-hand table column
returns NULL.
The below visual representation illustrates the FULL OUTER JOIN:

FULL OUTER JOIN Syntax

The following syntax illustrates the use of FULL OUTER JOIN in SQL Server:

1. SELECT column_lists
2. FROM table1
3. FULL [OUTER] JOIN table2
4. ON table1.column = table2.column;

Example

The following example explains how to use the FULL OUTER JOIN to get records from both tables:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_


paid
FROM Student
FULL OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;

This command gives the below result:

In this output, we can see that the column has NULL values when no matching records are found in
the left-hand and right-hand table based on the specified condition.
SQL ANY and ALL Operators
ALL & ANY are logical operators in SQL. They return boolean value as a result.
The ANY and ALL operators allow you to perform a comparison between a single
column value and a range of other values.

We can use any comparison operators like = , > , < , etc. with
the ANY and ALL keywords.

SQL ANY
SQL ANY compares a value of the first table with all values of the second table and
returns the row if there is a match with any value.
For example, if we want to find teachers whose age is similar to any of the student's
age, we can use

SELECT *
FROM Teachers
WHERE age = ANY (
SELECT age
FROM Students
);

Here, the sub query

SELECT age
FROM Students

returns all the ages from the Students table. And, the condition

WHERE age = ANY (...)

compares the student ages (returned by subquery) with the teacher's age. If there is
any match, the corresponding row of the Teachers table is selected.
Example: ANY in SQL

SQL ALL
SQL ALL compares a value of the first table with all values of the second table and
returns the row if there is a match with all values.
For example, if we want to find teachers whose age is greater than all students, we can
use

SELECT *
FROM Teachers
WHERE age > ALL (
SELECT age
FROM Students
);

Here, the sub query

SELECT age
FROM Students

returns all the ages from the Students table. And, the condition

WHERE age > ALL (...)


compares the student ages (returned by subquery) with the teacher's age. If the
teacher's age is greater than all student's ages, the corresponding row of
the Teachers table is selected.

Example: ALL in SQL

EXISTS

The EXISTS operator is used to test for the existence of any record in a subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
Using EXISTS condition with SELECT statement
To fetch the first and last name of the customers who placed atleast one order.
SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:

Using NOT with EXISTS


Fetch last and first name of the customers who has not placed any order.
SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:

Using EXISTS condition with DELETE statement


Delete the record of all the customer from Order Table whose last name is ‘Mehra’.
DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
SELECT * FROM Orders;

Output:

1. Using EXISTS condition with UPDATE statement


Update the lname as ‘Kumari’ of customer in Customer Table whose customer_id is
401.

UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);

SELECT * FROM Customers;


Output:

DISTINCT

There may be a situation when you have multiple duplicate records in a table. While fetching such records, it
makes more sense to fetch only those unique records instead of fetching duplicate records.

SQL DISTINCT clause is used to remove the duplicates columns from the result set.

The distinct keyword is used with select keyword in conjunction. It is helpful when we avoid duplicate
values present in the specific columns/tables. The unique values are fetched when we use the distinct
keyword.

 SELECT DISTINCT returns only distinct (different) values.


 DISTINCT eliminates duplicate records from the table.
 DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.
 DISTINCT operates on a single column.
 Multiple columns are not supported for DISTINCT.

Syntax:

1. SELECT DISTINCT expressions


2. FROM tables
3. [WHERE conditions];
SELECT DISTINCT state FROM suppliers ORDER BY state;

Example: Finding Unique Values in Multiple Column

The SQL DISTINCT clause is used to remove the duplicate records from many fields in the SELECT
statement.

Enter the SQL statement:

SELECT DISTINCT city, state


FROM suppliers
ORDER BY city, state;

The DISTINCT clause considers NULL to the unique value in SQL. We have a table called products which contains the
below data.
The SQL LIKE is a logical operator that is used to retrieve the data in a column of a table, based on a
specified pattern.

It is used along with the WHERE clause of the UPDATE, DELETE and SELECT statements, to filter the
rows based on the given pattern. These patterns are specified using ‘Wildcards’.

Suppose we need to submit the list of all the students whose name starts with ‘K’. We can obtain this with
the help of the LIKE operator as follows −

WHERE student_name LIKE 'K%';

Here, the “%” is a wild card which represents zero, one or multiple characters. And the expression “K%” specifies
that it will display the list of all the students whose name starts with ‘k’.

What are wild cards?


SQL wildcards are special characters used in SQL queries to match patterns in the data. Following are the
four wildcards used in conjunction with the LIKE operator −

S.No WildCard & Definition

1 % The percent sign represents zero, one or multiple characters.


_
2
The underscore represents a single number or character.
3 [] This matches any single character within the given range in the [].
4 [^] This matches any single character excluding the given range in the [^].

S.No Statement & Description


WHERE SALARY LIKE '200%'
1
Finds any values that start with 200.
WHERE SALARY LIKE '%200%'
2
Finds any values that have 200 in any position.
WHERE SALARY LIKE '_00%'
3
Finds any values that have 00 in the second and third positions.
WHERE SALARY LIKE '2_%_%'
4
Finds any values that start with 2 and are at least 3 characters in length.
WHERE SALARY LIKE '%2'
5
Finds any values that end with 2.
WHERE SALARY LIKE '_2%3'
6
Finds any values that have a 2 in the second position and end with a 3.
WHERE SALARY LIKE '2___3'
7
Finds any values in a five-digit number that start with 2 and end with 3.
WHERE NAME LIKE 'A[a, l, j, y, a, k]'
8
Finds any name that starts with A and has the specified alphabets. For e.g. Ajay
WHERE NAME LIKE 'A[a, l, j, y, a, k]'
9
Finds any name that starts with A and does not consists of the specified alphabets. For e.g. Abdu.

Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real
table in the database. We can create a view by selecting fields from one or more tables present in
the database. A View can either have all the rows of a table or specific rows based on certain
condition. In this article we will learn about creating , deleting and updating Views.

 A view in SQL is a virtual table that is based upon the result-set of an SQL statement
 A view will also have rows and columns just like a real table in a database
 Simply a view is nothing but a stored SQL Query
 A view can contain all the rows of a table or specific rows based on some condition
 SQL functions conditions and join statements to a view and present the data just like the data is
produced from a single table

Creating a view
A view is created by selecting fields from one or more tables present in a database

Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: Whenever a user creates a view, database engine recreates the data using the views SQL statement
i.e. view always shows upto date data.

StudentDetails

S_ID NAME ADDRESS

1 Harini Kolkata

2 Preity Hyderabad

3 Divya Chennai

4 Kushi Mumbai

5 Amitha Bangalore

StudentMarks

ID NAME MARKS AGE

1 Harini 96 20

2 Manisha 90 19

3 Divya 94 21

4 Kushi 92 19

5 Amitha 95 21

Simple Views in DBMS: Creating a view from a single table


In this example, we will create a view named as DetailsView from a single table StudentDetails

CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
The data present in a view can be seen just like a normal table select query

SELECT * FROM DetailsView;


Output:
NAME ADDRESS

Harini Kolkata

Preity Hyderabad

Divya Chennai

Kushi Mumbai

Complex view: Creating a view from multiple tables

 In this example will create a view named MarksView by taking data from both the table’s student details
and student marks
 To create a View from multiple tables just simply include multiple tables in the SELECT statement.

CREATE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View Marks:

SELECT * FROM MarksView;

Output:

NAME MARKS ADDRESS

Harini 96 Kolkata

Divya 94 Chennai

Kushi 92 Mumbai

Amitha 95 Bangalore

Deleting views in DBMS

 You can simply delete a view by using the Drop statement


 That view is not used anymore

Syntax:

DROP VIEW view_name;

Example

DROP VIEW MarksView;


Updating views
Views are updated only if certain conditions are met otherwise if any one of the conditions are not met
views will not be updated

Criteria for View Updating

 The select statement used in the create view statement should not include group by clause or order by clause
 The select statement must not contain distinct keyword
 A view should not be created from nested or Complex queries
 A view should be created from a single table but if the view is created from more than one table then it is
not allowed for updating

CREATE OR REPLACE VIEW

Create or replace view statement is used to add or remove fields from existing views

Syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
Update the view MarksView and add the field AGE to this View from StudentMarks Table,

CREATE OR REPLACE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks. AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
Fetch all the data from MarksView now as:

SELECT * FROM MarksView;


Output

NAME ADDRESS MARKS AGE

HARINI Kolkata 96 20

Divya Chennai 94 21

Kushi Mumbai 92 19

Amitha Bangalore 95 21
Inserting a row into a view

We can use insert into statement of SQL to insert a row in a view just like inserting a row in an ordinary
table

Syntax:

INSERT view_name(column1, column2 , column3,..)


VALUES(value1, value2, value3..);

Example

INSERT INTO DetailsView(NAME, ADDRESS)


VALUES("Preity","Hyderabad");
Fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;


Output

NAME ADDRESS

Harini Kolkotta

Divya Chennai

Kushi Mumbai

Amitha Bangalore

Preity Hyderabad

Deleting a row from a view

 A row in a view can be deleted just like simply deleting rows from a Table using delete statement
 But remember a row in a view can be deleted only if the row is actually deleted in the original table from
which it is created

Syntax:

DELETE FROM view_name


WHERE condition;

Example

DELETE FROM DetailsView


WHERE NAME="Preity";
Fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

NAME ADDRESS

Harini Kolkotta

Divya Chennai

Kushi Mumbai

Amitha Bangalore

Preity Hyderabad

Advantages and disadvantages of views

Advantages

 Enforce Business Rules: By placing complicated or misunderstood business logic into the view, you can be
sure to present a unified portrayal of the data which increases use and quality.
 Consistency: Once defined their calculations are referenced from the view rather than being restated in
separate queries. This makes for less mistakes and easier maintenance of code.
 Security: For example, you can restrict access to the employee table, that contains social security numbers,
but allow access to a view containing name and phone number.
 Simplicity: Databases with many tables possess complex relationships, which can be difficult to navigate if
you aren’t comfortable using Joins.
 Space: Views take up very little space, as the data is stored once in the source table.

Limitations

 Modifications: Not all views support INSERT, UPDATE, or DELETE operations. Complex multi-table
views are generally read-only.
 Performance: Hugely complex job for the database engine. That is because each time a view is referenced,
the query used to define it, is rerun.

Transaction control commands.

A transaction is the logical work unit that performs a single activity or multiple activities in a database. Transactions
may consist of a single read, write, delete, or update operations or a combination of these. Suppose that, when we
want to withdraw money from the ATM, the ATM application will achieve this operation in three steps. As a first
step, the application will check the balance of the account, and then it will deduct the money from the source
account. Along with these two processes, it will keep the log of this money withdrawing activity. The following image
basically illustrates the working principle of the transactions in the relational database systems.
The main idea of transactions is that when each of the statements returns an error, the entire modifications
rollback to provide data integrity. On the other hand, if all statements are completed successfully the data
modifications will become permanent on the database. As a result, if we experience any power outage or
other problems during the withdrawal of money from an ATM, transactions guarantee our balance
consistency. It would be the best method to perform all these steps through a transaction because the four
main properties of the transactions enable all operations more accurate and consistent. All these properties
are known as the ACID (atomicity, consistency, isolation, durability) in the relational database systems with
the first letter of their names.

 Atomicity: The entire of the operations that are included by the transaction performed successfully.
Otherwise, all operations are canceled at the point of the failure and all the previous operations are
rolled back
 Consistency: This property ensures that all the data will be consistent after a transaction is
completed according to the defined rules, constraints, cascades, and triggers
 Isolation: All transactions are isolated from other transactions
 Durable: The modification of the commited transactions becomes persist in the database

TCL stands for Transaction Control Languages. These commands are used for maintaining
consistency of the database and for the management of transactions made by the DML
commands.
A Transaction is a set of SQL statements that are executed on the data stored in DBMS.
Whenever any transaction is made these transactions are temporarily happen in database.So to
make the changes permanent, we use TCL commands.

TCL Commands
Transaction Control Language (TCL) Commands are:
 Commit − It is used to save the transactions in the database.
 Rollback − It is used to restore the database to that state which was last committed.
 Savepoint − The changes done till savpoint will be unchanged and all the transactions after
savepoint will be rolled back.

COMMIT :
This command is used to save the data permanently.
Whenever we perform any of the DML command like -INSERT, DELETE or UPDATE, these can
be rollback if the data is not stored permanently. So in order to be at the safer side COMMIT
command is used.
Syntax:
commit;
2. ROLLBACK :
This command is used to get the data or restore the data to the last savepoint or last committed
state. If due to some reasons the data inserted, deleted or updated is not correct, you can rollback
the data to a particular savepoint or if savepoint is not done, then to the last committed state.
Syntax:
rollback;
3. SAVEPOINT :
This command is used to save the data at a particular point temporarily, so that whenever needed
can be rollback to that particular point.
Syntax:
Savepoint A;
Consider the following Table Student:

Name Marks

John 79

Jolly 65

Shuzan 70

UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE NAME = ‘Jolly’;
COMMIT;
ROLLBACK;
By using this command you can update the record and save it permanently by
using COMMIT command.
Now after COMMIT :

Name Marks

John 79

Sherlock 65

Shuzan 70

If commit was not performed then the changes made by the update command can be rollback.
Now if no COMMIT is performed.
UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE STUDENT_NAME = ‘Jolly’;
After update command the table will be:

Name Marks

John 79

Sherlock 65

Shuzan 70

Now if ROLLBACK is performed on the above table:


rollback;
After Rollback:

Name Marks

John 79

Jolly 65

Shuzan 70

If on the above table savepoint is performed:


INSERT into STUDENT
VALUES ('Jack', 95);

Commit;

UPDATE NAME
SET NAME= ‘Rossie’
WHERE marks= 70;

SAVEPOINT A;

INSERT INTO STUDENT


VALUES (‘Zack’, 76);

Savepoint B;

INSERT INTO STUDENT


VALUES (‘Bruno’, 85);

Savepoint C;

SELECT *
FROM STUDENT;

Name Marks

John 79

Jolly 65

Rossie 70

Jack 95

Zack 76

Bruno 85

Now if we Rollback to Savepoint B:


Rollback to B;
The resulting Table will be-

Name Marks

John 79

Jolly 65

Rossie 70

Jack 95

Zack 76

Now if we Rollback to Savepoint A:


Rollback to A;
The resulting Table will be-

Name Marks

John 79

Jolly 65

Rossie 70

Jack 95

So It was all about TCL commands in SQL (transaction control language) with examples.

Example #1

Program to illustrate the use of COMMIT command on a DELETE statement.

Code:

BEGIN TRANSACTION;
DELETE FROM employees
WHERE employeeid = 10022;
COMMIT TRANSACTION;
PL/SQL Exit Loop (Basic Loop)
PL/SQL exit loop is used when a set of statements is to be executed at least once before the
termination of the loop. There must be an EXIT condition specified in the loop, otherwise the loop
will get into an infinite number of iterations. After the occurrence of EXIT condition, the process exits
the loop.

Syntax of basic loop:

LOOP
Sequence of statements;
END LOOP;

Syntax of exit loop:

LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;

Example of PL/SQL EXIT Loop


Let's take a simple example to explain it well:10s

DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;

After the execution of the above code, you will get the following result:

1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL Exit Loop.

o Initialize a variable before the loop body


o Increment the variable in the loop.
o You should use EXIT WHEN statement to exit from the Loop. Otherwise the EXIT statement
without WHEN condition, the statements in the Loop is executed only once.

PL/SQL EXIT Loop Example 2


DECLARE
VAR1 NUMBER;
VAR2 NUMBER;
BEGIN
VAR1:=100;
VAR2:=1;
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
IF (VAR2=10) THEN
EXIT;
END IF;
VAR2:=VAR2+1;
END LOOP;
END;

Output:

100
200
300
400
500
600
700
800
900
1000

You might also like