Module 4 SQL

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

MODULE NO:-4

Structured query Language (SQL):


4.1. Overview of SQL
4.2 Data Définition Command,
4.3. Data Manipulation command,
4.4. Data Control command,
4.5. Transaction Control Command
4.6. Set and string operations, aggregate function -
group by, having.
4.7. Views in SQL, joins , Nested and complex queries,
4.8. Integrity constraints :- key constraints, Domain
Constraints, Referential integrity , check constraints .
MODULE NO:-4
Structured query Language (SQL):
 SQL stands for Structured Query Language. It
is used for storing and managing data in
relational database management system
(RDMS).
 It is a standard language for Relational
Database System. It enables a user to create,
read, update and delete relational databases
and tables.
 All the RDBMS like MySQL, Informix, Oracle,
MS Access and SQL Server use SQL as their
MODULE NO:-4
Structured query Language (SQL):
SQL Sub Languages

 DDL – Data Definition Language.


 DML – Data Manipulation
Language.
 DRL/DQL – Data Retrieval
Language/Data Query Language.
 TCL – Transaction Query Language.
 DCL – Data Control Language.
MODULE NO:-4
Structured query Language (SQL):
Structured query Language (SQL):
DDL: Data Definition Language
This includes changes to the structure of the table like
creation of table, altering table, deleting a table etc.
All DDL commands are auto-committed. That means it
saves all the changes permanently in the database.
Comm Description
and
create to create new table
or database
alter for alteration
trunca delete data from
te table
drop to drop a table
Structured query Language (SQL):
DML: Data Manipulation Language
• DML commands are used for manipulating the data
stored in the table and not the table itself.
• DML commands are not auto-committed. It means
changes are not permanent to database, they can be
rolled back.
Comma
Description
nd
insert to insert a new row
update to update existing row
delete to delete a row
Structured query Language (SQL):
TCL: Transaction Control Language
These commands are to keep a check on other
commands and their affect on the database. These
commands can annul changes made by other
commands by rolling the data back to its original state.
It can also make any temporary
Command change permanent.
Description
to
commit permanently
save
to undo
rollback
change
to save
savepoint
temporarily
Structured query Language (SQL):
DCL: Data Control Language
Data control language are the commands to
grant and take back authority from any database
user.
Command Description
grant grant permission
of right
revoke take back
permission.
Structured query Language (SQL):
DQL: Data Query Language
Data query language is used to fetch data
from tables based on conditions that we can
easily apply.
Command Description
select retrieve records from one
or more table
Structured query Language (SQL):
Datatype of SQL:
Structured query Language (SQL):
Datatype of SQL:
2. Approximate Numeric
Datatype :
The subtypes are given
Data From To Description
below:
type
float -1.79E + 1.79E + It is used to specify a floating-
308 308 point value e.g. 6.2, 2.9 etc.
real -3.40e + 3.40E + It specifies a single precision
38 38 floating point number
Structured query Language (SQL):
Datatype of SQL:
3. Exact Numeric Datatype
The subtypes are given below:

Data Description
type
int It is used to specify an integer value.
smallint It is used to specify small integer
value.
bit It has the number of bits to store.
decimal It specifies a numeric value that can
have a decimal number.
Structured query Language (SQL):
Datatype of SQL:
4. Character String Datatype
The subtypes are given below:
Data Description
type
char It has a maximum length of 8000
characters. It contains Fixed-length non-
unicode characters.
varchar It has a maximum length of 8000
characters. It contains variable-length
non-unicode characters.
text It has a maximum length of
2,147,483,647 characters. It contains
Structured query Language (SQL):
Datatype of SQL:
Date and time Datatypes
Datatype Description
date It is used to store the year,
month, and days value.
time It is used to store the hour,
minute, and second values.
timestamp It stores the year, month, day,
hour, minute, and the second
value.
Data Definition
Language (DDL)-Syntax
Here are some commands that come
under DDL:
•CREATE
•ALTER
•DROP
•TRUNCATE
Data Definition
Language (DDL)-Syntax
a. CREATE It is used to create a new table in
the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NA
ME DATATYPES[,....]);

Example:
CREATE TABLE EMPLOYEE
(Name VARCHAR(20),
Email VARCHAR(100),
DOB DATE);
Data Definition
Language
b. DROP: (DDL)-Syntax
It is used to delete both the structure
and record stored in the table.
Syntax
1.DROP TABLE TABLE-
NAME;
Example
1.DROP TABLE EMPLOYEE;
Data Definition
Language (DDL)-Syntax
c. ALTER: It is used to alter the structure of the
database. This change could be either to modify the
characteristics of an existing attribute or probably to add
a new attribute.

Syntax:
To add a new column in the table
1.ALTER TABLE table_name ADD column_name COL
Example:-
UMN-definition;
ALTER TABLE Employee ADD
Phone_nO INT
Data Definition
Language (DDL)-Syntax
c. ALTER: It is used to alter the structure of the
database. This change could be either to modify the
characteristics of an existing attribute or probably to add
a new attribute.

Syntax:
To modify existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION....);
Example:-
ALTER TABLE Employee MODIFY
Phone_nO VARCHAR(10)
Data Definition
Language (DDL)-Syntax
c. ALTER: It is used to alter the structure of the
database. This change could be either to modify the
characteristics of an existing attribute or probably to add
a new attribute.

Syntax:
To DROP existing column in the table:
ALTER TABLE DROP(COLUMN NAME....);
Example:-
ALTER TABLE Employee DROP Phone_nO
Data Definition
Language (DDL)-Syntax
d. TRUNCATE: It is used to delete all the rows
from the table and free the space containing the
table.
Syntax:
1.TRUNCATE TABLE table_name;
Example:
1.TRUNCATE TABLE EMPLOY
EE;
2. Data Manipulation Language

•DML commands are used to modify the database.


It is responsible for all form of changes in the
database.
•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.

Here are some commands that come under DML:


•INSERT
•UPDATE
2. Data Manipulation Language

a. INSERT:
The INSERT statement is a SQL query. It is used to insert
data into the row of a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME VALUES (value1, value2, value
3, .... valueN);
2. Data Manipulation Language

Example:-
INSERT INTO employee VALUES
('RAVI','[email protected]','1990-10-18’)
Or
INSERT INTO `employee`(`Name`, `Email`,
`DOB`)
VALUES ('RAVI','[email protected]','1990-10-18')
2. Data Manipulation Language
b. UPDATE: This command is used to update or modify
the value of a column in the table.
Syntax:
UPDATE table_name
SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION]

Example:-
UPDATE employee
SET Email=‘[email protected]
Where Name=‘SANJAY’
2. Data Manipulation Language

c. DELETE: It is used to remove one or


more row from a table.
Syntax:
DELETE FROM table_name [WHERE conditio
n];
Example:-
DELETE FROM employee
where Name=‘SANJAY’

Example:-
DELETE FROM employee
3. Data Control Language

DCL commands are used to grant and


take back authority from any database
user.

Here are some commands that come


under DCL:
•Grant
•Revoke
3. Data Control Language

a. Grant: It is used to give user access


privileges to a database.
Example
GRANT SELECT, UPDATE ON MY_TABLE TO S
OME_USER, ANOTHER_USER;

b. Revoke: It is used to take back


permissions from the user.
Example
4. Transaction Control Language
TCL commands can only use with DML commands
like INSERT, DELETE and UPDATE only.

These operations are automatically committed in


the database that's why they cannot be used
while creating tables or dropping them.

Here are some commands that come under TCL:

COMMIT
ROLLBACK
4. Transaction Control Language
a. Commit: Commit command is used to save all
the transactions to the database.

Syntax:
COMMIT;

Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
4. Transaction Control Language
Rollback: Rollback command is used to
undo transactions that have not
already been saved to the database..

Syntax:
ROLLBACK;

Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
4. Transaction Control Language

c. SAVEPOINT: It is used to roll the


transaction back to a certain point without
rolling back the entire transaction.

Syntax:
SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.

It uses only one command:


SELECT

a. SELECT: This is the same as the projection operation


of relational algebra. It is used to select the attribute
based on the condition described by WHERE clause.
Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;
5. Data Query Language
Syntax:
SELECT columns/function
FROM TABLES
WHERE conditions;

Example:-
SELECT Fname,Ssn,Salary
FROM employee
Where Dno=5;
SQL Constraints

Constraints are the rules enforced on the data


columns of a table. These 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 database.

Constraints could be either on a column level or


a table level. The column level constraints are
applied only to one column, whereas the table
level constraints are applied to the whole table.
SQL Constraints
The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a


NULL value
 UNIQUE - Ensures that all values in a column are
different
 PRIMARY KEY - A combination of a NOT NULL and
UNIQUE. Uniquely identifies each row in a table
 FOREIGN KEY - Uniquely identifies a row/record in
another table
 CHECK - Ensures that all values in a column satisfies
a specific condition
SQL Constraints
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:
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
SQL Constraints
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


The following SQL creates a UNIQUE constraint on the "ID"
column when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
SQL Constraints
 To name a UNIQUE constraint, and to define a UNIQUE 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 UC_Person UNIQUE (ID,LastName));

 SQL UNIQUE Constraint on ALTER TABLE


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

ALTER TABLE Persons ADD UNIQUE (ID);

 To name a UNIQUE constraint, and to define a UNIQUE constraint


on multiple columns, use the following SQL syntax:
SQL Constraints
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


The following SQL creates a PRIMARY KEY on the "ID" column
when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
SQL Constraints
 SQL PRIMARY KEY on ALTER TABLE
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);

 DROP a PRIMARY KEY Constraint , To drop a PRIMARY


KEY constraint, use the following SQL:
SQL Constraints
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.
Person table
SQL Constraints
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 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,
 To create a FOREIGN KEY constraint on the "PersonID" column
when the "Orders" table is already created, use the following SQL:

ALTER TABLE Orders ADD FOREIGN KEY (PersonID)


REFERENCES Persons(PersonID);
 To allow naming of a FOREIGN KEY constraint, and for defining a
FOREIGN KEY constraint on multiple columns, use the following
SQL syntax:

ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder


FOREIGN KEY (PersonID) REFERENCES
DROP a FOREIGN KEY Constraint
Persons(PersonID);
To drop a FOREIGN KEY constraint, use the
following SQL:
ALTER TABLE Orders DROP FOREIGN KEY
FK_PersonOrder;
SQL CHECKSQL Constraints
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
SQL
the CHECK on CREATE TABLE
row.
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));
SQL Constraints
SQL CHECK Constraint
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 Constraints
SQL CHECK Constraint
 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);

 DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;


SQL Constraints
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.

SQL DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City"
column when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes');
SQL Constraints
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in
tables.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.
Note: Updating a table with indexes takes more time than
updating a table without (because the indexes also need an
update). So, only create indexes on columns that will be
frequently searched against.

CREATE INDEX Syntax Creates an index on a table.


Duplicate values are allowed:
SQL Constraints
 CREATE INDEX Example
The SQL statement below creates an index named
"idx_lastname" on the "LastName" column in the "Persons"
table:
CREATE INDEX idx_lastname ON Persons (LastName);
 If you want to create an index on a combination of
columns, you can list the column names within the
parentheses, separated by commas:

CREATE INDEX idx_pname ON Persons


(LastName, FirstName);
 DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.
Integrity constraints :
 Integrity constraints are a set of rules. It is used
to maintain the quality of information.
 Integrity constraints ensure that the data
insertion, updating, and other processes have to
be performed in such a way that data integrity is
not affected.
 Thus, integrity constraint is used to guard
against accidental damage to the database.
Integrity constraints :

-
Integrity constraints :
Domain constraints
 Domain constraints can be defined as the
definition of a valid set of values for an attribute.
 The data type of domain includes string,
character, integer, time, date, currency, etc.
 The value of the attribute must be available in
the corresponding domain.
Integrity constraints :
Entity integrity constraints
 The entity integrity constraint states that
primary key value can't be null.
This is because the primary key value is used to
identify individual rows in relation and if the
primary key has a null value, then we can't identify
those rows.
 A table can contain a null value other than the
primary key field.
Integrity constraints :
Referential Integrity Constraints
 A referential integrity constraint is specified between
two tables.
 In the Referential integrity constraints, if a foreign key
in Table 1 refers to the Primary Key of Table 2, then
every value of the Foreign Key in Table 1 must be null
or be available in Table 2.
Integrity constraints :
Key constraints
 Keys are the entity set that is used to identify
an entity within its entity set uniquely.
 An entity set can have multiple keys, but out of
which one key will be the primary key. A
primary key can contain a unique and null value
in the relational table.
Structured Query Language (SQL)
 Syntax
 Simple query example
 Simple query –string operation
 Simple Query--Set operations
 Simple Query--Arithmetic Operation
Structured Query Language (SQL)-
Syntax
SQL SELECT Statement

SELECT column1, column2....columnN FROM


table_name/table_names;
SQL WHERE Clause
SELECT column1, column2....columnN FROM table_name/ table_names
WHERE CONDITION;
SQL AND/OR Clause
SELECT column1, column2....columnN FROM table_name/
table_names
WHERE CONDITION-1 {AND|OR} CONDITION-2;
Structured Query Language (SQL)-Examples

Example-1 Retrieve Name and


Surname of the Students
Structured Query Language (SQL)-Examples

Example-2 Retrieve Students

Select *
from
Students;
Structured Query Language (SQL)-Examples
Example 3:-Retrieves the students
whose age is bigger and equal to 20.
Structured Query Language (SQL)-String Operation

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
 _ - The underscore represents a single
character

LIKE Syntax:-
SELECT column1, column2, ...
FROM table_name
Structured Query Language (SQL)-String
Operation-Examples

:-Retrieve the students whose names start with J character

SELECT * FROM Student


WHERE Name LIKE 'J%'
Structured Query Language (SQL)-String
Operation-Examples

:-selects all customers with a CustomerName starting with "a

CUSTOME
R

SELECT * FROM
Customers WHERE
CustomerName
LIKE 'a%';
Structured Query Language (SQL)-String
Operation-Examples
Example 6:-Selects all customers with a
CustomerName that have "or" in any position
CUSTOME
R

SELECT * FROM
Customers
WHERE
CustomerName LIKE
'%or%';
Structured Query Language (SQL)-String
Operation-Examples
Example 7:-Selects all customers with a
CustomerName that have "r" in the second position:
CUSTOME
R

SELECT * FROM
Customers
WHERE
CustomerName LIKE
'_r%';
Structured Query Language (SQL)-String
Operation-Examples
Example 8:-selects all customers with a
CustomerName that starts with "a" and are at least 3
characters in length:
CUSTOME
R

SELECT * FROM
Customers
WHERE CustomerName
LIKE 'a__%';
Structured Query Language (SQL)-String
Operation-Examples
Example 9:-selects all customers with a
ContactName that starts with "a" and ends with "o":

CUSTOME
R

SELECT * FROM
Customers
WHERE ContactName
LIKE 'a%o';
Structured Query Language (SQL)-String
Operation-Examples
Example 10:-Selects all customers with a
CustomerName that does NOT start with "a":

CUSTOME
R

SELECT * FROM
Customers
WHERE CustomerName
NOT LIKE 'a%';
Structured Query Language (SQL)- Simple
Query--Set operations

SQL supports few Set operations which can be


performed on the table data.
These are used to get meaningful results from
data stored in the table, under different special
conditions.

we will cover 4 different types of SET


operations, along with example:
1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS
Structured Query Language (SQL)- Simple
Query--Set operations

SQL | Union Clause


The Union Clause is used to combine two
separate select statements and produce the
result set as a union of both the select
statements.

NOTE:
1.The fields to be used in both the select
statements must be in same order, same
number and same data type.
2.The Union clause produces distinct values in
the result set, to fetch the duplicate values too
Structured Query Language (SQL)-
Simple Query--Set operations
Basic Syntax:
SELECT column_name(s)
FROM table1
UNION
SELECT column_name(s)
FROM table2;
Resultant set consists of distinct values.
SELECT column_name(s)
FROM table1
UNION ALL
SELECT column_name(s)
FROM table2;
Resultant set consists of duplicate values too .
Structured Query Language (SQL)-
Simple Query--Set operations
Structured Query Language (SQL)-
Simple Query--Set operations

Example 11:-To fetch distinct ROLL_NO from


Student and Student_Details table
Stude SELECT ROLL_NO FROM Student
nt Student _Details
UNION
SELECT ROLL_NO FROM
Student_Details;
Structured Query Language (SQL)-
Simple Query--Set operations

Example 11:-To fetch distinct ROLL_NO from


Student and Student_Details table
Stude SELECT ROLL_NO FROM Student
nt Student _Details
UNION ALL
SELECT ROLL_NO FROM
Student_Details;
Structured Query Language (SQL)- Simple
Query--Set operations
INTERSECT clause :
As the name suggests, the intersect clause is used to
provide the result of the intersection of two select
statements. This implies the result contains all the rows
which are common to both the
Syntax : SELECT statements.
SELECT column-1, column-2 ……FROM table 1
WHERE…..
INTERSECT
SELECT column-1, column-2 …… FROM table 2
WHERE…. .
Structured Query Language (SQL)- Simple
Query--Set operations

Example 12:-Retrieves the salary which are


SELECT
common SALARY FROM10
in department employees
and 20. WHERE
DEPARTMENT_ID = 10
INTRESECT
SELECT SALARY FROM employees WHERE
DEPARTMENT_ID = 20
Structured Query Language (SQL)- Simple
Query--Set operations

MINUS
Minus operator displays the rows which are present in
the Example:-
first query but absent in the second query, with no
duplicates and data arranged in ascending order by
SELECT JOB_ID FROM employees WHERE
default.
DEPARTMENT_ID = 10
MINUS
SELECT JOB_ID FROM employees WHERE
DEPARTMENT_ID = 20;
Structured Query Language (SQL)
 Syntax
 Simple query example
 Simple query –string operation
 Simple Query--Set operations
 Simple Query--Arithmetic Operation
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation

The 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;
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example1:-selects all products with a price
BETWEEN 10 and 20:

SELECT * FROM Products WHERE Price


BETWEEN 10 AND 20;
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example 2:-selects all products with a price NOT
IN BETWEEN 10 and 20:

SELECT * FROM Products WHERE Price NOT


BETWEEN 10 AND 20;
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example 3:-selects all products with a price NOT
IN BETWEEN 10 and 20:

SELECT * FROM Products WHERE Price NOT


BETWEEN 10 AND 20;
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example 4:-Show the resulting salaries if every employee
working on the ‘ProductX’ project is given a 10 percent
raise.

SELECT E.Fname, E.Lname, 1.1 *


E.Salary AS Increased_sal FROM
EMPLOYEE AS E, WORKS_ON AS
W, PROJECT AS P WHERE
E.Ssn=W.Essn AND
E.Fname E.Lname
W.Pno=P.Pnumber AND Increased Sal
John Smith
P.Pname=‘ProductX’; 33000
Jyoce English 27500
Structured Query Language (SQL)-Simple Query--
Arithmetic Operation
Example 5:-Give all employees in the department number
‘5’ a 10 percent raise in salary

Ssn Salary
123456 33000
789
333445 44000
555
UPDATE 999887 25000
777
EMPLOYEE
SET Salary = 987654 43000
321
Salary * 1.1
666884 41800
WHERE Dno
Aggregate Functions

Aggregate Functions
These functions return a single value after
performing calculations on a group of values.
Following are some of the frequently used Aggregate
functions.
AVG() Function
Average returns average value after calculating it
from values in a numeric column.
Its general syntax is,

SELECT AVG(column_name) FROM table_name;


Aggregate Functions

mple:-SQL query to find average salary will be,


Aggregate Functions

SQL query to count employees, satisfying specified condition


Aggregate Functions

FIRST() Function
First function returns first value of a selected column
Aggregate Functions
LAST() Function
LAST function returns the return last value of the
selected column.
MAX() Function
MAX function returns maximum value from
selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-
name;

MIN() Function
MIN function returns minimum value from a
selected column of the table.
Syntax for MIN function is
SELECT MIN(column_name) from table-name;

SUM() Function
SUM function returns total sum of a selected
columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name;
IN clause usage
AND ,OR operators in where clause
NOT IN Clause
Problem: List products with order quantities
greater than 100.

SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId
FROM
OrderItem
WHERE
Quantity > 100)
EXAMPLE-2
Return the details of only those customers
whose order value in the orders table is more
than 5000 dollar

SELECT *
FROM customers
WHERE cust_id IN (SELECT
DISTINCT cust_id
FROM
orders
WHERE
order_value > 5000);
SQL ORDER
Ordering BYResult
the Clause Set
Generally when you use the SELECT statement to fetch data from a
table, the rows in result set are not in any particular order. If you
want your result set in a particular order, you can specify the
ORDER BY clause at the end of the statement which tells the
server how to sort the data returned by the query. The default
sorting order is ascending.
Syntax
The ORDER BY clause is used to sort the data returned by a
query in ascending or descending order. The basic syntax of this
clause can be given with:

SELECT column_list FROM table_name ORDER BY


column_name ASC|DESC;
Add a Slide Title - 5
Sorting Multiple Columns
The SQL GROUP BY Statement

The GROUP BY Statement in SQL is used to arrange


identical data into groups with the help of some
functions. i.e if a particular column has same values in
different rows then it will arrange these rows in a group.

Points to Remember:
GROUP BY Clause is utilized with the SELECT statement.
GROUP BY aggregates the results on the basis of
selected column: COUNT, MAX, MIN, SUM, AVG, etc.
GROUP BY returns only one result per group of data.
GROUP BY Clause always follows the WHERE Clause.
GROUP BY Clause always precedes the ORDER BY
GROUP BY Clause
Ex:-Table is grouped based on the DeptID column and
Salary is aggregated department-wise.
The SQL GROUP BY Statement
Syntax:-
SELECT column1,function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;

function_name: Name of the function used for


example, SUM() , AVG(). table_name: Name of
the table.
condition: Condition used.
EXAMPLE-1:Retrieve Sum Of Salary Of
Each Employee
EMPLOYE
E
Example 2:-lists the number of customers
in each country
Example 3:lists the number of customers
in each country, sorted high to low
The SQL HAVING Clause

HAVING Clause utilized in SQL as a conditional Clause with


GROUP BY Clause.
This conditional clause returns rows where aggregate
function results matched with given conditions only.
It added in the SQL because WHERE Clause cannot be
combined with aggregate results, so it has a different
purpose.

The primary purpose of the WHERE Clause is to deal with


non-aggregated or individual records.
•HAVING Clause always utilized in combination with
GROUP BY Clause.
Example:-

Table is grouped based on DeptID column and


these grouped rows filtered using HAVING Clause
with condition AVG(Salary) > 3000.
SQL ANY & ALL OPERATOR

The SQL ANY and ALL Operators


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.
Y Syntax
The ALL operator returns true if all of the subquery
LECT column_name(s)
values meet the condition.
OM table_name
ERE column_name operator ANY
LECT column_name FROM table_name WHERE condition);
SQL ANY & ALL OPERATOR

Syntax
ECT column_name(s)
M table_name
ERE column_name operator ALL
LECT column_name FROM table_name WHERE condition);
EXAMPLE 1:-lists the product names if it finds ANY
records in the OrderDetails table that quantity = 10
EXAMPLE 2:-lists the product names if ALL the records
in the OrderDetails table has quantity = 10
SQL - Alias Syntax

The use of table aliases is to rename a table in a


specific SQL statement. The renaming is a temporary
change and the actual table name does not change in
Syntax
the database.
The column aliases are used to rename a table's
columns for the
 The basic purpose
syntax of a particular
of a table SQL
alias is as query.
follows.
SELECT column1, column2.... FROM table_name AS
alias_name WHERE [condition];

 The basic syntax of a column alias is as follows.


SELECT column_name AS alias_name FROM table_name
WHERE [condition];
Table Alias.

SELECT C.ID, C.NAME, C.AGE,


O.AMOUNT
FROM CUSTOMERS AS C,
ORDERS AS O
WHERE C.ID =
O.CUSTOMER_ID;
Column Alias

SELECT ID AS CUSTOMER_ID, NAME


AS CUSTOMER_NAME FROM
CUSTOMERS
WHERE SALARY IS NOT NULL;
SQL EXAMPLE ON LIBRARY DATABASE
SQL EXAMPLE ON LIBRARY DATABASE

Example 1: List all the


records in the student chart
SOL-Example 1:-
select * from
Example
students 2: List the name surname and class of
the student in the student table
le 2:-select name, surname, class from students

Example 3: List the gender Female


(F) records in the student table
le 3:-select * from students where gender='F'
SQL EXAMPLE ON LIBRARY DATABASE

Example 4 : List the names


of each class in the way of
being seen once in the
Solution ex 4:-select distinct
student table
class from students
Example 5: List the students with Female gender and
the class 10Math in the student table
select * from students where gender='F' and class='10Math'
Example 6: List the names, surnames and classes of the
students in the class 10Math or 10Sci in the student table
Solution ex 6:-select name, surname, class from
SQL EXAMPLE ON LIBRARY DATABASE

Example 7: List the students


name surname and school
number in the student table
Solution-7:-select name,
surname ,studentid as
'number' from students
Example 8: List the students name and surname
by combining them as name surname in the
student table
-select name+surname as 'Name Surname' from students
SQL EXAMPLE ON LIBRARY DATABASE
Example 9: List the students with the names
starting with “A” letter in the student table
Solution:9-select * from
students where name like 'A
Example 10: List the book
%'
names and pages count with
number of pages between 50
and 200 in the book table
lect name from books where pagecount between 50 and 200
Example 11: List the students with names Emma
Sophia and Robert in the student table
Solution 11 :-select * from students
where name in ('Emma','Sophia','Robert')
SQL EXAMPLE ON LIBRARY DATABASE
Example 12: List the
students with names starting
with A D and
Solution K in the student
12:-select *
table
from students where
name like '[ADK]%'
Example 13: List the names surnames classes and genders
of males in 9Math or females in 9His in the student table
Solution 13:-select name, surname, class, gende
from students
where (class='9Math' and gender='M')
or (class='9His' and gender='F')
SQL EXAMPLE ON LIBRARY DATABASE
Example 15: List the students with birth
year 1989 in the student table
Solution 15:-select * from students
where birthdate between '01/01/1989' and
'12/31/1989'
Example 16: List the female
students with student numbers
between
Solution30 and 50 * from students where
16:-select
studentid between 30 and 70 and gender = 'F'
e 17: List the students according to their names
17:-select * from students order by name
SQL EXAMPLE ON LIBRARY DATABASE

Example 18: List the students


by names for those with same
names. List
18:-select them
* from by their
students order by name,surname
surnames
Example 19: List the students
in 10Math by decreasing school
numbers
Solution 19:-select * from students where
class='10Math' order by ogrno desc
e 20: List the first 10 records in the student chart
n 20:-select top 10 * from students
SQL EXAMPLE ON LIBRARY DATABASE

Example 21: List the first 10 records


name surname and date of birth
information
1:-select inname,
top 10 the student tablebirthdate from students
surname,
e 22: List the book with the most page number
select top 1 * from books order by pagecount desc
Example 23: List the youngest student
in the student table
Solution 23:-select top 1 name, surname,
birthdate from students order by birthdate desc
4: List the oldest student in the 10Math class
Solution 24:-select top 1 name,surname,birthdate from
SQL EXAMPLE ON LIBRARY DATABASE
5: List the books with the second letter N
Solution25:-select * from books
where name like '_n%'
SQL EXAMPLE ON LIBRARY DATABASE
SQL UPDATE Queries
Example 26: Change the class of the
student whose school number is 3 from
10Bio to 10His
Solution 26:-update students set
class='10His' where studentid=3 and
class='10Bio'
Example 27: Increase all of the
students’ score
on 27:-update by 5 set
students points
puan=score+5
SQL EXAMPLE ON LIBRARY DATABASE
DATA FROM MULTI TABLE

Example 28: List the name ,surname and the dates


of received books of the student
Solution 28:-select students.name,
students.surname, students.birthdate
from student,borrows
where
students.studentId=borrows.borrowI
d
VIEWS

 A View in SQL as a logical subset of data from one


or more tables.
 Views are used to restrict data access.
 A View contains no data of its own but its like
window through which data from tables can be
viewed or changed.
 The table on which a View is based are called BASE
Tables.
 The SQL VIEW is, in essence, a virtual table that
does not physically exist. Rather, it is created by a
SQL statement that joins one or more tables.
TYPES OF VIEWS

 Simple views can only contain a single


base table.
 Complex views can be constructed on
more than one base table. In particular,
complex views can contain: join
conditions, a group by clause, a order by
clause.
SIMPLE
SIMPLEX VIEW
VS COMPLEX VIEW COMPLEX VIEW
Contains only one single base Contains more than one base
table or is created from only one tables or is created from more
table. than one tables.
We cannot use group functions
We can use group functions.
like MAX(), COUNT(), etc.
Does not contain groups of data. It can contain groups of data.
DML operations could not always
DML operations could be
be performed through a complex
performed through a simple view.
view.
We cannot apply INSERT, DELETE
INSERT, DELETE and UPDATE are
and UPDATE on complex view
directly possible on a simple view.
directly.
Simple view does not contain
It can contain group by, distinct,
group by, distinct, pseudocolumn
pseudocolumn like rownum,
like rownum, columns defiend by
columns defiend by expressions.
CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1, SQL CREATE VIEW Examples
column2, ... Creates a view that shows all
FROM table_name customers from Brazil:
WHERE condition; CREATE VIEW [Brazil
Customers] AS
SELECT CustomerName,
ContactName
FROM Customers
WHERE Country = 'Brazil';
EXAMPLE RELATION
Creating View from a single table(SIMPLEX VIEW)

View named DetailsView from the


table Student_Detail.
CREATE VIEW Deta
ilsView AS
SELECT NAME, ADD
RESS
FROM Student_Det
ails
WHERE STU_ID < 4
;
Creating View from multiple tables(COMPLEX VIEW)

View is created named MarksView from two


tables Student_Detail and Student_Marks
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDR
ESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NA
ME;
Deleting View

Syntax
DROP VIEW view_n
ame;

Example:
If we want to delete the View
MarksView, we can do this as:

DROP VIEW MarksView;


UPDATING VIEWS

There are certain conditions needed to be


satisfied to update a view. If any one of these
conditions is not met, then we will not be allowed
to update the view.

1.The SELECT statement which is used to create


the view should not include GROUP BY clause or
ORDER BY clause.
2.The SELECT statement should not have the
DISTINCT keyword.
3.The View should have all NOT NULL values.
4.The view should not be created using nested
CREATE OR REPLACE VIEW

We can use the CREATE OR REPLACE VIEW statement


to add or remove fields from a view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,..
FROM table_name
WHERE condition
EXAMPLE
Create a View named MarksView from two tables
StudentDetails
CREATE and
VIEW MarksView ASStudentMarks
SELECT StudentDetails.NAME,
StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME =
StudentMarks.NAME;
MarksView
EXAMPLE

Update the view MarksView and add the field


AGE to this View from StudentMarks Table, we
can do OR
CREATE this as:
REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks MarksView
WHERE StudentDetails.NAME = StudentMarks.NAME;
MarksView
We can insert
Inserting a in
a row row in a View in a same way as we
a view
do in a table.
We can use the INSERT INTO statement of SQL to
insert a row in a View.
Syntax :
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
Inserting a row in a view

Create a View named DetailsView


from the table StudentDetails.
CREATE VIEW
DetailsView AS
SELECT NAME,
ADDRESS
FROM StudentDetails
DetailsView
WHERE S_ID < 5;
Inserting a row in a view
Insert a new row in the View DetailsView which we
have created above in the example of “creating
views from a single table”.
INSERT INTO
DetailsView(NAME,
ADDRESS)
VALUES("Suresh","Gurgaon"
);
Deleting a row from a View:
Deleting rows from a view is also as simple as deleting
rows from a table. We can use the DELETE statement of
SQL to delete rows from a view. Also deleting a row from
a view first delete the row from the actual table and the
Syntax :
change is then reflected in the view
DELETE FROM view_name WHERE condition;
Example:
In this example we will delete the last row from the view
DetailsView which we just added in the above example of
inserting rows.

DELETE FROM DetailsView WHERE NAME="Suresh";


Deleting a row from a View:

ETE FROM DetailsView WHERE NAME="Suresh";


DetailsView
OUTPUT
THANK YOU

You might also like