0% found this document useful (0 votes)
11 views129 pages

SQL-DDL DML TCL

The document provides an overview of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), along with their historical context and evolution. It details key SQL statements for creating, modifying, and managing databases and tables, as well as various constraints to ensure data integrity. Additionally, it describes the syntax for common SQL operations such as SELECT, INSERT, UPDATE, and DELETE, along with data types and constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT.

Uploaded by

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

SQL-DDL DML TCL

The document provides an overview of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), along with their historical context and evolution. It details key SQL statements for creating, modifying, and managing databases and tables, as well as various constraints to ensure data integrity. Additionally, it describes the syntax for common SQL operations such as SELECT, INSERT, UPDATE, and DELETE, along with data types and constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT.

Uploaded by

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

SQL DDL DML

COMMANDS
History

 IBM Sequel language developed as part of System R project


at the IBM San Jose Research Laboratory
 Renamed Structured Query Language (SQL)
 ANSI and ISO standard SQL:
 SQL-86
 SQL-89
 SQL-92
 SQL:1999 (language name became Y2K compliant!)
 SQL:2003
 Commercial systems offer most, if not all, SQL-92 features,
plus varying feature sets from later standards and special
proprietary features.
SQL Statments

SELECT Data retrieval


INSERT
UPDATE Data manipulation language
DELETE
MERGE (DML)
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK
SAVEPOINT Transaction control
GRANT
REVOKE
Data control language (DCL)
Most Important SQL Commands

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
SQL Data Types

Data type Description Max size Storage


char(n) Fixed width character string 8,000 characters Defined width

varchar(n) Variable width character 8,000 characters 2 bytes + number of chars


string

varchar(max) Variable width character 1,073,741,824 characters 2 bytes + number of chars


string

text Variable width character 2GB of text data 4 bytes + number of chars
string

nchar Fixed width Unicode string 4,000 characters Defined width x 2

nvarchar Variable width Unicode 4,000 characters


string

nvarchar(max) Variable width Unicode 536,870,912 characters


string

ntext Variable width Unicode 2GB of text data


string

binary(n) Fixed width binary string 8,000 bytes

varbinary Variable width binary string 8,000 bytes

varbinary(max) Variable width binary string 2GB

image Variable width binary string 2GB


Table creation

 The CREATE TABLE statement is used to create a new table in a


database.

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
);
Create Table Using Another Table
 A copy of an existing table can also be created using CREATE TABLE.
 The new table gets the same column definitions. All columns or
specific columns can be selected.
 If you create a new table using an existing table, the new table will
be filled with the existing values from the old table.

CREATE TABLE new_table_name AS


SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
SQL INSERT INTO Statement
 The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
 It is possible to write the INSERT INTO statement in two ways.

 The first way specifies both the column names and the values to be

inserted:

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, ...);
SQL DROP TABLE Statement

 The DROP TABLE statement is used to drop an existing


table in a database.
Syntax
DROP TABLE table_name;

SQL TRUNCATE TABLE


The TRUNCATE TABLE statement is used to delete the data inside a table, but
not the table itself.
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement

 The ALTER TABLE statement is used to add, delete, or modify


columns in an existing table.
 The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.
ALTER TABLE - ADD Column
 To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

ALTER TABLE - DROP COLUMN


To delete a column in a table

ALTER TABLE table_name


DROP COLUMN column_name;
SQL ALTER TABLE Statement

 ALTER TABLE - ALTER/MODIFY COLUMN

ALTER TABLE table_name


ALTER COLUMN column_na
me datatype;
SQL Create Constraints

 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.

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
 SQL constraints are used to specify rules for the data in a table.
 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.
SQL Create Constraints

 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 - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific
condition
 DEFAULT - Sets a default value for a column when no value is
specified
 INDEX - Used to create and retrieve data from the database very
quickly
SQL NOT NULL Constraint

 By default, a column can hold NULL values.


 The NOT NULL constraint enforces a column to NOT accept NULL values.
 This enforces a field to always contain a value, which means that you
cannot insert a new record, or update a record without adding a value to
this field.
SQL NOT NULL on CREATE TABLE
 The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Persons" table is created:
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL NOT NULL Constraint

 To create a NOT NULL constraint on the "Age" column when the


"Persons" table is already created, use the following SQL:

ALTER TABLE Persons


MODIFY Age int NOT NULL;
SQL UNIQUE Constraint

 The UNIQUE constraint ensures that all values in a column are different.
 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint.
 However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE

CREATE TABLE Persons (

ID int NOT NULL UNIQUE,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int

);
SQL PRIMARY KEY Constraint

 The PRIMARY KEY constraint uniquely identifies each record in a table.


 Primary keys must contain UNIQUE values, and cannot contain NULL values.
 A table can have only ONE primary key; and in the table, this primary key can consist of single or
multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE

CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
SQL PRIMARY KEY Constraint

 To create a PRIMARY KEY constraint on the "ID" column when the table is already created,
use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons


ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
Note : If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) must already have been declared to not contain
NULL values (when the table was first created).
SQL PRIMARY KEY Constraint

 DROP a PRIMARY KEY Constraint


 To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP CONSTRAINT PK_Person;
SQL FOREIGN KEY Constraint

 A FOREIGN KEY is a key used to link two tables together.


 A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
 The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
SQL FOREIGN KEY Constraint

 Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
 The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
 The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
 The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables. OrderID OrderNu PersonI
PersonID LastName FirstName Age mber D
The FOREIGN KEY constraint also prevents invalid data from being inserted into
1 the foreignHansen
key column,Ola 30 to be one of1 the values
because it has 77895 3 in the
contained
2 table it points
Svendson
to. Tove 23 2 44678 3
3 Pettersen Kari 20 3 22456 2
4 24562 1
SQL FOREIGN KEY Constraint

 SQL FOREIGN KEY on CREATE TABLE


 The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table
is created:
 CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
CREATE TABLE Persons (
); ID
int NOT NULL PRIMARY KEY,
LastName
varchar(255) NOT NULL,
FirstName varchar(255),
Age int );
SQL CHECK Constraint

 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for this column.
 If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

SQL CHECK on CREATE TABLE


 The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is
created. The CHECK constraint ensures that the age of a person must be 18, or older:
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
 To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following SQL syntax:
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
SQL CHECK on ALTER TABLE

 To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
DROP a CHECK Constraint

 ALTER TABLE Persons


DROP CONSTRAINT CHK_PersonAge;
SQL DEFAULT Constraint

 The DEFAULT constraint is used to provide a default value for a


column.
 The default value will be added to all new records IF no other
value is specified.

 CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
SQL DEFAULT Constraint

SQL DEFAULT on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is
already created, use the following SQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';
SQL SELECT Statement

 The SELECT statement is used to select data from a database.


 The data returned is stored in a result table, called the result-
set.

Syntax:
SELECT column1, column2, ...
FROM table_name;

To select all the fields available in the table, use the following
syntax:
SELECT * FROM table_name;
SQL SELECT DISTINCT Statement

 The SELECT DISTINCT statement is used to return only


distinct (different) values.

Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
SQL SELECT

 The select clause can contain arithmetic


expressions involving the operation, +, –, ,
and /, and operating on constants or attributes of
tuples.
 The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor
relation, except that the value of the attribute salary is
divided by 12.
 Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
The From clause
 The from clause lists the relations involved in the
query
 Corresponds to the Cartesian product operation of the
relational algebra.
 Find the Cartesian product instructor X teaches

select * from instructor, teaches


 generates every possible instructor – teaches pair, with all
attributes from both relations.
 For common attributes (e.g., ID), the attributes in the
resulting table are renamed using the relation name (e.g.,
instructor.ID)
 Cartesian product not very useful directly, but
useful combined with where-clause condition
(selection operation in relational algebra).
The From clause
instructor teaches
The From clause
Find the names of all instructors who have taught some course
and the course_id
select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID

Find the names of all instructors in the Art department who have
taught some course and the course_id
select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID and instructor. dept_name
= ‘Art’
instructor teaches
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.

Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Operators in The WHERE Clause
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
SQL AND, OR and
NOT Operators
 The WHERE clause can be combined with AND, OR, and
NOT operators.
 The AND and OR operators are used to filter records based
on more than one condition:
 The AND operator displays a record if all the
conditions separated by
AND are TRUE.
 The OR operator displays a record if any of the
conditions separated by
OR is TRUE.
 The NOT operator displays a record if the condition(s) is
NOT TRUE.
SQL AND, OR and
NOT Operators
AND Syntax
SELECT column1, column2, ... SELECT * FROM Customers
FROM table_name WHERE Country='Germany' AND C
WHERE condition1 AND condition2ity='Berlin';
AND condition3 ...;

OR Syntax
SELECT * FROM Customers
SELECT column1, column2, ...
FROM table_name WHERE City='Berlin' OR City='Münche
n'; OR condition3 ...;
WHERE condition1 OR condition2

NOT Syntax
SELECT column1, column2, ... SELECT * FROM Customers
FROM table_name WHERE NOT Country='Germany'
WHERE NOT condition; ;
SQL ORDER BY
 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
SELECT * FROM Customers
sort the records in descending order, use the DESC keyword.
ORDER BY Country;

ORDER BY Syntax SELECT * FROM Customers


 SELECT column1, column2, ... ORDER BY Country DESC;
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT * FROM Customers
ORDER BY Country,
CustomerName;

SELECT * FROM Customers


ORDER BY Country ASC,
CustomerName DESC;
SQL NULL Values
 A field with a NULL value is a field with no value.
 If a field in a table is optional, it is possible to insert a new
record or update a record without adding a value to this
field. Then, the field will be saved with a NULL value.

Note: A NULL value is different from a zero value or a field that


contains spaces. A field with a NULL value is one that has been left
blank
IS NULLduring
Syntaxrecord creation!
 SELECT column_names
FROM table_name
WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
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, ...
Note: The WHERE
WHERE clause specifies which record(s) that should be
condition;
updated. If you omit the WHERE clause, all records in the table will
be updated!
UPDATE Customers
SET ContactName = 'Alfred
Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
SQL DELETE Statement
 The DELETE statement is used to delete existing records in
a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will
be deleted!

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; DELETE FROM Customers WHERE


CustomerName='Alfreds Futterkiste';
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() Functions
 The MIN() function returns the smallest value of the selected
column.
 The MAX() function returns the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
SQL MIN() and MAX() Functions

SELECT MIN(Price) AS SmallestPri


ce
FROM Products;

SELECT MAX(Price) AS LargestPric


e
FROM Products;
SQL COUNT(), AVG() and
SUM() Functions
 The COUNT() function returns the number of rows that
matches a specified criterion.
 The AVG() function returns the average value of a numeric
column.
 The SUM() function returns the total sum of a numeric
column.

COUNT() Syntax
SELECT COUNT(column_name) SUM() Syntax
FROM table_name
WHERE condition; SELECT SUM(column_na
me)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SQL COUNT(), AVG() and
SUM() Functions

SELECT COUNT(ProductID) FROM Products;

SELECT AVG(Price) FROM Products;

SELECT SUM(Price)FROM Products;


SQL LIKE Operator
 The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
 There are two wildcards often used in conjunction with the LIKE operator:
% - The percent sign represents zero, one, or multiple characters. i.e
characters
matches any
substring
_ - The underscore represents a single character. i.e(characters matches any
characeter
Note : The percent sign and the underscore can also be used in
combinations!

LIKE Syntax
 SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Other functions • String conversion
 Concatenation (||) upper(s)
lower(s)
 Extracting substrings • Remove the space at
 Length of the sring the end of the string
SQL LIKE Operator
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or Finds any values that have "or" in
%' any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in
the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a"
and are at least 2 characters in
length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a"
and are at least 3 characters in
length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a"
and ends with "o"
SQL LIKE Operator
LIKE Operator Description
WHERE CustomerName LIKE ‘___' Matches any string of exactly three
characters
WHERE CustomerName LIKE ‘___%' Matches any string of atleastthree
characters
SQL LIKE Operator
 Find the names of all instructors whose name
includes the substring “dar”.
select name
from instructor
where name like '%dar%'
 Match the string “100%”
like ‘100 \%' escape '\'
in that above we use backslash (\) as the escape
character.
SQL IN Operator

 The IN operator allows you to specify multiple values in a


WHERE clause.
 The IN operator is a shorthand for multiple OR conditions.

IN 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);

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');
SQL IN Operator

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');

SELECT * FROM Customers


WHERE Country NOT IN ('Germany',
'France', 'UK');
SQL IN Operator

SQL statement selects all customers that are from the same
countries as the suppliers:

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);
SQL BETWEEN Operator

 The BETWEEN operator selects values within a given range.


The values can be numbers, text, or dates.
 The BETWEEN operator is inclusive: begin and end values
are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL BETWEEN Operator

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;
SQL Aliases

 SQL aliases are used to give a table, or a column in a table,


a temporary name.
 Aliases are often used to make column names more
readable.
 An alias only exists for the duration of the query.

Alias Column Syntax


 SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


 SELECT column_name(s)
FROM table_name AS alias_name;
SQL Aliases

SELECT CustomerID AS ID, CustomerName AS Customer


FROM Customers;
SQL Aliases

SELECT o.OrderID, o.OrderDate, c.CustomerName


FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the
Horn' AND c.CustomerID=o.CustomerID;
SQL Aliases

Aliases can be useful when:


•There are more than one table involved in a query
•Functions are used in the query
•Column names are big or not very readable
•Two or more columns are combined together
SQL JOIN

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

How to Join two tables in SQL?


 A JOIN works on two or more tables if they have at least one common field and have a relationship
between them
 JOIN keeps the base tables (structure and data) unchanged.

SQL JOINS: EQUI JOIN and NON EQUI JOIN

The are two types of SQL JOINS - EQUI JOIN and NON EQUI JOIN

 1) SQL EQUI JOIN :

The SQL EQUI JOIN is a simple SQL join uses the equal sign(=) as the comparison operator for the

condition. It has two types - SQL Outer join and SQL Inner join.

 2) SQL NON EQUI JOIN :

The SQL NON EQUI JOIN is a join uses comparison operator other than the equal sign like >, <,

>=, <= with the condition .


SQL EQUI JOIN

 (INNER) JOIN: Returns records that have matching values


in both tables
 Outer Join : returns all rows from one table and only
those rows from the secondary table where the joined
condition is satisfying i.e. the columns are equal in both
tables.
 LEFT (OUTER) JOIN: Returns all records from the left
table, and the matched records from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right
table, and the matched records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a
match in either left or right table
SQL EQUI JOIN

.
SQL EQUI JOIN

.
SQL EQUI JOIN

.
SQL EQUI JOIN

SQL EQUI JOIN performs a JOIN against equality or matching column(s)

values of the associated tables. An equal sign (=) is used as comparison

operator in the where clause to refer equality.


SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
OR
SELECT *
FROM table1
JOIN table2
[ON (join_condition)]
SQL EQUI JOIN
Difference between Equi Join and Inner Join in SQL?

 An equijoin is a join with a join condition containing an


equality operator. An equijoin returns only the rows that
have equivalent values for the specified columns.
 An inner join is a join of two or more tables that returns
only those rows (compared using a comparison operator)
that satisfy the join condition.
SQL INNER JOIN

The INNER JOIN keyword selects records that have matching


values in both tables.

INNER JOIN Syntax


 SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL INNER JOIN
SQL INNER JOIN
SELECT table1.column1, table1.column2,
table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column =
table2.matching_column;

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID
AND DEPARTMENT = ‘DEVELOPMENT’;
P_ID EMP_N CITY SALAR AG
NO EMP_ID DEPARTMEN
AME Y E
T
Angelin Chicag
1 200000 30 101 1 Testing
a o
102 2 Development
2 Robert Austin 300000 26
103 3 Designing
Christia
3 Denver 100000 42 104 4 Development
n PROJECT
EMPLOYEE
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID
AND DEPARTMENT = ‘DEVELOPMENT’;
SQL LEFT JOIN

 The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table
(table2). The result is NULL from the right side, if there is no
match.
 Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SQL RIGHT JOIN

The RIGHT JOIN keyword returns all records from the right
table (table2), and the matched records from the left table
(table1). The result is NULL from the left side, when there is no
match.
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
SQL FULL OUTER JOIN

The FULL OUTER JOIN keyword returns all records when there is
a match in left (table1) or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-
sets!
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SQL NON EQUI JOIN

The SQL NON EQUI JOIN uses


comparison operator instead of the
equal sign like >, <, >=, <= along
with conditions.

SELECT * FROM table_name1,


table_name2 WHERE
table_name1.column [> | < | >= |
<= ] table_name2.column;
Natural Join in SQL

The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in


such a way that, columns with the same name of associated tables
will appear once only.
Natural Join: Guidelines
- The associated tables have one or more pairs of identically named
columns.
- The columns must be the same data type.
SELECT * FROM table1 NATURAL JOIN table2;
- Don’t use ON clause in a natural join.
Natural Join in SQL

To get all the unique


columns from foods and
company tables, the
following SQL
statement can be used

SELECT *
FROM foods
NATURAL JOIN
company;
SELECT column_1, column_2...column_n
FROM table_1
NATURAL JOIN table_2;

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE, PROJECT
NATURAL JOIN EMP_ID;

P_ID EMP_N CITY SALAR AG NO EMP_ID DEPARTMEN


AME Y E T
Angelin Chicag 101 1 Testing
1 200000 30
a o 102 2 Development
2 Robert Austin 300000 26 103 3 Designing
Christia 104 4 Development
3 Denver 100000 42
n
Cross Join in SQL

 SQL CROSS JOIN produces a result set which is


SELECT * FROM table1 CROSS JOIN
the number of rows in the first table multiplied table2;

by the number of rows in the second table if


no WHERE clause is used along with CROSS
JOIN. This kind of result is called as Cartesian
Product.
 If WHERE clause is used with CROSS JOIN, it
functions like an INNER JOIN.
 An alternative way of achieving the same
result is to use column names separated by
commas after SELECT and mentioning the

table names involved, after a FROM clause.


Cross Join in SQL
Cross Join in SQL
P_ID EMP_N CITY SALAR AG NO EMP_ID DEPARTMEN
AME Y E T
Angelin Chicag 101 1 Testing
1 200000 30
a o 102 2 Development
2 Robert Austin 300000 26 103 3 Designing
Christia 104 4 Development
3 Denver 100000 42
n
 SELECT EMPLOYEE.EMP_NAME, EMPLOYEE.CITY, EMPLOYEE.SALARY,
EMPLOYEE.AGE, PROJECT.PROJECT_NO
FROM EMPLOYEE
CROSS JOIN PROJECT;
 SELECT EMPLOYEE.EMP_NAME, EMPLOYEE.CITY, EMPLOYEE.SALARY,
EMPLOYEE.AGE, PROJECT.PROJECT_NO
FROM EMPLOYEE
CROSS JOIN PROJECT;
EMP_NAME CITY SALARY AGE PROJECT_NO

Angelina Chicago 200000 30 101

Angelina Chicago 200000 30 102

Angelina Chicago 200000 30 103

Angelina Chicago 200000 30 104


Robert Austin 300000 26 101
Robert Austin 300000 26 102
Robert Austin 300000 26 103
Robert Austin 300000 26 104
Christian Denver 100000 42 101

Christian Denver 100000 42 102

Christian Denver 100000 42 103

Christian Denver 100000 42 104


SQL UNION Operator

The UNION operator is used to combine the result-set of two or


more SELECT statements.
Each SELECT statement within UNION must have the same
number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the
same order
Syntax:
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
SQL UNION Operator
SQL UNION ALL Operator
SQL Group By

The GROUP BY statement groups rows that have the same


values into summary rows, like "find the number of customers in
each country".
The GROUP BY statement is often used with aggregate functions
(COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or
more columns.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE


keyword could not be used with aggregate functions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;
The 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.
functions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
SQL ANY and ALL Operators

 The Any and All operators allow you to perform a comparison


between a single column value and range of other values.
 The ANY and ALL operators are used with a WHERE or HAVING
clause.
 The ANY operator returns true if any of the subquery values
meet the condition.
 ANY operator
 returns a boolean value as a result
 Returns true if any of the subquery values meet the
condition.
 means that the condition will be true if the operation is
true for any of the values in the range.

Note: The operator must be a standard comparison operator


(=, <>, !=, >, >=, <, or <=).

ANY Syntax:
SQL ANY and ALL Operators

ANY Syntax:
SELECT column_
name(s)
FROM table_na
me
WHERE column_
name
operator ANY
(SELECT column FROM Products
SELECT ProductName
WHERE ProductID = ANY (SELECT ProductID
_name outp
FROM OrderDetails WHERE Quantity = 10);
FROM table_na ut
me WHERE
condition);
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
ANY means that the condition will be true if the operation is true for any of the values in the range.
ANY means that the condition will be true if the operation is true for any of the values in the range.

SQL ANY and ALL Operators

 ALL operator returns true if all of the subquery values meet


the condition.
LL operator:
 boolean value as a result
ns a
ns TRUE if ALL of the subquery values meet the condition
d with SELECT, WHERE and HAVING statements

ALL Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
SQL ANY and ALL Operators

SELECT column_
name(s)
FROM table_na
me
WHERE column_
name
operator ALL
(SELECT column
_name
FROM
SELECTtable_na
ProductName FROM Products
me WHERE cond = ALL (SELECT ProductID
WHERE ProductID
ition);
FROM OrderDetails WHERE Quantity = 10);
outp
ut
SQL Views

 A view is nothing more than a SQL statement that is stored in


the database with an associated name.
 view is a virtual table based on the result-set of an SQL
statement.
 A view can contain all rows of a table or select rows from a
table. A view can be created from one or many tables which
depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the
following −
- Structure data in a way that users or classes of users find
natural or intuitive.
SQL Views

Creating Views
 Database views are created using the CREATE
VIEW statement. Views can be created from a single table,
multiple tables or another view.
 To create a view, a user must have the appropriate system
privilege according to the specific implementation.

CREATE VIEW syntax


CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Creating Views

CREATE VIEW syntax


CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Creating Views
A view can be updated with the CREATE OR REPLACE VIEW command.
SQL Updating a View

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
A view is deleted with the DROP VIEW command.
SQL Dropping a View

Syntax:

DROP VIEW view_name;


The WITH CHECK OPTION

The WITH CHECK OPTION is a CREATE VIEW statement option.


The purpose of the WITH CHECK OPTION is to ensure that all
UPDATE and INSERTs satisfy the condition(s) in the view
definition.
If they do not satisfy the condition(s), the UPDATE or INSERT
returns an error.
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS WHERE age IS NOT NULL WITH CHECK OPTION;

creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION.

The WITH CHECK OPTION in this case should deny the entry of
any NULL values in the view's AGE column, because the view is
defined by data that does not have a NULL value in the AGE
column.
To Display all the tables of current user
Cursors

 In SQL, a cursor is a temporary workstation that is allocated by the database server


during the execution of a statement.
 While SQL is generally optimized for set-based operations, there are scenarios where
row-level operations are required.
 It is a database object that allows us to access data of one row at a time. This concept
of SQL is useful when the user wants to update the rows of the table one by one.
 A cursor in SQL is a temporary memory or workspace allocated by the database
server to process DML (Data Manipulation Language) operations. It allows
processing query results from row-by-row instead of applying operations to the
entire set.
Cursors are especially useful for:

• Performing complex row-by-row operations.


• Iterating over result sets for conditional
updates or transformations.
• Handling hierarchical or recursive data
structures.
Types of Cursor in SQL
Implicit Cursor
 These types of cursors are generated and allocated by the SQL server when the system performs
INSERT, DELETE, and UPDATE operations on SQL queries.
 This cursor is also referred to as the default cursor in SQL.
 An implicit cursor is also created by the system when the SELECT query selects the single row.
 Implicit cursors are good for getting info about the data changed, like how many rows were updated or
the last ID inserted.
 This cursor holds the data to be inserted or identifies the rows to be updated or deleted.

•Usage : Managed entirely by the SQL engine without explicit declaration.


•Attributes:
•%FOUND: True if the SQL operation affects at least one row.
•%NOTFOUND: True if no rows are affected.
•%ROWCOUNT: Returns the number of rows affected.
•%ISOPEN: Checks if the cursor is open.
Types of Cursor in SQL

Explicit Cursor
 These types of cursors are created by the user using the SELECT query.
 An explicit cursor holds multiple records but processes a single row at a
time. It uses the pointer, which moves to another row after reading one row.
 It is basically used for gaining extra control over the temporary workstation.
 With explicit cursors, developers can fetch data from a query, go through
each row, and work on it individually. They offer more control and are perfect
for complex tasks or when you need to process data row by row.
Advantages of Using Cursors
in Database Management
 They are a key tool for developers and database admins. They help you get and change
data efficiently, boosting database performance in certain cases.
 Cursors also make data manipulation easier. You can update or delete rows based on
certain rules. This is crucial for changing data in a targeted way, like updating records or
removing old data.
 Also, cursors help with complex data tasks. You can go through data sets, do math, or apply
rules to each row. This makes it easier to handle complex data changes that regular SQL
queries can’t handle.
How Cursor works?
Declaring a Cursor

 The first step is declaring a cursor. You define its name, the SQL statement it will

run, and any parameters needed. This stage sets up the cursor’s role and its scope.

CURSOR <cursorName> IS SELECT <Required fields> FROM


<tableName>;

Opening a Cursor

 After declaring, you must open the cursor. Opening it allocates memory and runs

the SQL statement. It gets ready to fetch data from the result set.
OPEN <cursorName>;
How Cursor works?
Fetching Data with a Cursor
 With the cursor open, you can start fetching data. The data fetching process gets rows from the

result set one by one. You can move through the result set using FETCH NEXT, FETCH PRIOR,

FETCH FIRST, and FETCH LAST, as needed.


FETCH <cursorName> INTO <Respective columns>

FETCH FIRST FROM Cursor_Name;

FETCH LAST FROM Cursor_Name;

FETCH NEXT FROM Cursor_Name;

FETCH PRIOR FROM Cursor_Name;


FETCH ABSOLUTE n FROM Cursor_Name;
How Cursor works?
Fetching Data with a Cursor

 With the cursor open, you can start fetching data. The data fetching process gets rows from

the result set one by one. You can move through the result set using FETCH NEXT, FETCH

PRIOR, FETCH FIRST, and FETCH LAST, as needed .


FETCH <cursorName> INTO <Respective columns>

Closing a Cursor

 When you’re done fetching data, close the cursor. Closing it frees up memory and ends the
CLOSE <cursorName>;
cursor’s lifecycle. Not closing it can cause resource leaks and harm database performance.
To SQL CREATE INDEX Statement

 The CREATE INDEX statement is used to create indexes in tables.


 Indexes are special lookup tables that the database search
engine can use to speed up data retrieval.
 It works by creating a separate data structure that provides
pointers to the rows in a table, making it faster to look up rows
based on specific column values.
 Indexes are used to retrieve data from the database more quickly
than otherwise.
 The users cannot see the indexes, they are just used to speed up
searches/queries.
 An index in a database is very similar to an index in the back of a
book.
Deallocate Cursor
Memory
 The final step is to deallocate the cursor to free up server memory.
 The DEALLOCATE statement removes the cursor definition and its
associated resources from the memory.
 The DEALLOCATE statement completely removes the cursor s1
from memory, ensuring efficient resource usage.

DEALLOCATE cursor_name
Example : Implicit Cursor

BEGIN
FOR emp_rec IN SELECT * FROM emp LOOP
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.ename);
END LOOP;
END;
Example: Using an Explicit Cursor

DECLARE emp_cursor CURSOR FOR SELECT Name, Salary FROM Employees;

BEGIN
-- Open the cursor
OPEN emp_cursor;

-- Fetch rows from the cursor


FETCH NEXT FROM emp_cursor INTO @Name, @Salary;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Name: ' + @Name + ', Salary: ' + CAST(@Salary AS VARCHAR);
FETCH NEXT FROM emp_cursor INTO @Name, @Salary;
END;

-- Close the cursor


CLOSE emp_cursor;

-- Deallocate the cursor


DEALLOCATE emp_cursor;
END;
Using Implicit Cursor for Bulk
Updates

DECLARE
total_rows number;
BEGIN
UPDATE Emp
SET Salary = Salary + 1500;

total_rows := SQL%ROWCOUNT;

dbms_output.put_line(total_rows || ' rows updated.');


END;
 In addition to these attributes,
%BULK_ROWCOUNT and %BULK_EXCEPTIONS are specific to the FOR ALL
statement, which is used to perform multiple DML operations at once.

 %BULK_ROWCOUNT returns the number of rows affected by each DML


operation,
 %BULK_EXCEPTION returns any exception that occurred during the operations.
SQL Cursor Exceptions

1. Duplicate Value Error


 This error occurs when the cursor attempts to insert a record or row
that already exists in the database, causing a conflict due to
duplicate values.
 Solution: Use proper error handling mechanisms such as TRY-
CATCH blocks or check for existing records before inserting data.
2. Invalid Cursor State
 This error is triggered when the cursor is in an invalid state, such as
attempting to fetch data from a cursor that is not open or already
closed.
 Solution: Ensure the cursor is properly opened before fetching data
and closed only after completing all operations.
SQL Cursor Exceptions

3. Lock Timeout
• This happens when the cursor tries to obtain a lock on a row or table,
but the lock is already held by another transaction for an extended
time.
• Solution: Use appropriate isolation levels, manage transactions
efficiently, and minimize locking duration to prevent timeouts.
Advantages of Using
Cursors
1. Row-by-Row Processing: Cursors allow data to be processed
row-by-row, which is particularly useful for tasks requiring detailed
and individualized operations, such as complex calculations or
transformations.
2. Iterative Data Handling: With cursors, we can iterate over a
result set multiple times, making it ideal for scenarios where
repeated operations are necessary on the same data.
3. Working with Complex Relationships: Cursors make it easier
to handle multiple tables with complex relationships, such as
hierarchical data structures or recursive queries.
4. Conditional Operations: Cursors are effective for performing
operations like updates, deletions, or inserts based on specific
conditions.
5. Processing Non-Straightforward Relationships: When the
relationships between tables are not straightforward or set-based
operations are impractical, cursors provide a flexible alternative.
Limitations of Cursors
While cursors are helpful in certain scenarios, they come with notable
limitations, and alternatives should be explored whenever possible:
1. Performance Overhead: Cursors process one row at a time,
which can be significantly slower compared to set-based operations
that handle all rows at once.
2. Resource Consumption: Cursors impose locks on tables or
subsets of data, consuming server memory and increasing the risk of
resource contention.
3. Increased Complexity: Managing cursors requires explicit
declarations, opening, fetching, closing, and deallocating, which adds
to the complexity of the SQL code.
4. Impact of Large Datasets: The performance of cursors decreases
with the size of the dataset, as larger rows and columns require more
resources and time to process.
Syntax:
CREATE INDEX Statement

CREATE INDEX index_name ON


table_name;
Single-Column Indexes
A single-column index is created based on only one table
column
CREATE INDEX idx_product_id
CREATE INDEX
ON Sales (product_id); index_name ON table_name
(column_name);
CREATE INDEX idx_product_quantity
ON Sales (product_id, quantity);
CREATE INDEX Statement

Uniqdexes
Unique indexes are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the
table.
CREATE UNIQUE INDEX index_name on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table
CREATE INDEX index_name on table_name (column1, column2);
Implicit Indexes
Implicit indexes are indexes that are automatically created by the
database server when an object is created. Indexes are
automatically created for primary key constraints and unique
constraints.
When should indexes be created –
SQL INDEX

 A column contains a wide range of values Ex: product IDs or


customer names
 A column does not contain a large number of null values
 One or more columns are frequently used together in a where
clause or a join condition
When should indexes be avoided –
 The table is small
 The columns are not often used as a condition in the query
 The column is updated frequently
SELECT * from USER_INDEXES;
DROP INDEX Command

 An index can be dropped using SQL DROP command.


 Care should be taken when dropping an index because the
performance may either slow down or improve.
DROP INDEX index_name;
Why Indexing in
DBMS ???
 critical feature for optimizing query performance
 Large Data Tables: SQL queries on tables with millions of rows can significantly slow down due

to full table scans. Indexes provide a faster alternative by allowing quick access to relevant rows.
 Join Optimization: Indexes on columns used for joining tables (such as foreign keys) improve

the performance of complex joins.


 Search Operations: Queries that search for specific values in a column can be sped up with

indexes, reducing the time required to perform lookups.

4. However, it is essential to be mindful of the storage cost and performance tradeoffs associated

with indexes. Over-indexing can lead to unnecessary overhead, while under-indexing may slow

down data retrieval


TCL Commands

 Transaction Control Language(TCL) commands are used to manage


transactions in the database.
 These are used to manage the changes made to the data in a table
by DML statements.
 It also allows statements to be grouped together into logical
transactions.

Commit Command
COMMIT command is used to permanently save any
transaction into the database.
Syntax:
COMMIT;
TCL Commands

ROLLBACK command
- restores the database to last commited state. It is also used with
savepoint command to jump to a savepoint in an ongoing
transaction.
Syntax
ROLLBACK TO savepoint_name;

Savepoint Command:
command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
Syntax
SAVEPOINT savepoint_name;
TCL Commands
id name
1 Abhi
2 Adam
4 Alex

INSERT INTO class VALUES(5, 'Rahul');

COMMIT;

UPDATE class SET name = 'Abhijit' WHERE id = '5';

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;
TCL Commands

 SELECT * FROM class;


id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
TCL Commands
ROLLBACK TO B;

SELECT * FROM class;

d name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
TCL Commands
ROLLBACK TO A;

SELECT * FROM class;

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit

You might also like