SlideShare a Scribd company logo
RDBMS Concepts
www.webstackacademy.com
What is RDBMS?
www.webstackacademy.com
www.webstackacademy.com
Definition
● RDBMS stands for Relational Database Management System. RDBMS
is the basis for SQL, and for all modern database systems like MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
● A Relational database management system (RDBMS) is a database
management system (DBMS) that is based on the relational model as
introduced by E. F. Codd.
● The data in RDBMS is stored in database objects called tables.
www.webstackacademy.com
Different RDBMS
Technology
www.webstackacademy.com
DBMS & RDBMS
● DBMS applications store
data as file.
● DBMS does not support
client/server architecture.
● DBMS does not allow
normalization.
● DBMS does not impose
integrity constraints.
● RDBMS applications store
data in a tabular form.
● RDBMS supports
client/server architecture.
● RDBMS allows
normalization.
● RDBMS imposes integrity
constraints.
www.webstackacademy.com
Creating Table
www.webstackacademy.com
Creating Table
● The data in RDBMS is stored in database objects called
tables. The table is a collection of related data entries and
it consists of columns and rows.
● Remember, a table is the most common and simplest form
of data storage in a relational database.
www.webstackacademy.com
Field, Record or
Row
● Every table is broken up into smaller entities called fields.
The fields in the CUSTOMERS table consist of ID, NAME,
AGE, ADDRESS and SALARY.
● A record, also called a row of data, is each individual entry
that exists in a table. For example there are 7 records in
the above CUSTOMERS table.
www.webstackacademy.com
Column
● A column is a vertical entity in a table that
contains all information associated with a
specific field in a table.
www.webstackacademy.com
Null Value
● A NULL value in a table is a value in a field that
appears to be blank, which means a field with a
NULL value is a field with no value.
www.webstackacademy.com
SQL
www.webstackacademy.com
SQL
● SQL is a standard language for accessing
databases.
● SQL stands for Structured Query Language
● SQL lets you access and manipulate databases
● SQL is an ANSI (American National Standards
Institute) standard
www.webstackacademy.com
Benefit of SQL
● SQL can execute queries against a database
● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
www.webstackacademy.com
Using SQL in your
Project
To build an application that shows data from a
database, you will need:
● An RDBMS database program (i.e. MS Access, SQL Server,
MySQL)
● To use a server-side scripting language, like Java, PHP or ASP
● To use SQL to get the data you want
● To use HTML / CSS
www.webstackacademy.com
SQL Data Types
● Number Data types :-
- INTEGER :- The Integer data type is used to
specify an integer value.
- SMALLINT :- The SMALLINT data type is used to
specify small integer value.
- NUMERIC(P,S) :-It specifies a numeric value. Here
'p' is precision value and 's' is a scale value.
www.webstackacademy.com
SQL Data Types
● Float Types :
- FLOAT(P) - It specifies floating-point value. Here
'p' is precision value.
- DOUBLE PRECISION - It specifies double
precision floating point number.
- REAL - The real integer is used to specify a
single precision floating point number.
- DECIMAL(P,S) - It specifies a decimal value. Here
'p' is precision value and 's' is scale value.
www.webstackacademy.com
SQL Data Types
● String Types :-
- CHAR(X) - Here 'x' is the character's number to
store. Here char should be used for storing fix
length strings.
- VARCHAR2(X) - Here 'x' is the character's
number to store. varchar is used to store variable
length strings. The String value's length will be
stored on disk with the value itself.
www.webstackacademy.com
SQL Data Types
● Date & Time Type
- DATE :- It stores year , month and days values.
- TIME : -It stores hour,minute and second values.
- TIMESTAMP :- The timestamp data type is used
to year , month ,day ,hour ,minute and second
values.
www.webstackacademy.com
MYSQL
Data Types
● In MySQL there are three main types : text, number, and Date/Time
types.
www.webstackacademy.com
MySQL Datatypes
● Text Types:
– CHAR(size):(can contain letters, numbers, and special
characters).Can store up to 255 characters
– VARCHAR(size):can contain letters, numbers, and special
characters).Can store up to 255 characters.
– TEXT: Holds a string with a maximum length of 65,535 characters
– BLOB: For BLOBs (Binary Large OBjects). Holds up to 65,535
bytes of data
www.webstackacademy.com
MySQL Data Types
● Number types:
– INT(size)
– FLOAT(size,d)
– DOUBLE(size,d)
www.webstackacademy.com
MySQL Data Types
● Date types:
– DATE(): A date. Format: YYYY-MM-DD
– DATETIME(): A date and time combination. Format: YYYY-MM-DD
HH:MM:SS
– TIME(): A time. Format: HH:MM:SS
– YEAR(): A year in two-digit or four-digit format.
www.webstackacademy.com
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
www.webstackacademy.com
Important SQL
Commands
● ALTER DATABASE - modifies a database
● CREATE TABLE - creates a new table
● ALTER TABLE - modifies a table
● DROP TABLE - deletes a table
www.webstackacademy.com
SQL Syntax
● CREATE DATABASE
– CREATE DATABASE dbname;
● CREATE TABLE
– CREATE TABLE Persons(PersonID int,LastName
varchar(255),FirstName varchar(255),Address
varchar(255),City varchar(255)
);
www.webstackacademy.com
SQL Syntax
● SQL SELECT Statement
– SELECT * FROM table_name;
● SELECT Column Example
– SELECT CustomerName,City FROM Customers;
● SELECT DISTINCT Statement
– SELECT DISTINCT column_name,column_name
FROM table_name;
www.webstackacademy.com
SQL Syntax
● SQL WHERE Clause
– SELECT * FROM Customers
WHERE Country='Mexico';;
www.webstackacademy.com
SQL Syntax
● Operators in the where clause:
=, >,<,>=,<=, BETWEEN, LIKE, IN
●
SQL AND Operators
– SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
● OR Operator Example
– SELECT * FROM Customers
– WHERE City='Berlin'
– OR City='Munchen';
www.webstackacademy.com
SQL Syntax
● Combining AND & OR
– SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
www.webstackacademy.com
ORDER BY Keyword
● The ORDER BY keyword is used to sort the result-set by one or more
columns.
● The ORDER BY keyword sorts the records in ascending order by
default. To sort the records in a descending order, you can use the
DESC keyword.
www.webstackacademy.com
ORDER BY Keyword
– SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
– SELECT * FROM Customers ORDER BY Country;
– SELECT * FROM Customers ORDER BY Country DESC;
– SELECT * FROM Customers ORDER BY
Country,CustomerName;
www.webstackacademy.com
INSERT INTO
Statement
● INSERT INTO table_name
VALUES (value1,value2,value3,...);
● INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
● INSERT INTO Customers (CustomerName, ContactName, Address,
City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen
21','Stavanger','4006','Norway');
www.webstackacademy.com
Update Statement
The UPDATE statement is used to update existing records in a table.
● UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
● UPDATE Customers SET ContactName='Alfred Schmidt',
City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';
www.webstackacademy.com
DELETE Statement
● The DELETE statement is used to delete records in a table.
● DELETE FROM table_name WHERE
some_column=some_value;
● DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste' AND ContactName='Maria Anders';
www.webstackacademy.com
DELETE Statement
● Delete All Data
● DELETE FROM table_name;
or
● DELETE * FROM table_name;
www.webstackacademy.com
SQL Injection
An SQL Injection can destroy the database. SQL injection is a
technique where malicious users can inject SQL commands into
an SQL statement ,via web page input.
Injected SQL commands can alter SQL statements and
compromise the security of a web application.
www.webstackacademy.com
SQL Web Page
When SQL is used to display data on a web page,it is common
to let web user input their own search value.
Since SQL statements are text only,it is easy,with a little piece
of computer code, to dynamically change SQL statements to
provide the user with selected data.
www.webstackacademy.com
SQL WEB Page
txtUserId =getRequestString(“UserId”);
txtSQL =”SELECT * FROM Users Where
UserId=”+txtUserId
● The example creates a select statement by adding a
variable (txtUserId) to a select string. The variable is
fetched from the user input (Request) to the page.
www.webstackacademy.com
SQL Injection
SELECT * FROM Users Where UserId =105 or 1=1
● SQL above is valid. It will return all rows from the table
Users ,since Where 1=1 is always true.
www.webstackacademy.com
SELECT TOP
● SELECT TOP clause is used to specify the number of records
to return.
● SELECT TOP clause can be very useful on large tables with
thousands of records. Returning a large number of records can
impact on performance.
www.webstackacademy.com
SELECT TOP
● MySQL Syntax :
SELECT column_name(s) from table_name LIMIT number;
● Example
SELECT * FROM Students LIMIT 5;
www.webstackacademy.com
SELECT TOP
● Oracle Syntax :
SELECT column_name(s) FROM table_name WHERE
ROWNUM <= number;
● Example
SELECT * FROM Students WHERE ROWNUM <=5;
www.webstackacademy.com
SELECT TOP
● Oracle Syntax :
SELECT column_name(s) FROM table_name WHERE
ROWNUM <= number;
● Example
SELECT * FROM Students WHERE ROWNUM <=5;
www.webstackacademy.com
Between Operators
www.webstackacademy.com
BETWEEN
Operator
● SELECT column_name(s) FROM table_name WHERE column_name
BETWEEN value1 AND value2;
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
● NOT BETWEEN
SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND
20;
● BETWEEN Operator with IN
SELECT * FROM Products WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
www.webstackacademy.com
BETWEEN
Operator
● BETWEEN Operator with Text Value
– SELECT * FROM Products WHERE ProductName BETWEEN 'C'
AND 'M';
● NOT BETWEEN Operator with Text Value
– SELECT * FROM Products WHERE ProductName NOT
BETWEEN 'C' AND 'M';
● BETWEEN Operator with Date Value
– SELECT * FROM Orders WHERE OrderDate BETWEEN
#07/04/1996# AND #07/09/1996#;
www.webstackacademy.com
LIKE
Operator
The Like operator is used to search for a specified pattern in a
column .
SQL LIKE Syntax :
SELECT column_name(s) FROM table_name WHERE column_name
LIKE pattern;
www.webstackacademy.com
LIKE
Operator
● Select all Customers starting with a City starting with the letter “m”
SELECT * FROM Customers WHERE City LIKE 'm%';
● Select all Customers with a City ending with the letter “m”
SELECT * FROM Customers WHERE City LIKE '%m';
● Select all customers with a City not containing the pattern
“nadu”
SELECT * FROM Customers WHERE City NOT LIKE '%nadu%';
www.webstackacademy.com
Wildcards
A wildcard character can be used to substitute for any other
character(s) in a string.
Two types of Wildcard characters :
● Percent sign(%) : Matches one or more Characters
● Underscore (_) : Matches one Character
www.webstackacademy.com
Wildcards
● Find any value start with 50
SELECT * FROM Product where price LIKE '50%';
● Find any value that have 50 in any position.
SELECT * FROM Product where price LIKE '%50%';
● Find any value that have 00 in the second and third positions
SELECT *FROM Product where price LIKE '_00%';
● Finds any values in a five-digit number that start with 2 and end with
3
SELECT * FROM Product where price LIKE '2___3';
www.webstackacademy.com
IN Operator
In operator allows to specify multiple values in a Where clause.
● IN Operator Syntax :
SELECT column_name(s) FROM table_name WHERE column_name
IN (value1,value2,....);
www.webstackacademy.com
IN Operator
● Select all Customer with a City of “Manchester” and “London”
SELECT * FROM Customers WHERE City IN
('Manchester','London');
● Select all Customers Except City of “Manchester” and “London”
SELECT * FROM Customers WHERE City NOT IN
('Manchester','London');
www.webstackacademy.com
SQL Functions
SQL has many built-in functions for performing
calculations on data.
www.webstackacademy.com
Aggregate Functions
SQL aggregate functions return a single value ,
calculated from values in a column.
www.webstackacademy.com
Aggregate Functions
● SUM() - Returns the sum
● AVG() - Returns the average value
● COUNT() - Returns the number of rows
● MAX() - Returns the Largest value
● MIN() - Returns the Smallest value
● FIRST() - Returns the first value
● LAST() - Returns the last value
www.webstackacademy.com
SUM()
● Syntax :
SELECT SUM(expression) FROM tables WHERE
conditions;
● Example :
SELECT SUM(salary) AS “Total Salary” FROM
Employee WHERE salary >20000;
www.webstackacademy.com
Group By
● The GROUP BY clause is a SQL command that is
used to group rows that have the same values.
● It is used in conjunction with aggregate functions to
produce summary reports from the database.
● GROUP BY clause are called grouped queries and
only return a single row for every grouped item.
www.webstackacademy.com
Group By
● Syntax :
SELECT column_name , aggregate_function(column_name
) FROM table_name WHERE column_name operator value
GROUP BY column_name;
● Example :
SELECT Department ,SUM(Salary) AS “Total Salary “ FROM
Employee
GROUP BY Department ;
www.webstackacademy.com
SQL Scalar Functions
SQL Scalar function return a single value, based on
the input value.
www.webstackacademy.com
SQL Scalar Functions
● UCASE() - Converts a field to upper case.
● LCASE() - Converts a field to lower case.
● LEN() - Returns the length of a text field.
● MID() - Extract characters from a text field.
● ROUND() - Rounds a numeric field to the number of decimal
specified.
● NOW() - Returns the current date and time.
● FORMAT() - Formats how a field is to be displayed.
www.webstackacademy.com
UCASE()
The UCASE() function converts the value of a field to
uppercase.
● Syntax
SELECT UCASE(column_name) FROM
table_name;
● Syntax for SQL Server
SELECT UPPER(column_name) FROM
table_name;
www.webstackacademy.com
LEN()
The LEN() function returns the length of the value in a
text field.
● Syntax
SELECT LEN(column_name) FROM table_name;
● Syntax for Oracle
SELECT LENGTH(column_name) FROM
table_name;
www.webstackacademy.com
MID()
The MID() function is used to extract characters from a text
field.
● Syntax
SELECT MID(column_name,start,length) AS
some_name FROM table_name;
● column_name - The field to extract characters
● Start - Specifies the starting position
● Length - The number of characters to return.
www.webstackacademy.com
ROUND()
The ROUND() function is used to round a numeric field to the number
of decimal specified.
● Syntax :
SELECT ROUND(column_name ,decimals) FROM table_name;
● column_name - The field to round.
● Decimals - Specifies the number of decimals to be
returned.
www.webstackacademy.com
NOW()
The Now() function returns the current date and time.
● Syntax :
SELECT NOW() FROM table_name;
● Example :
SELECT Product_Name ,Price ,NOW() AS “ Per Date” from
Products;
www.webstackacademy.com
FORMAT()
The FORMAT() function is used to format how a field is to be
displayed.
● Syntax :
SELECT FORMAT(column_name,format) FROM table_name;
● Example :
SELECT Product_Name ,Price, FORMAT(NOW(),'YYYY-MM-DD')
AS 'Per Date' FROM Products;
www.webstackacademy.com
SQL Aliases
SQL Aliases are used to temporarily rename a table or
column heading.
Syntax
● SELECT column_name AS alias_name FROM
table_name;
www.webstackacademy.com
Table Alias
Syntax :
SELECT column_name AS alias_name FROM
table_name;
Example
SELECT C.ID ,C.NAME ,C.AGE ,O.AMOUNT FROM
Customer As C , Order As O WHERE C.ID =
O.Customer _ID;
www.webstackacademy.com
Column Alias
● Syntax :
SELECT column_name(s) FROM table_name AS
alias_name;
● Example
SELECT ID AS CUSTOMER_ID , NAME AS
CUSTOMER_NAME FROM CUSTOMERS WHERE
SALARY IS NOT NULL;
www.webstackacademy.com
SQL Joins
www.webstackacademy.com
SQL Joins
● An SQL JOIN clause is used to combine rows from
two or more tables, based on a common field between
them.
www.webstackacademy.com
SQL Joins
● The different SQL JOINs you can use:
– INNER JOIN: Returns all rows when there is at least one match in
BOTH tables
– LEFT JOIN: Return all rows from the left table, and the matched
rows from the right table. The result is null in the right side if there
is no match.
– RIGHT JOIN: Return all rows from the right table, and the
matched rows from the left table. The result is null in the right side
if there is no match.
– FULL JOIN: Return all rows from the left table and right table. It
combines the result of both LEFT and RIGHT join.
www.webstackacademy.com
SQL Joins
● The most common type of join is: SQL INNER JOIN (simple
join). An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
www.webstackacademy.com
SQL Joins
Let's look at a selection from the "Orders" table:
● OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
www.webstackacademy.com
SQL Joins
Have a look at a selection from the "Customers" table:
● CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Trujillo Mexico
3 Antonio Moreno Moreno Mexico
● Notice that the "CustomerID" column in the "Orders" table refers to the
customer in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.
www.webstackacademy.com
SQL Joins
Example:
● SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
● It will produce the following:
OrderID CustomerName OrderDate
10308 Ana Trujillo 9/18/1996
www.webstackacademy.com
LEFT JOIN
SYNTAX :
SELECT column_name(s) FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name ;
www.webstackacademy.com
RIGHT JOIN
SYNTAX :
SELECT column_name(s) FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name ;
www.webstackacademy.com
FULL JOIN
SYNTAX :
SELECT column_name(s) FROM table1 FULL JOIN table2
ON table1.column_name = table2.column_name ;
www.webstackacademy.com
Union Operator
The SQL Union operator combines the result of two or more select
statement. Union Operator Select only distinct values by default . To
allow duplicate values use ALL keyword with UNION .
Syntax :
SELECT Column_name(s) FROM table1
UNION
SELECT Column_name(s) FROM table2;
www.webstackacademy.com
Select Into
The SELECT INTO statement copies data from
one table and insert it into a new Table.
Syntax :
● SELECT * INTO new table [ IN External db ]
FROM table1
OR
● SELECT column_name (s) INTO new table [IN
external db]
FROM table1;
www.webstackacademy.com
Insert into Select
The INSERT INTO SELECT statement copies data from one table and
insert it into existing table.
Syntax
● Copy data from one table to another existing table.
INSERT INTO table2
SELECT * FROM table1;
● Copy only columns into another existing table
INSERT INTO table2
( column_name (s))
SELECT column_name(s) FROM table1;
www.webstackacademy.com
SQL Constraints
● SQL constraints are used to specify rules for the data in a table.
● Constraints can be specified when the table is created (inside the
CREATE TABLE statement) or after the table is created (inside the
ALTER TABLE statement).
www.webstackacademy.com
SQL Constraints
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
● CHECK
● DEFAULT
www.webstackacademy.com
NOT NULL Constraint
NOT NULL Constraint enforces a column to not accept a null values.
● Example
CREATE TABLE Student
(Stud_ID int (10) NOT NULL,
Name varchar (20) NOT NULL,
Address varchar(20)
Course varchar (20));
www.webstackacademy.com
Unique Constraint
The UNIQUE Constraint uniquely identifies each record in a database
table.
Example
CREATE TABLE Student
(Stud_id int NOT NULL UNIQUE,
Name varchar (255) NOT NULL,
Address varchar (255),
City varchar (255) );
www.webstackacademy.com
PRIMARY KEY Constraint
● PRIMARY KEY Constraint uniquely identifies each record in a
database table.
● PRIMARY KEY must contain UNIQUE values.
● PRIMARY KEY column cannot contain NULL values.
● Each table can have only one PRIMARY KEY.
www.webstackacademy.com
Primary Key Constraint
CREATE TABLE Student
(Stud_Id int PRIMARY KEY,
Name varchar (20) NOT NULL,
Address varchar (20) ,
City varchar(35));
www.webstackacademy.com
Primary Key Constraint
● Adding Primary key Already created Table
ALTER TABLE STUDENT
ADD PRIMARY_KEY (STUD_ID) ;
● Defining Primary Key Constraints on Multiple Columns
ALTER TABLE STUDENT
ADD CONSTRAINT S_ID PRIMARY_KEY( STUD_ID, FIRSTNAME)
;
www.webstackacademy.com
Primary Key Constraint
● To DROP a Primary KEY
ALTER TABLE STUDENT
DROP PRIMARY KEY
www.webstackacademy.com
Foreign Key Constraint
● A Foreign Key in one table points to a PRIMARY KEY in another
table.
● A Foreign key is a field or a column that is used to establish a link
between two tables.
● The Foreign Key constraint also prevents invalid data from being
inserted into foreign key column ,because it has to be one of the
values contained in the table it points to.
www.webstackacademy.com
Foreign Key Constraint
● CREATE TABLE Student_Detail
(Stud_Id int PRIMARY KEY,
Name varchar (20) NOT NULL,
Address varchar (20) ,
City varchar(35));
● CREATE TABLE Marks_Detail
(Stud_Id int PRIMARY KEY,
Name varchar (20) NOT NULL,
Address varchar (20) ,
City varchar(35)
FOREIGN KEY (Stud_Id) REFERENCES STUDENT_DETAILS(Stud_Id)
);
www.webstackacademy.com
Check Constraint
● The CHECK constraint is used to limit the value range that can be
placed in a column.
CREATE TABLE Student
( Stud_Id int PRIMARY KEY,
Name varchar(20) NOT NULL,
Address varchar(20) NOT NULL,
City varchar(20) NOT NULL CHECK (City ='Banglore'));
www.webstackacademy.com
Default Constraint
Default constraint is used to insert a default value into a column.
Default value will be added to all new records ,if no other value is
specified.
CREATE TABLE Student
( Stud_Id int PRIMARY KEY,
Name varchar(20) NOT NULL,
Address varchar(20) NOT NULL,
City varchar(20) DEFAULT 'Banglore');
www.webstackacademy.com
Indexes
● Indexes allows the database application to find data
fast , without reading the whole table.
● An Index can be created in a table to find data more
quickly and efficiently
● The users cannot see the indexes, they are just used
to speed up searches/queries.
www.webstackacademy.com
Indexes
● Create Index Syntax
CREATE INDEX index_name
ON table_name (column_name)
● Create Unique Index
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
www.webstackacademy.com
Index Example
● Creating Index on a single column
CREATE INDEX ID1 ON Student(Name);
● Creating Index on a multiple Column
CREATE INDEX ID2
ON Student (FirstName , LastName);
www.webstackacademy.com
SQL Drop
● DROP TABLE
– The DROP TABLE statement is used to delete a table.
– DROP TABLE table_name
● DROP DATABASE
– The DROP DATABASE statement is used to delete a database.
– DROP DATABASE database_name
● ALTER TABLE
– The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
– ALTER TABLE table_name ADD column_name datatype
www.webstackacademy.com
SQL Drop
● TRUNCATE TABLE
– What if we only want to delete the data inside the table, and not
the table itself?
– TRUNCATE TABLE table_name
www.webstackacademy.com
SQL AUTO
INCREMENT
● Very often we would like the value of the primary key field to be
created automatically every time a new record is inserted.
● We would like to create an auto-increment field in a table.
● CREATE TABLE Persons(ID int NOT NULL
AUTO_INCREMENT,LastName varchar(255) NOT
NULL,FirstName varchar(255),Address varchar(255),
City varchar(255),PRIMARY KEY (ID))
www.webstackacademy.com
SQL AUTO
INCREMENT
● By default, the starting value for AUTO_INCREMENT is 1,and it will
increment by 1 for each new record.
● To let the AUTO_INCREMENT sequence start with another value, use
the following SQL statement:
– ALTER TABLE Persons AUTO_INCREMENT=100
● To insert a new record into the "Persons" table, we will NOT have to
specify a value for the "ID" column (a unique value will be added
automatically):
– INSERT INTO Persons (FirstName,LastName) VALUES
('Lars','Monsen')
www.webstackacademy.com
Views
● View is a virtual table based on the result-set of
an SQL statement.
● A view contains rows and columns , just like a
real table.
● The fields in a view are fields from one or more
real tables in the database.
www.webstackacademy.com
Views
● Updating View
CREATE OR REPLACE VIEW view_name AS SELECT
column_name(s) FROM table_name WHERE condition;
● Dropping a View
DROP VIEW view_name;
www.webstackacademy.com
View
View Syntax :
CREATE VIEW view_name AS SELECT column_name(s) FROM
table_name WHERE condition
Example :
CREATE VIEW StudentList AS SELECT Stud_Id ,Name FROM
Students WHERE City ='Banglore' ;
We can query the view as follows :
SELECT * FROM StudentList ;
www.webstackacademy.com
Views
● Updating View
CREATE OR REPLACE VIEW view_name AS SELECT
column_name(s) FROM table_name WHERE condition;
● Dropping a View
DROP VIEW view_name;
www.webstackacademy.com
SQL DATES
Assume we have following “Orders” table
● OrderID CustomerID OrderDate
10308 2 2011-09-18
10309 37 2009-09-19
10310 77 2012-09-20
10311 78 2012-09-21
SELECT *FROM Orders WHERE OrderDate='2011-09-18'
www.webstackacademy.com
SQL DATE Function
● GETDATE() returns the current date & Time from SQL Server.
Example
SELECT GETDATE() AS CurrentDateTime
● DATEDIFF() function returns the time between two functions.
DATEDIFF(datepart, startdate, enddate)
Example
SELECT DATEDIFF(day,'2016-08-05' ,'2016-08-06') AS DiffDate
www.webstackacademy.com
SQL NULL Values
● NULL values represent missing unknown data.
● By default ,a table can hold NULL values.
● NULL values are treated differently from other
values.
Example
SELECT OrderId ,CustomerId from Orders
where OrderId IS NULL
www.webstackacademy.com
NULL Functions
● ISNULL() :- function is used to specify how we want to
treat NULL values.
● NVL(), IFNULL(), and COALESCE() functions can also
be used to achieve the same result.
www.webstackacademy.com
Subquery
● Subquery or Inner query or Nested query is a query in query is
usually added in the WHERE clause of the SQL Statement.
● Subqueries are an alternate way of returning data from multiple
tables.
● Subqueries can be used with the SELECT ,INSERT ,UPDATE
and DELETE statements along with the operators like =
,<,>,>=,<=,IN ,BETWEEN etc.
www.webstackacademy.com
Subquery
Syntax :
SELECT select_list FROM table WHERE expr operator
(SELECT select_list FROM table);
● The subquery (inner query) executes once before the main
query (outer query) executes.
● The main query(outer query) use the subquery result.
www.webstackacademy.com
Subquery Example
● We have the following two tables
student and marks.
● Student Table
StudentIDName City
A001 John Paris
A002 Smith London
A003 Mac Berlin
A004 Ivan London
www.webstackacademy.com
Subquery Example
● Marks Table
StudentID Total_Marks
A001 95
A002 80
A003 75
A004 81
www.webstackacademy.com
Subquery Example
● We want to write a query to identify all students who get better
marks than that of the students who's StudentID is A002,but we
don't know the marks of A002.
Here two query one query return the the marks stored in
Total_marks field another query identifies the students who get
better marks than the result of the first query.
www.webstackacademy.com
Subquery Example
SELECT a.StudentID , a.name , b.Total_marks FROM
Student a , Marks b WHERE a.StudentID =b.StudentID AND
b.Total_marks > (SELECT Total_Marks FROM Marks
WHERE StudentId='A002');
● Output :
StudentID Name Total_Marks
A001 John 95
A004 Ivan 81
www.webstackacademy.com
Types of Subqueries
● Single Row Subquery
● Multiple Row Subquery
● Correlated Subquery
www.webstackacademy.com
Single Row Subquery
● Subquery which returns single row output. They mark the usage
of single row comparison operators when used in where
condition.
AGENT_CODE | AGENT_NAME | WORKING_AREA | COMMISSION | PHONE_NO | COUNTRY |
+------------+----------------------+--------------------+------------+-----------------+---------+
| A007 | Ramasundar | Bangalore | 0.15 | 077-25814763 | |
| A003 | Alex | London | 0.13 | 075-12458969 | |
| A008 | Alford | New York | 0.12 | 044-25874365 | |
| A011 | Ravi Kumar | Bangalore | 0.15 | 077-45625874 | |
| A010 | Santakumar | Chennai | 0.14 | 007-22388644 | |
| A012 | Lucida | San Jose | 0.12 | 044-52981425 | |
| A005 | Anderson | Brisban | 0.13 | 045-21447739 | |
| A001 | Subbarao | Bangalore | 0.14 | 077-12346674 | |
| A002 | Mukesh | Mumbai | 0.11 | 029-12358964 | |
| A006 | McDen | London | 0.15 | 078-22255588 | |
| A004 | Ivan | Torento | 0.15 | 008-22544166 | |
| A009 | Benjamin | Hampshair | 0.11 | 008-22536178 | |
+------------+----------------------+--------------------+------------+-----------------+---------+
Agent Table
www.webstackacademy.com
Single Row Subquery Example
SQL Statement :
SELECT agent_name ,agent_code,phone_no FROM agents
WHERE agent_code=(SELECT agent_code FROM agents
WHERE agent_name ='Alex';
● Output
AGENT_NAME AGENT_CODE PHONE_NO
Alex A003 075-12458969
www.webstackacademy.com
Single Row Subquery Example
www.webstackacademy.com
Multiple Row Subquery
● Multiple row subquery returns one or more rows to the outer
SQL statement. We can use IN, ANY, or ALL operator in outer
query to handle a subquery that returns multiple rows.
www.webstackacademy.com
Multiple Row Subquery[Using IN]
Order Table
ORD_NUM ORD_AMOUNT ADVANCE_AMOUNT ORD_DATE CUST_CODE AGENT_CODE ORD_DESCRIPTION
---------- ---------- -------------- --------- --------------- --------------- -----------------
200114 3500 2000 15-AUG-08 C00002 A008
200122 2500 400 16-SEP-08 C00003 A004
200118 500 100 20-JUL-08 C00023 A006
200119 4000 700 16-SEP-08 C00007 A010
200121 1500 600 23-SEP-08 C00008 A004
200130 2500 400 30-JUL-08 C00025 A011
200134 4200 1800 25-SEP-08 C00004 A005
200108 4000 600 15-FEB-08 C00008 A004
200103 1500 700 15-MAY-08 C00021 A005
200105 2500 500 18-JUL-08 C00025 A011
200109 3500 800 30-JUL-08 C00011 A010
200101 3000 1000 15-JUL-08 C00001 A008
200111 1000 300 10-JUL-08 C00020 A008
200104 1500 500 13-MAR-08 C00006 A004
200106 2500 700 20-APR-08 C00005 A002
200125 2000 600 10-OCT-08 C00018 A005
200117 800 200 20-OCT-08 C00014 A001
200123 500 100 16-SEP-08 C00022 A002
200120 500 100 20-JUL-08 C00009 A002
200116 500 100 13-JUL-08 C00010 A009
200124 500 100 20-JUN-08 C00017 A007
200126 500 100 24-JUN-08 C00022 A002
200129 2500 500 20-JUL-08 C00024 A006
200127 2500 400 20-JUL-08 C00015 A003
200128 3500 1500 20-JUL-08 C00009 A002
200135 2000 800 16-SEP-08 C00007 A010
200131 900 150 26-AUG-08 C00012 A012
200133 1200 400 29-JUN-08 C00009 A002
200100 1000 600 08-JAN-08 C00015 A003
www.webstackacademy.com
Multiple Row Subquery
SQL Statement :
SELECT ord_num,ord_amount ,ord_date ,cust_code ,agent_code
FROM orders WHERE agent_code IN (SELECT agent_code FROM
agents WHERE working_area ='Banglore');
● Output :
ORD_NUM ORD_AMOUNT ORD_DATE CUST_CODE AGENT_CODE
200130 25000 30-JUL-08 C00025 A011
200105 2500 18-JUL-08 C00025 A011
www.webstackacademy.com
Correlated Subquery
SQL Correlated Subqueries are used to select data from a table
referenced in the outer query. The subquery is known as a
correlated because the subquery is related to the outer query.
www.webstackacademy.com
Correlated Subquery
SQL Statement :-
SELECT a.ord_num ,a.ord_amount ,a.cust_code ,a.agent_code
FROM orders a WHERE a.agent_code =(SELECT b.agent_code
FROM agents b WHERE b.agent_name='Alex');
Output :-
ORD_NUM ORD_AMOUNT CUST_CODE AGENT_CODE
200127 2500 C00015 A003
200100 1000 C00015 A003
www.webstackacademy.com
Correlated Subquery
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com
www.webstackacademy.com

More Related Content

What's hot (20)

PPTX
Introduction to Oracle Database
puja_dhar
 
PPTX
SQL commands
GirdharRatne
 
PPTX
SQL - Structured query language introduction
Smriti Jain
 
PDF
Introduction to SQL
Ram Kedem
 
PPTX
Sql queries presentation
NITISH KUMAR
 
PPTX
Database : Relational Data Model
Smriti Jain
 
PPT
MYSQL.ppt
webhostingguy
 
PPTX
Relational model
Dabbal Singh Mahara
 
PPTX
Sql commands
Pooja Dixit
 
PPTX
File Handling and Command Line Arguments in C
Mahendra Yadav
 
PPTX
Postgresql
NexThoughts Technologies
 
PPTX
SQL Commands
Sachidananda M H
 
PPTX
SQL Queries Information
Nishant Munjal
 
PPTX
Presentation slides of Sequence Query Language (SQL)
Punjab University
 
PPTX
DBMS and its Models
AhmadShah Sultani
 
PPTX
HTML and DHTML
Dr. SURBHI SAROHA
 
PPTX
Dbms Introduction and Basics
SHIKHA GAUTAM
 
PPT
Database Triggers
Aliya Saldanha
 
PPT
Mysql
TSUBHASHRI
 
Introduction to Oracle Database
puja_dhar
 
SQL commands
GirdharRatne
 
SQL - Structured query language introduction
Smriti Jain
 
Introduction to SQL
Ram Kedem
 
Sql queries presentation
NITISH KUMAR
 
Database : Relational Data Model
Smriti Jain
 
MYSQL.ppt
webhostingguy
 
Relational model
Dabbal Singh Mahara
 
Sql commands
Pooja Dixit
 
File Handling and Command Line Arguments in C
Mahendra Yadav
 
SQL Commands
Sachidananda M H
 
SQL Queries Information
Nishant Munjal
 
Presentation slides of Sequence Query Language (SQL)
Punjab University
 
DBMS and its Models
AhmadShah Sultani
 
HTML and DHTML
Dr. SURBHI SAROHA
 
Dbms Introduction and Basics
SHIKHA GAUTAM
 
Database Triggers
Aliya Saldanha
 
Mysql
TSUBHASHRI
 

Similar to SQL - RDBMS Concepts (20)

PPTX
CSE311_IAH_Slide06_SQL _Retrival_Queries.pptx
noshinnawar31
 
PPT
Introduction to Structured Query Language (SQL).ppt
Ashwini Rao
 
PDF
Sql a practical introduction
Hasan Kata
 
PDF
Sql a practical introduction
sanjaychauhan689
 
PDF
MySQL for beginners
Saeid Zebardast
 
PDF
Sql a practical_introduction
investnow
 
PPTX
Sql – pocket guide
Santhosh Kumar
 
PDF
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
PDF
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
PPT
Chapt7.ppt
ImXaib
 
PPTX
SQL Sort Notes
ShivaAdasule
 
PPTX
Introduction to structured query language (sql) (1)
RajniKashyap9
 
PPT
MY SQL
sundar
 
DOCX
Sql
navsissuk
 
PDF
Complete SQL in one video by shradha.pdf
rahulashu699
 
PPT
Introduction to Structured Query Language (SQL).ppt
JohnnySebastian4
 
PPT
mis4200notes4_2.ppt
SarfarazSiddiqui20
 
PDF
Lecture on DBMS & MySQL.pdf v. C. .
MayankSinghRawat6
 
PPT
Oracle Sql & PLSQL Complete guide
Raviteja Chowdary Adusumalli
 
PPTX
BITM3730Week14.pptx
MattMarino13
 
CSE311_IAH_Slide06_SQL _Retrival_Queries.pptx
noshinnawar31
 
Introduction to Structured Query Language (SQL).ppt
Ashwini Rao
 
Sql a practical introduction
Hasan Kata
 
Sql a practical introduction
sanjaychauhan689
 
MySQL for beginners
Saeid Zebardast
 
Sql a practical_introduction
investnow
 
Sql – pocket guide
Santhosh Kumar
 
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
Chapt7.ppt
ImXaib
 
SQL Sort Notes
ShivaAdasule
 
Introduction to structured query language (sql) (1)
RajniKashyap9
 
MY SQL
sundar
 
Complete SQL in one video by shradha.pdf
rahulashu699
 
Introduction to Structured Query Language (SQL).ppt
JohnnySebastian4
 
mis4200notes4_2.ppt
SarfarazSiddiqui20
 
Lecture on DBMS & MySQL.pdf v. C. .
MayankSinghRawat6
 
Oracle Sql & PLSQL Complete guide
Raviteja Chowdary Adusumalli
 
BITM3730Week14.pptx
MattMarino13
 
Ad

More from WebStackAcademy (20)

PDF
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
PDF
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
PDF
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
PDF
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
PDF
Webstack Academy - Internship Kick Off
WebStackAcademy
 
PDF
Building Your Online Portfolio
WebStackAcademy
 
PDF
Front-End Developer's Career Roadmap
WebStackAcademy
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Ad

Recently uploaded (20)

PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 

SQL - RDBMS Concepts

  • 4. www.webstackacademy.com Definition ● RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. ● A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. ● The data in RDBMS is stored in database objects called tables.
  • 6. www.webstackacademy.com DBMS & RDBMS ● DBMS applications store data as file. ● DBMS does not support client/server architecture. ● DBMS does not allow normalization. ● DBMS does not impose integrity constraints. ● RDBMS applications store data in a tabular form. ● RDBMS supports client/server architecture. ● RDBMS allows normalization. ● RDBMS imposes integrity constraints.
  • 8. www.webstackacademy.com Creating Table ● The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows. ● Remember, a table is the most common and simplest form of data storage in a relational database.
  • 9. www.webstackacademy.com Field, Record or Row ● Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY. ● A record, also called a row of data, is each individual entry that exists in a table. For example there are 7 records in the above CUSTOMERS table.
  • 10. www.webstackacademy.com Column ● A column is a vertical entity in a table that contains all information associated with a specific field in a table.
  • 11. www.webstackacademy.com Null Value ● A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value is a field with no value.
  • 13. www.webstackacademy.com SQL ● SQL is a standard language for accessing databases. ● SQL stands for Structured Query Language ● SQL lets you access and manipulate databases ● SQL is an ANSI (American National Standards Institute) standard
  • 14. www.webstackacademy.com Benefit of SQL ● SQL can execute queries against a database ● SQL can retrieve data from a database ● SQL can insert records in a database ● SQL can update records in a database ● SQL can delete records from a database
  • 15. www.webstackacademy.com Using SQL in your Project To build an application that shows data from a database, you will need: ● An RDBMS database program (i.e. MS Access, SQL Server, MySQL) ● To use a server-side scripting language, like Java, PHP or ASP ● To use SQL to get the data you want ● To use HTML / CSS
  • 16. www.webstackacademy.com SQL Data Types ● Number Data types :- - INTEGER :- The Integer data type is used to specify an integer value. - SMALLINT :- The SMALLINT data type is used to specify small integer value. - NUMERIC(P,S) :-It specifies a numeric value. Here 'p' is precision value and 's' is a scale value.
  • 17. www.webstackacademy.com SQL Data Types ● Float Types : - FLOAT(P) - It specifies floating-point value. Here 'p' is precision value. - DOUBLE PRECISION - It specifies double precision floating point number. - REAL - The real integer is used to specify a single precision floating point number. - DECIMAL(P,S) - It specifies a decimal value. Here 'p' is precision value and 's' is scale value.
  • 18. www.webstackacademy.com SQL Data Types ● String Types :- - CHAR(X) - Here 'x' is the character's number to store. Here char should be used for storing fix length strings. - VARCHAR2(X) - Here 'x' is the character's number to store. varchar is used to store variable length strings. The String value's length will be stored on disk with the value itself.
  • 19. www.webstackacademy.com SQL Data Types ● Date & Time Type - DATE :- It stores year , month and days values. - TIME : -It stores hour,minute and second values. - TIMESTAMP :- The timestamp data type is used to year , month ,day ,hour ,minute and second values.
  • 20. www.webstackacademy.com MYSQL Data Types ● In MySQL there are three main types : text, number, and Date/Time types.
  • 21. www.webstackacademy.com MySQL Datatypes ● Text Types: – CHAR(size):(can contain letters, numbers, and special characters).Can store up to 255 characters – VARCHAR(size):can contain letters, numbers, and special characters).Can store up to 255 characters. – TEXT: Holds a string with a maximum length of 65,535 characters – BLOB: For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
  • 22. www.webstackacademy.com MySQL Data Types ● Number types: – INT(size) – FLOAT(size,d) – DOUBLE(size,d)
  • 23. www.webstackacademy.com MySQL Data Types ● Date types: – DATE(): A date. Format: YYYY-MM-DD – DATETIME(): A date and time combination. Format: YYYY-MM-DD HH:MM:SS – TIME(): A time. Format: HH:MM:SS – YEAR(): A year in two-digit or four-digit format.
  • 24. www.webstackacademy.com 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
  • 25. www.webstackacademy.com Important SQL Commands ● ALTER DATABASE - modifies a database ● CREATE TABLE - creates a new table ● ALTER TABLE - modifies a table ● DROP TABLE - deletes a table
  • 26. www.webstackacademy.com SQL Syntax ● CREATE DATABASE – CREATE DATABASE dbname; ● CREATE TABLE – CREATE TABLE Persons(PersonID int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255) );
  • 27. www.webstackacademy.com SQL Syntax ● SQL SELECT Statement – SELECT * FROM table_name; ● SELECT Column Example – SELECT CustomerName,City FROM Customers; ● SELECT DISTINCT Statement – SELECT DISTINCT column_name,column_name FROM table_name;
  • 28. www.webstackacademy.com SQL Syntax ● SQL WHERE Clause – SELECT * FROM Customers WHERE Country='Mexico';;
  • 29. www.webstackacademy.com SQL Syntax ● Operators in the where clause: =, >,<,>=,<=, BETWEEN, LIKE, IN ● SQL AND Operators – SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; ● OR Operator Example – SELECT * FROM Customers – WHERE City='Berlin' – OR City='Munchen';
  • 30. www.webstackacademy.com SQL Syntax ● Combining AND & OR – SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
  • 31. www.webstackacademy.com ORDER BY Keyword ● The ORDER BY keyword is used to sort the result-set by one or more columns. ● The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.
  • 32. www.webstackacademy.com ORDER BY Keyword – SELECT column_name,column_name FROM table_name ORDER BY column_name,column_name ASC|DESC; – SELECT * FROM Customers ORDER BY Country; – SELECT * FROM Customers ORDER BY Country DESC; – SELECT * FROM Customers ORDER BY Country,CustomerName;
  • 33. www.webstackacademy.com INSERT INTO Statement ● INSERT INTO table_name VALUES (value1,value2,value3,...); ● INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); ● INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
  • 34. www.webstackacademy.com Update Statement The UPDATE statement is used to update existing records in a table. ● UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value; ● UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';
  • 35. www.webstackacademy.com DELETE Statement ● The DELETE statement is used to delete records in a table. ● DELETE FROM table_name WHERE some_column=some_value; ● DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';
  • 36. www.webstackacademy.com DELETE Statement ● Delete All Data ● DELETE FROM table_name; or ● DELETE * FROM table_name;
  • 37. www.webstackacademy.com SQL Injection An SQL Injection can destroy the database. SQL injection is a technique where malicious users can inject SQL commands into an SQL statement ,via web page input. Injected SQL commands can alter SQL statements and compromise the security of a web application.
  • 38. www.webstackacademy.com SQL Web Page When SQL is used to display data on a web page,it is common to let web user input their own search value. Since SQL statements are text only,it is easy,with a little piece of computer code, to dynamically change SQL statements to provide the user with selected data.
  • 39. www.webstackacademy.com SQL WEB Page txtUserId =getRequestString(“UserId”); txtSQL =”SELECT * FROM Users Where UserId=”+txtUserId ● The example creates a select statement by adding a variable (txtUserId) to a select string. The variable is fetched from the user input (Request) to the page.
  • 40. www.webstackacademy.com SQL Injection SELECT * FROM Users Where UserId =105 or 1=1 ● SQL above is valid. It will return all rows from the table Users ,since Where 1=1 is always true.
  • 41. www.webstackacademy.com SELECT TOP ● SELECT TOP clause is used to specify the number of records to return. ● SELECT TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance.
  • 42. www.webstackacademy.com SELECT TOP ● MySQL Syntax : SELECT column_name(s) from table_name LIMIT number; ● Example SELECT * FROM Students LIMIT 5;
  • 43. www.webstackacademy.com SELECT TOP ● Oracle Syntax : SELECT column_name(s) FROM table_name WHERE ROWNUM <= number; ● Example SELECT * FROM Students WHERE ROWNUM <=5;
  • 44. www.webstackacademy.com SELECT TOP ● Oracle Syntax : SELECT column_name(s) FROM table_name WHERE ROWNUM <= number; ● Example SELECT * FROM Students WHERE ROWNUM <=5;
  • 46. www.webstackacademy.com BETWEEN Operator ● SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; ● NOT BETWEEN SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20; ● BETWEEN Operator with IN SELECT * FROM Products WHERE (Price BETWEEN 10 AND 20) AND NOT CategoryID IN (1,2,3);
  • 47. www.webstackacademy.com BETWEEN Operator ● BETWEEN Operator with Text Value – SELECT * FROM Products WHERE ProductName BETWEEN 'C' AND 'M'; ● NOT BETWEEN Operator with Text Value – SELECT * FROM Products WHERE ProductName NOT BETWEEN 'C' AND 'M'; ● BETWEEN Operator with Date Value – SELECT * FROM Orders WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
  • 48. www.webstackacademy.com LIKE Operator The Like operator is used to search for a specified pattern in a column . SQL LIKE Syntax : SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;
  • 49. www.webstackacademy.com LIKE Operator ● Select all Customers starting with a City starting with the letter “m” SELECT * FROM Customers WHERE City LIKE 'm%'; ● Select all Customers with a City ending with the letter “m” SELECT * FROM Customers WHERE City LIKE '%m'; ● Select all customers with a City not containing the pattern “nadu” SELECT * FROM Customers WHERE City NOT LIKE '%nadu%';
  • 50. www.webstackacademy.com Wildcards A wildcard character can be used to substitute for any other character(s) in a string. Two types of Wildcard characters : ● Percent sign(%) : Matches one or more Characters ● Underscore (_) : Matches one Character
  • 51. www.webstackacademy.com Wildcards ● Find any value start with 50 SELECT * FROM Product where price LIKE '50%'; ● Find any value that have 50 in any position. SELECT * FROM Product where price LIKE '%50%'; ● Find any value that have 00 in the second and third positions SELECT *FROM Product where price LIKE '_00%'; ● Finds any values in a five-digit number that start with 2 and end with 3 SELECT * FROM Product where price LIKE '2___3';
  • 52. www.webstackacademy.com IN Operator In operator allows to specify multiple values in a Where clause. ● IN Operator Syntax : SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,....);
  • 53. www.webstackacademy.com IN Operator ● Select all Customer with a City of “Manchester” and “London” SELECT * FROM Customers WHERE City IN ('Manchester','London'); ● Select all Customers Except City of “Manchester” and “London” SELECT * FROM Customers WHERE City NOT IN ('Manchester','London');
  • 54. www.webstackacademy.com SQL Functions SQL has many built-in functions for performing calculations on data.
  • 55. www.webstackacademy.com Aggregate Functions SQL aggregate functions return a single value , calculated from values in a column.
  • 56. www.webstackacademy.com Aggregate Functions ● SUM() - Returns the sum ● AVG() - Returns the average value ● COUNT() - Returns the number of rows ● MAX() - Returns the Largest value ● MIN() - Returns the Smallest value ● FIRST() - Returns the first value ● LAST() - Returns the last value
  • 57. www.webstackacademy.com SUM() ● Syntax : SELECT SUM(expression) FROM tables WHERE conditions; ● Example : SELECT SUM(salary) AS “Total Salary” FROM Employee WHERE salary >20000;
  • 58. www.webstackacademy.com Group By ● The GROUP BY clause is a SQL command that is used to group rows that have the same values. ● It is used in conjunction with aggregate functions to produce summary reports from the database. ● GROUP BY clause are called grouped queries and only return a single row for every grouped item.
  • 59. www.webstackacademy.com Group By ● Syntax : SELECT column_name , aggregate_function(column_name ) FROM table_name WHERE column_name operator value GROUP BY column_name; ● Example : SELECT Department ,SUM(Salary) AS “Total Salary “ FROM Employee GROUP BY Department ;
  • 60. www.webstackacademy.com SQL Scalar Functions SQL Scalar function return a single value, based on the input value.
  • 61. www.webstackacademy.com SQL Scalar Functions ● UCASE() - Converts a field to upper case. ● LCASE() - Converts a field to lower case. ● LEN() - Returns the length of a text field. ● MID() - Extract characters from a text field. ● ROUND() - Rounds a numeric field to the number of decimal specified. ● NOW() - Returns the current date and time. ● FORMAT() - Formats how a field is to be displayed.
  • 62. www.webstackacademy.com UCASE() The UCASE() function converts the value of a field to uppercase. ● Syntax SELECT UCASE(column_name) FROM table_name; ● Syntax for SQL Server SELECT UPPER(column_name) FROM table_name;
  • 63. www.webstackacademy.com LEN() The LEN() function returns the length of the value in a text field. ● Syntax SELECT LEN(column_name) FROM table_name; ● Syntax for Oracle SELECT LENGTH(column_name) FROM table_name;
  • 64. www.webstackacademy.com MID() The MID() function is used to extract characters from a text field. ● Syntax SELECT MID(column_name,start,length) AS some_name FROM table_name; ● column_name - The field to extract characters ● Start - Specifies the starting position ● Length - The number of characters to return.
  • 65. www.webstackacademy.com ROUND() The ROUND() function is used to round a numeric field to the number of decimal specified. ● Syntax : SELECT ROUND(column_name ,decimals) FROM table_name; ● column_name - The field to round. ● Decimals - Specifies the number of decimals to be returned.
  • 66. www.webstackacademy.com NOW() The Now() function returns the current date and time. ● Syntax : SELECT NOW() FROM table_name; ● Example : SELECT Product_Name ,Price ,NOW() AS “ Per Date” from Products;
  • 67. www.webstackacademy.com FORMAT() The FORMAT() function is used to format how a field is to be displayed. ● Syntax : SELECT FORMAT(column_name,format) FROM table_name; ● Example : SELECT Product_Name ,Price, FORMAT(NOW(),'YYYY-MM-DD') AS 'Per Date' FROM Products;
  • 68. www.webstackacademy.com SQL Aliases SQL Aliases are used to temporarily rename a table or column heading. Syntax ● SELECT column_name AS alias_name FROM table_name;
  • 69. www.webstackacademy.com Table Alias Syntax : SELECT column_name AS alias_name FROM table_name; Example SELECT C.ID ,C.NAME ,C.AGE ,O.AMOUNT FROM Customer As C , Order As O WHERE C.ID = O.Customer _ID;
  • 70. www.webstackacademy.com Column Alias ● Syntax : SELECT column_name(s) FROM table_name AS alias_name; ● Example SELECT ID AS CUSTOMER_ID , NAME AS CUSTOMER_NAME FROM CUSTOMERS WHERE SALARY IS NOT NULL;
  • 72. www.webstackacademy.com SQL Joins ● An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
  • 73. www.webstackacademy.com SQL Joins ● The different SQL JOINs you can use: – INNER JOIN: Returns all rows when there is at least one match in BOTH tables – LEFT JOIN: Return all rows from the left table, and the matched rows from the right table. The result is null in the right side if there is no match. – RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table. The result is null in the right side if there is no match. – FULL JOIN: Return all rows from the left table and right table. It combines the result of both LEFT and RIGHT join.
  • 74. www.webstackacademy.com SQL Joins ● The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met.
  • 75. www.webstackacademy.com SQL Joins Let's look at a selection from the "Orders" table: ● OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20
  • 76. www.webstackacademy.com SQL Joins Have a look at a selection from the "Customers" table: ● CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Trujillo Mexico 3 Antonio Moreno Moreno Mexico ● Notice that the "CustomerID" column in the "Orders" table refers to the customer in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.
  • 77. www.webstackacademy.com SQL Joins Example: ● SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; ● It will produce the following: OrderID CustomerName OrderDate 10308 Ana Trujillo 9/18/1996
  • 78. www.webstackacademy.com LEFT JOIN SYNTAX : SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name ;
  • 79. www.webstackacademy.com RIGHT JOIN SYNTAX : SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name ;
  • 80. www.webstackacademy.com FULL JOIN SYNTAX : SELECT column_name(s) FROM table1 FULL JOIN table2 ON table1.column_name = table2.column_name ;
  • 81. www.webstackacademy.com Union Operator The SQL Union operator combines the result of two or more select statement. Union Operator Select only distinct values by default . To allow duplicate values use ALL keyword with UNION . Syntax : SELECT Column_name(s) FROM table1 UNION SELECT Column_name(s) FROM table2;
  • 82. www.webstackacademy.com Select Into The SELECT INTO statement copies data from one table and insert it into a new Table. Syntax : ● SELECT * INTO new table [ IN External db ] FROM table1 OR ● SELECT column_name (s) INTO new table [IN external db] FROM table1;
  • 83. www.webstackacademy.com Insert into Select The INSERT INTO SELECT statement copies data from one table and insert it into existing table. Syntax ● Copy data from one table to another existing table. INSERT INTO table2 SELECT * FROM table1; ● Copy only columns into another existing table INSERT INTO table2 ( column_name (s)) SELECT column_name(s) FROM table1;
  • 84. www.webstackacademy.com SQL Constraints ● SQL constraints are used to specify rules for the data in a table. ● Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
  • 85. www.webstackacademy.com SQL Constraints ● NOT NULL ● UNIQUE ● PRIMARY KEY ● FOREIGN KEY ● CHECK ● DEFAULT
  • 86. www.webstackacademy.com NOT NULL Constraint NOT NULL Constraint enforces a column to not accept a null values. ● Example CREATE TABLE Student (Stud_ID int (10) NOT NULL, Name varchar (20) NOT NULL, Address varchar(20) Course varchar (20));
  • 87. www.webstackacademy.com Unique Constraint The UNIQUE Constraint uniquely identifies each record in a database table. Example CREATE TABLE Student (Stud_id int NOT NULL UNIQUE, Name varchar (255) NOT NULL, Address varchar (255), City varchar (255) );
  • 88. www.webstackacademy.com PRIMARY KEY Constraint ● PRIMARY KEY Constraint uniquely identifies each record in a database table. ● PRIMARY KEY must contain UNIQUE values. ● PRIMARY KEY column cannot contain NULL values. ● Each table can have only one PRIMARY KEY.
  • 89. www.webstackacademy.com Primary Key Constraint CREATE TABLE Student (Stud_Id int PRIMARY KEY, Name varchar (20) NOT NULL, Address varchar (20) , City varchar(35));
  • 90. www.webstackacademy.com Primary Key Constraint ● Adding Primary key Already created Table ALTER TABLE STUDENT ADD PRIMARY_KEY (STUD_ID) ; ● Defining Primary Key Constraints on Multiple Columns ALTER TABLE STUDENT ADD CONSTRAINT S_ID PRIMARY_KEY( STUD_ID, FIRSTNAME) ;
  • 91. www.webstackacademy.com Primary Key Constraint ● To DROP a Primary KEY ALTER TABLE STUDENT DROP PRIMARY KEY
  • 92. www.webstackacademy.com Foreign Key Constraint ● A Foreign Key in one table points to a PRIMARY KEY in another table. ● A Foreign key is a field or a column that is used to establish a link between two tables. ● The Foreign Key constraint also prevents invalid data from being inserted into foreign key column ,because it has to be one of the values contained in the table it points to.
  • 93. www.webstackacademy.com Foreign Key Constraint ● CREATE TABLE Student_Detail (Stud_Id int PRIMARY KEY, Name varchar (20) NOT NULL, Address varchar (20) , City varchar(35)); ● CREATE TABLE Marks_Detail (Stud_Id int PRIMARY KEY, Name varchar (20) NOT NULL, Address varchar (20) , City varchar(35) FOREIGN KEY (Stud_Id) REFERENCES STUDENT_DETAILS(Stud_Id) );
  • 94. www.webstackacademy.com Check Constraint ● The CHECK constraint is used to limit the value range that can be placed in a column. CREATE TABLE Student ( Stud_Id int PRIMARY KEY, Name varchar(20) NOT NULL, Address varchar(20) NOT NULL, City varchar(20) NOT NULL CHECK (City ='Banglore'));
  • 95. www.webstackacademy.com Default Constraint Default constraint is used to insert a default value into a column. Default value will be added to all new records ,if no other value is specified. CREATE TABLE Student ( Stud_Id int PRIMARY KEY, Name varchar(20) NOT NULL, Address varchar(20) NOT NULL, City varchar(20) DEFAULT 'Banglore');
  • 96. www.webstackacademy.com Indexes ● Indexes allows the database application to find data fast , without reading the whole table. ● An Index can be created in a table to find data more quickly and efficiently ● The users cannot see the indexes, they are just used to speed up searches/queries.
  • 97. www.webstackacademy.com Indexes ● Create Index Syntax CREATE INDEX index_name ON table_name (column_name) ● Create Unique Index CREATE UNIQUE INDEX index_name ON table_name (column_name)
  • 98. www.webstackacademy.com Index Example ● Creating Index on a single column CREATE INDEX ID1 ON Student(Name); ● Creating Index on a multiple Column CREATE INDEX ID2 ON Student (FirstName , LastName);
  • 99. www.webstackacademy.com SQL Drop ● DROP TABLE – The DROP TABLE statement is used to delete a table. – DROP TABLE table_name ● DROP DATABASE – The DROP DATABASE statement is used to delete a database. – DROP DATABASE database_name ● ALTER TABLE – The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. – ALTER TABLE table_name ADD column_name datatype
  • 100. www.webstackacademy.com SQL Drop ● TRUNCATE TABLE – What if we only want to delete the data inside the table, and not the table itself? – TRUNCATE TABLE table_name
  • 101. www.webstackacademy.com SQL AUTO INCREMENT ● Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. ● We would like to create an auto-increment field in a table. ● CREATE TABLE Persons(ID int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255), City varchar(255),PRIMARY KEY (ID))
  • 102. www.webstackacademy.com SQL AUTO INCREMENT ● By default, the starting value for AUTO_INCREMENT is 1,and it will increment by 1 for each new record. ● To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: – ALTER TABLE Persons AUTO_INCREMENT=100 ● To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically): – INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen')
  • 103. www.webstackacademy.com Views ● View is a virtual table based on the result-set of an SQL statement. ● A view contains rows and columns , just like a real table. ● The fields in a view are fields from one or more real tables in the database.
  • 104. www.webstackacademy.com Views ● Updating View CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition; ● Dropping a View DROP VIEW view_name;
  • 105. www.webstackacademy.com View View Syntax : CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Example : CREATE VIEW StudentList AS SELECT Stud_Id ,Name FROM Students WHERE City ='Banglore' ; We can query the view as follows : SELECT * FROM StudentList ;
  • 106. www.webstackacademy.com Views ● Updating View CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition; ● Dropping a View DROP VIEW view_name;
  • 107. www.webstackacademy.com SQL DATES Assume we have following “Orders” table ● OrderID CustomerID OrderDate 10308 2 2011-09-18 10309 37 2009-09-19 10310 77 2012-09-20 10311 78 2012-09-21 SELECT *FROM Orders WHERE OrderDate='2011-09-18'
  • 108. www.webstackacademy.com SQL DATE Function ● GETDATE() returns the current date & Time from SQL Server. Example SELECT GETDATE() AS CurrentDateTime ● DATEDIFF() function returns the time between two functions. DATEDIFF(datepart, startdate, enddate) Example SELECT DATEDIFF(day,'2016-08-05' ,'2016-08-06') AS DiffDate
  • 109. www.webstackacademy.com SQL NULL Values ● NULL values represent missing unknown data. ● By default ,a table can hold NULL values. ● NULL values are treated differently from other values. Example SELECT OrderId ,CustomerId from Orders where OrderId IS NULL
  • 110. www.webstackacademy.com NULL Functions ● ISNULL() :- function is used to specify how we want to treat NULL values. ● NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
  • 111. www.webstackacademy.com Subquery ● Subquery or Inner query or Nested query is a query in query is usually added in the WHERE clause of the SQL Statement. ● Subqueries are an alternate way of returning data from multiple tables. ● Subqueries can be used with the SELECT ,INSERT ,UPDATE and DELETE statements along with the operators like = ,<,>,>=,<=,IN ,BETWEEN etc.
  • 112. www.webstackacademy.com Subquery Syntax : SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); ● The subquery (inner query) executes once before the main query (outer query) executes. ● The main query(outer query) use the subquery result.
  • 113. www.webstackacademy.com Subquery Example ● We have the following two tables student and marks. ● Student Table StudentIDName City A001 John Paris A002 Smith London A003 Mac Berlin A004 Ivan London
  • 114. www.webstackacademy.com Subquery Example ● Marks Table StudentID Total_Marks A001 95 A002 80 A003 75 A004 81
  • 115. www.webstackacademy.com Subquery Example ● We want to write a query to identify all students who get better marks than that of the students who's StudentID is A002,but we don't know the marks of A002. Here two query one query return the the marks stored in Total_marks field another query identifies the students who get better marks than the result of the first query.
  • 116. www.webstackacademy.com Subquery Example SELECT a.StudentID , a.name , b.Total_marks FROM Student a , Marks b WHERE a.StudentID =b.StudentID AND b.Total_marks > (SELECT Total_Marks FROM Marks WHERE StudentId='A002'); ● Output : StudentID Name Total_Marks A001 John 95 A004 Ivan 81
  • 117. www.webstackacademy.com Types of Subqueries ● Single Row Subquery ● Multiple Row Subquery ● Correlated Subquery
  • 118. www.webstackacademy.com Single Row Subquery ● Subquery which returns single row output. They mark the usage of single row comparison operators when used in where condition. AGENT_CODE | AGENT_NAME | WORKING_AREA | COMMISSION | PHONE_NO | COUNTRY | +------------+----------------------+--------------------+------------+-----------------+---------+ | A007 | Ramasundar | Bangalore | 0.15 | 077-25814763 | | | A003 | Alex | London | 0.13 | 075-12458969 | | | A008 | Alford | New York | 0.12 | 044-25874365 | | | A011 | Ravi Kumar | Bangalore | 0.15 | 077-45625874 | | | A010 | Santakumar | Chennai | 0.14 | 007-22388644 | | | A012 | Lucida | San Jose | 0.12 | 044-52981425 | | | A005 | Anderson | Brisban | 0.13 | 045-21447739 | | | A001 | Subbarao | Bangalore | 0.14 | 077-12346674 | | | A002 | Mukesh | Mumbai | 0.11 | 029-12358964 | | | A006 | McDen | London | 0.15 | 078-22255588 | | | A004 | Ivan | Torento | 0.15 | 008-22544166 | | | A009 | Benjamin | Hampshair | 0.11 | 008-22536178 | | +------------+----------------------+--------------------+------------+-----------------+---------+ Agent Table
  • 119. www.webstackacademy.com Single Row Subquery Example SQL Statement : SELECT agent_name ,agent_code,phone_no FROM agents WHERE agent_code=(SELECT agent_code FROM agents WHERE agent_name ='Alex'; ● Output AGENT_NAME AGENT_CODE PHONE_NO Alex A003 075-12458969
  • 121. www.webstackacademy.com Multiple Row Subquery ● Multiple row subquery returns one or more rows to the outer SQL statement. We can use IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.
  • 122. www.webstackacademy.com Multiple Row Subquery[Using IN] Order Table ORD_NUM ORD_AMOUNT ADVANCE_AMOUNT ORD_DATE CUST_CODE AGENT_CODE ORD_DESCRIPTION ---------- ---------- -------------- --------- --------------- --------------- ----------------- 200114 3500 2000 15-AUG-08 C00002 A008 200122 2500 400 16-SEP-08 C00003 A004 200118 500 100 20-JUL-08 C00023 A006 200119 4000 700 16-SEP-08 C00007 A010 200121 1500 600 23-SEP-08 C00008 A004 200130 2500 400 30-JUL-08 C00025 A011 200134 4200 1800 25-SEP-08 C00004 A005 200108 4000 600 15-FEB-08 C00008 A004 200103 1500 700 15-MAY-08 C00021 A005 200105 2500 500 18-JUL-08 C00025 A011 200109 3500 800 30-JUL-08 C00011 A010 200101 3000 1000 15-JUL-08 C00001 A008 200111 1000 300 10-JUL-08 C00020 A008 200104 1500 500 13-MAR-08 C00006 A004 200106 2500 700 20-APR-08 C00005 A002 200125 2000 600 10-OCT-08 C00018 A005 200117 800 200 20-OCT-08 C00014 A001 200123 500 100 16-SEP-08 C00022 A002 200120 500 100 20-JUL-08 C00009 A002 200116 500 100 13-JUL-08 C00010 A009 200124 500 100 20-JUN-08 C00017 A007 200126 500 100 24-JUN-08 C00022 A002 200129 2500 500 20-JUL-08 C00024 A006 200127 2500 400 20-JUL-08 C00015 A003 200128 3500 1500 20-JUL-08 C00009 A002 200135 2000 800 16-SEP-08 C00007 A010 200131 900 150 26-AUG-08 C00012 A012 200133 1200 400 29-JUN-08 C00009 A002 200100 1000 600 08-JAN-08 C00015 A003
  • 123. www.webstackacademy.com Multiple Row Subquery SQL Statement : SELECT ord_num,ord_amount ,ord_date ,cust_code ,agent_code FROM orders WHERE agent_code IN (SELECT agent_code FROM agents WHERE working_area ='Banglore'); ● Output : ORD_NUM ORD_AMOUNT ORD_DATE CUST_CODE AGENT_CODE 200130 25000 30-JUL-08 C00025 A011 200105 2500 18-JUL-08 C00025 A011
  • 124. www.webstackacademy.com Correlated Subquery SQL Correlated Subqueries are used to select data from a table referenced in the outer query. The subquery is known as a correlated because the subquery is related to the outer query.
  • 125. www.webstackacademy.com Correlated Subquery SQL Statement :- SELECT a.ord_num ,a.ord_amount ,a.cust_code ,a.agent_code FROM orders a WHERE a.agent_code =(SELECT b.agent_code FROM agents b WHERE b.agent_name='Alex'); Output :- ORD_NUM ORD_AMOUNT CUST_CODE AGENT_CODE 200127 2500 C00015 A003 200100 1000 C00015 A003
  • 127. Web Stack Academy (P) Ltd #83, Farah Towers, 1st floor,MG Road, Bangalore – 560001 M: +91-80-4128 9576 T: +91-98862 69112 E: [email protected] www.webstackacademy.com