Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

SQL Notes

Uploaded by

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

SQL Notes

Uploaded by

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

27/12/2021:

Agenda:
 Functional Testing
 Background and need of Database Testing(With few
Examples)
 Why we need database?
 Why we need backend testing?
 What is SQL and what it can do?
 Popular DB’s Available in the market

Functional Testing :(Frond End(UI)+Backend


Testing(Database Testing))
- Behavior coverage
- Input domain coverage
- Error handling coverage
- Service level coverage
- Calculation based Coverage
- Backend Coverage(Database coverage/Database
Testing)

Web Based application:


Ex.1: Sign Up Form: (First Name, LastName, Email,
Mob,Address): If we have to check on UI==To check if
signup is success. We can check for success message.

Customers_Sign_up table:
- Validate Existence of the values in the database
table
- Validate Correctness of the values in the database
table
- Validate Completeness of the values in a database
table
Ex.2: Google.com: Whatever we search we get data from
DB(database)
- On UI 200 results
- Check same in DB and let’s say we get 250 results

What is database? Why we need database?--- Refer PPT

Database Systems:
Database: Storage Location: Collection of related data.
- Structured Data- IRCTC, Facebook, Flipkart,
Amazon, MSEB Board, MPSC
- Unstructured Data- Random Data—Social Media
Post- Data can not be stored in db in the form of
Database.
Database Management Systems (DBMS):
- To perform any operations on the data we need the
database management systems
- SQL Server,MySQL,Oracle,DB2,MongoDB

When we deal with structured data we use RDBMS.

SQL: Structured Query Language


SEquel: Simple English Query Language

Installation:
Windows 7: https://www.techbeamers.com/quick-steps-to-
install-mysql-on-windows/
Windows 10: https://youtu.be/OM4aZJW_Ojs

28/12/2021:
Agenda:
- Data Types in SQL
- Types of SQL Commands
Data Types in SQL:
- Numeric
- Character
- Date and time
Decimal(s,d):
S=Size
D=after decimal

Ex: 10.44
S=4
D=2
Decimal(4,2)

Ex. 2
10.4444
Decimal(6,4)

Types of SQL Commands:


DQL: Data Query Language: SELECT
DDL: Data Definition Language: CREATE, ALTER,
DROP, TRUNCATE
DML: Data Manipulation Language: SELECT, INSERT,
UPDATE, DELETE
DCL: Data Control Language: Grant, Revoke

29/12/2021:
Agenda: Data Definition Language: Create, Alter, Drop,
Truncate

CREATE TABLE:
Definition: It is the SQL Statement used to create a new table
in a database.
Syntax to Create a new Table:
CREATE TABLE table_name(
Column1 datatype,
Column2 datatype,
Column3 datatype,
.
.
ColumnN datatype);

Ex:
CREATE TABLE Persons(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255));
Syntax for Creating Database:
CREATE DATABASE database_name;
Ex.
CREATE DATABASE Pramod;

One Time Set-up: How to Start?


Show databases;
Create Database database_name;
Use database;
DROP:
Definition: It is used to drop an existing table from a database
Syntax for dropping table:
DROP Table table_name;
Ex:
DROP TABLE PersonsP;

Syntax for Dropping Database:


DROP DATABASE database_name;
Ex:
DROP DATABASE Prasad;

Before:
After:
TRUNCATE:
- It is used to delete the data from the table, but the
structure remains same.
- The SQL TRUNCATE TABLE command is used to delete
complete data from the table.
- You can also use DROP TABLE command to delete the
complete data but it will remove the complete table
structure from the database and you need to re-create that
table again if you have to store some data.
- It performs the same function as the DELETE Statement
without a WHERE Clause.
Syntax:
TRUNCATE TABLE table_name;
Ex:
TRUNCATE TABLE VCTC;

Before:
After:

30/12/2021:
Agenda:
- DDL: CREATE,DROP,TRUNCATE,ALTER
- DML: Data Manipulation Language: INSERT
INTO,SELECT
ALTER:
- It is used to add, delete or modify columns in a table.
If you want to ADD a column in a SQL Table:
Syntax:
ALTER TABLE table_name
ADD Column_name datatype;

Ex:
ALTER TABLE PersonsP
ADD EmailID varchar(255);
Before:
After:

If you want to delete column in a SQL Table:


Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
Ex:
ALTER TABLE PersonsP
DROP COLUMN EmailID;
Before:

After:

If you want to modify column in a SQL Table:


Syntax:
ALTER TABLE table_name
Modify column_name datatype;
Ex:
ALTER TABLE PersonsP
MODIFY LastName varchar(20);

If you want to Rename column in a SQL Table:


Syntax:
ALTER TABLE table_name
RENAME COLUMN Old_column_name to NewColumn_name;

ALTER TABLE personsp


RENAME COLUMN LastName to Surname;

Before:
After:

DML: Data Manipulation Language: INSERT INTO, SELECT,


INSERT INTO:
- It is SQL statement used to insert a single record or
multiple records in a database table.
Syntax:
1st way: Specify both the column_names and values to be inserted
into table.
INSERT INTO
table_name(Column1,Column2,Column3,…,ColumnN)
VALUES(Value1,Value2,Value3,..,ValueN);

Ex:
INSERT INTO
PersonsP(PersonID,LastName,FirstName,Address,City)
VALUES(1 ,’Ambhore’, ’Pramod’,’Kharadi’,’Pune’);

2nd Way:
- If you are adding values for all the columns of a table, you
do not need to specify the column names in the SQL query
- However Make Sure that the order of the values is in the
same order as columns in a table.
INSERT INTO table_name
VALUES(Value1,Value2,Value3,…,ValueN);

EX:
INSERT INTO PersonsP
VALUES(2 ,’Patil’, ’Prakash’,’Katraj’,’Pune’);

How to Insert Multiple Records at a time?


INSERT INTO PersonsP
(PersonID,LastName,FirstName,Address,City)
VALUES
(2,'Kale','Pramod','Kharadi','Pune'),
(3,'Patil','Prasad','Katraj','Pune'),
(4,'Mane','Mangesh','Chnadannagar','Pune');
SELECT:
- It is SQL statement used to fetch the data from a database
table
To fetch all the columns from the table:
Syntax:
SELECT * from table_name;
*stands for all columns
Ex:
SELECT * from PersonsP;

To fetch specified columns:


Syntax:
SELECT column1,column2,…,ColumnN
From table_name;

Ex:
SELECT PersonID, Address,City
From PersonsP;
31/12/2021:
Agenda:
- SELECT DISTINCT
- TOP Clause
- Aggregate Functions:
COUNT(),AVG(),SUM(),MIN(),MAX()

DISTINCT:
- It is SQL Clause/Keyword used in conjunction with
SELECT statement.
- Returns only DISTINCT Values
- Inside a table column often contains duplicate values,
sometimes we want unique values
- Only returns distinct records or values(Unique/Different
Values)
Syntax:
SELECT DISTINCT Column_name
FROM table_name;

Ex:
SELECT DISTINCT SALARY
FROM CUSTOMERS;

Before:
After:

TOP Clause:
- TOP Clause is used to fetch TOP N or X Percent of
records from the database table
- It is used in Conjunction with SELECT Statement.
- In MySQL TOP Clause is not supported so we have
LIMIT Clause.
- The SELECT TOP clause is used to specify the number of
records to return.
- The SELECT TOP clause is useful on large tables with
thousands of records. Returning a large number of records
can impact performance.
-
Syntax:
SELECT TOP Number|Percent Column_name
FROM Table_name;

Ex:
SELECT TOP 3 * from CUSTOMERS;
In MYSQL:
SELECT * FROM CUSTOMERS
LIMIT 3;

SELECT TOP 50 PERCENT * FROM Customers;

Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while Oracle
uses FETCH FIRST n ROWS ONLY and ROWNUM.
Aggregate Functions: COUNT(),AVG(),SUM(),MIN(),MAX()

- An aggregate function performs calculation on set of


values and returns a Single Value
MAX():
- It returns maximum value of a numeric column
- Returns largest value of a selected column
- Maximum value in a column EXCEPT NULL.
Syntax:
SELECT MAX(Column_name)
FROM table_name;

Ex:
SELECT MAX(SALARY)
FROM CUSTOMERS;
Before:

After:
MIN():
- It returns minimum value of a numeric column
- Returns smallest value of a selected column
- Minimum value in a column EXCEPT NULL.
Syntax:
SELECT MIN(Column_name)
FROM table_name;

03/01/2022:
Agenda: Aggregate Functions- AVG(), Count(),WHERE Clause

AVG():
- Function returns the average value of a numeric column
- It will apply for NON-NULL Values
- AVG=Sum(column_name)/COUNT(Column_name)
Syntax:
SELECT AVG(Column_name)
FROM table_name;
Ex:
SELECT AVG(SALARY)
FROM CUSTOMERS;

COUNT():
- Returns total number of records
Syntax:
SELECT COUNT(*) from CUSTOMERS

Ex:
SELECT MIN(SALARY)
FROM CUSTOMERS;

SUM():
- Sum of all NON-NULL values of a column
- It returns total sum of numeric column
Syntax:
SELECT SUM(Column_name)
FROM table_name;
Ex:
SELECT SUM(SALARY)
FROM CUSTOMERS;

WHERE Clause:
- This clause is used to specify a condition while fetching
data from a database table.
- If the given condition is satisfied then only it returns
specific value
- Used to fetch specific records from database table
- The WHERE Clause is used in DELETE and UPDATE.
Syntax:
SELECT Column1, Column2
FROM table_name
WHERE Condition;

Condition will be applied using below Operators:


>, <,=,>=,<=, AND, OR, NOT, IN, BETWEEN, LIKE
Ex:
SELECT C_ID,NAME, SALARY
FROM CUSTOMERS
WHERE SALARY=2000;
AND, OR, NOT:
- Operators used to combine multiple condition’s on a data
- Also called a Conjunctive Operators
- WHERE Clause can be combined with AND,OR,NOT
AND: It displays a record if all the conditions separated by AND are
true.
Syntax:
SELECT Column1,Column2
FROM table_name
WHERE [Condition1] AND [Condition2]…AND [ConditionN];

Ex:
SELECT * from Customers
WHERE AGE=32 AND SALARY=2000;
OR: If one condition is true then it will display a record
Syntax:
SELECT Column1,Column2
FROM table_name
WHERE [Condition1] OR [Condition2]…OR [ConditionN];

Ex:
SELECT * from Customers
WHERE AGE=32 OR SALARY=2000;

NOT: Display a record if condition is NOT True


Syntax:
SELECT column_name
From table_name
WHERE NOT Column_name=Value;

Ex:
SELECT * FROM CUSTOMERS
WHERE NOT Age=32;
IN Operator:
- It is used along with SELECT Statement
- It allows you to specify multiple values in a WHERE
Clause
- The IN Operator is shorthand for Multiple OR Conditions
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name IN(Value1,Value2,…,ValueN);

By USING OR:
WHERE [Condition1(Column_name=Value1)] OR
[Condition2(Column_name=Value2)]
OR[Condition3(column_name=Value3)]

WHERE Column_name=Value1 OR Column_name=Value2 OR


column_name=Value3
Ex:
SELECT *
FROM VCTC
WHERE Mockresult IN(6,7,8,9);

NOT IN Operator:
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name NOT IN(Value1,Value2,…,ValueN);
Ex:
SELECT *
FROM VCTC
WHERE Mockresult NOT IN(6,7,8,9);
04/01/2022:
Agenda: BETWEEN, LIKE, What is NULL Value? , How to
Check for Null Values?

BETWEEN:
- Selects values within a range
- Values Can be numbers, text or dates
- Start Value and end values are inclusive
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name BETWEEN Value 1 AND Value 2;

Ex:
SELECT Mockresult
FROM VCTC
WHERE Mockresult BETWEEN 8 AND 9;
NOT BETWEEN:
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name NOT BETWEEN Value 1 AND Value 2;

Ex:
SELECT Mockresult
FROM VCTC
WHERE Mockresult NOT BETWEEN 8 AND 9;

LIKE:
- Used with WHERE Clause to search specified condition in
table
- It is used to search specified Pattern in a column
There are two wildcards often used in conjuction with LIKE
Operator:
- The Percentage Sign(%) represents zero,one or Multiple
Characters
- The Underscore Sign(_) represents one Single Character

LIKE Operator Description

SELECT * FROM Customers Finds any value that starts with a


WHERE CustomerName LIKE
'a%'

SELECT * FROM Customers Finds any value that ends with a


WHERE CustomerName LIKE
'%a'

SELECT * FROM Customers Finds any values that have ‘or’


WHERE CustomerName LIKE in any Position.
'%or%'

SELECT * FROM Customers Finds any value that have r in


WHERE CustomerName LIKE second position.
'_r%'

SELECT * FROM Customers Finds any value that starts with a


WHERE CustomerName LIKE and are at least 3 characters in
'a_ _%' length

SELECT * FROM Customers Finds any values that starts with


WHERE ContactName LIKE a and ends with o
'a%o'

Null Value:
- A field with No Value
- Blank Value
- Null value is different than zero
- A field which is kept blank during record creation
How to check for NULL Values?
IS NULL:
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name IS NULL;

Ex:
SELECT SALARY
FROM Customers
WHERE SALARY IS NULL;

Select * from employeeself


WHERE ManagerID IS NULL;

IS NOT NULL:
Syntax:
SELECT Column_name
FROM table_name
WHERE Column_name IS NOT NULL;
Ex:
SELECT SALARY
FROM Customers
WHERE SALARY IS NOT NULL;

Ex:
Select * from employeeself
WHERE ManagerID IS NOT NULL;

05/01/2021:
Agenda: Data Manipulation Language (DML): (INSERT INTO,
SELECT, UPDATE, DELETE), UNION and UNION ALL,
GROUP BY Clause

UPDATE:
- It is used to modify existing records in a database table.
- Used to modify specific records based on WHERE Clause
Syntax:
UPDATE table_name
SET Column1=Value1,Column2=Value2,..,ColumnN=ValueN
WHERE Condition;
Ex:
UPDATE Customers
SET Name=’Prakash’, Address=’Chepok’
WHERE C_ID=1;

Update without WHERE Clause:


DELETE:
- Used to delete the existing records in a database table
- To DELETE particular record based on WHERE
Condition.
Syntax:
DELETE FROM table_name
WHERE Condition;

Syntax:
DELETE FROM PersonsNew
WHERE PersonID=4;
DELETE Without WHERE Clause:

UNION and UNION ALL:


- SQL Operators used to combine 2 or more result sets
- Allow us to write multiple select statements, retrieve the
desired results then combine them into final result set.
UNION:
- Union removes any duplicate records(Distinct records)
- Only keeps unique records
- Combine result set of two or more SELECT
Statements(and Displays Unique Records)

UNION ALL:
- Keep all records including duplicates
UNION and UNION ALL have some basic requirements of the
data being combined:
- There must same number of columns retrieved in each
SELECT Statement
- The Columns retrieved must be of similar datatype
- There Columns retrieved must be in same order in each
SELECT Statement.
06/01/2022:
Agenda: GROUP BY Clause, Having Clause, Order By Clause,
GROUP BY Clause:
- The GROUP BY Clause is utilized in SQL with SELECT
Statement to organize similar data into groups
- It combines the multiple records in single or more columns
using some functions. Generally these functions are called
as aggregate functions such as
MIN(),MAX(),COUNT(),AVG(),SUM().
- It is used with SELECT statement to make group of rows
based on the values of a specific column.
- The WHERE Clause is used to retrieve rows based on a
certain condition but it can’t be applied to Grouped Result.

Syntax:
SELECT Column_name(s)
FROM Table_name
WHERE Condition
GROUP BY Column_name
ORDER BY Column_name;
Points to Remember:
- GROUP BY Clause is utilized with SELECT Statement
- GROUP BY Clause aggregates the results on the basis of selected
column: MIN(),MAX(),SUM(),AVG().COUNT()
- GROUP BY Clause returns only one result per group of data
- GROUP BY Clause always follows WHERE Clause
- GROUP BY Clause always Preceedes the ORDER BY Clause.

Ex:
SELECT Country, Count(CustomerID)
FROM Customers
GROUP BY Country;

HAVING Clause:
- Having Clause is utilized in SQL as a conditional Clause
with GROUP BY Clause
- This Clause returns rows where aggregate function results
are matched with given condition only
- It is added to SQL because WHERE Clause cannot be
combined with aggregate functions
- WHERE only deal with Non-aggregated data or individual
records
- Having Clause is utilized with GROUP BY Clause

Compare Having and Where Clause in SQL: -


- In some cases, you need to filter out the individual records.
In such cases, you can use WHERE Clause, Whereas in
other cases you need to filter the groups with the specific
condition. In such cases, you can use HAVING Clause.
- WHERE Clause filters the records tuple by tuple while
HAVING Clause filters the whole group.
- A query may have both the clauses( WHERE and
HAVING Clause).
- Where Clause applied first and then Having Clause.
- WHERE Clause restricts records before GROUP BY
Clause, whereas HAVING Clause restricts groups after
GROUP BY Clause are performed.
- WHERE Clause can be utilized with SELECT, UPDATE,
DELETE, and INSERT, whereas HAVING can be utilized
only with SELECT statement
Syntax:
SELECT Column_name
FROM table_name
WHERE Condition
GROUP BY Column_name
HAVING Condition
ORDER BY Column_name;

Ex:
SELECT Country,Count(CustomerID)
FROM Customers
GROUP BY Country
HAVING Count(CustomerID)>5
ORDER BY Count(CustomerID) Desc;
Ex:
SELECT DeptID, AVG(SALARY)
FROM employee
GROUP BY DeptID
HAVING AVG(SALARY)>3000;
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

ORDER BY Clause:
- Used to sort the results in ascending or descending
- By default sorting order is ascending if we do not specify
the keyword
- To sort the results in descending use keyword: DESC
- To sort in Ascending order use keyword: ASC
Syntax:
SELECT Column_name
FROM table_name
ORDER By Column_name ASC|DESC;

Ex 1:
SELECT * FROM Customers
ORDER BY Country;
Ex 2:
SELECT * FROM Customers
ORDER BY Country DESC;

Aliases:
- Aliases are used to give a table or a column in a table a
temporary name
- It is to make the table name or column name more
readable
- It only exists for the duration of that query
- It is created using AS keyword.
Syntax:
SELECT Column_name AS alias_name
FROM table_name;

Ex:
Select C_ID AS CustomerID,
NAME As CustomerName,
AGE As CustomerAge,
ADDRESS As CustomerAddress,
SALARY As CustomerSALARY
from customers;
07/01/2022:
Agenda: Constraint, Types of Constraints, JOIN, Types of JOINs
Constraint:
- Used to limit the type of data that go inside the database
table columns
- Used to limit type of value
- Rules enforced on the data columns of a table in a database
- This ensures the accuracy and reliability of the data in the
table.
Types of Constraints:
NOT NULL: Ensures that a column can’t have null value.
UNIQUE: Ensures that all values in a column are different.
Default: Provides default value for a column when nothing is
specified
Primary Key(Unique+ NOT NULL): Uniquely identifies each
record in a database(One table can have only one Primary Key)
Ex: Phone Number, Adhar Card Number, PAN Card Number,
Student Roll Number, License Number, Passport Number, Student
Registration Number.
Check: Ensures that all the values in a column satisfy specified
condition. Ex: CHECK(Age>18)
Foreign Key:
- Used to link two tables together
- Uniquely identifies each record in any of the given
database table
- A foreign key is field(or collection of filed) in one table
that refers to Primary key of another table(We can have
one or More key)
- It is attribute or set of attributes that references to Primary
key of same table or Another table.
- It maintains referential integrity
Students:
Roll Number(pk) Name Address
1 A Delhi
2 B Mumbai
3 C Chennai
Courses:
CourseID Course_Name Roll Number(fk)
C1 DBMS 1
C2 Networks 2
10

Syntax:
CREATE TABLE table_name(
Fname varchar(255) NOT NULL,
Lname varchar(255) NOT NULL,
AdharID int UNIQUE,
State varchar(255) Default ‘Maharashtra’,
Age int CHECK(Age>18),
Primary Key(AdharID));

Ex:
Table 1: Customers:
CREATE TABLE CUSTOMERS(
C_ID int NOT NULL,
NAME Varchar(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS Char(25),
SALARY int,
Primary Key(C_ID));

Table 2: ORDERS
CREATE TABLE ORDERS(
OrderID int NOT NULL,
OrderDate DATE,
CustomerID int,
Amount int,
Primary Key(CustomerID),
FOREIGN KEY(CustomerID) REFERENCES
CUSTOMERS(C_ID));
JOIN:
- A JOIN Clause is used to combine rows from two or
more tables based on related column between them.
- Used to Join two or more tables
- Used by backend developers during integration testing to
join database tables of multiple modules.
Integration Testing:
Module 1=Tested Individually=Table1
Module 2=Tested Individually=Table2
Module 3=Tested Individually=Table3

10/01/2022:
Agenda: Types of Joins:
INNER JOIN: Returns records that have matching values in both the
tables.
LEFT (OUTER)JOIN: Returns all records from the left table and
the matched records from the right table
RIGHT (OUTER)JOIN: Returns all records from the Right table
and the matched records from the Left table
FULL (OUTER) JOIN: Returns all records when there is a match
either in Left or Right table.
SELF JOIN: Joining a table itself is called Self-JOIN.
INNER JOIN:
Syntax:
SELECT table1.Column1,table2.Column2
FROM table1
INNER JOIN table2
ON table1.CommonField(pk)=table2.CommonField(fk);

Ex:
SELECT Customers.C_ID, Customers.NAME, Orders.OrderDate,
Orders.Amount
FROM Customers
INNER JOIN Orders
ON Customers.C_ID=Orders.CustomerID;

LEFT JOIN:
Syntax:
SELECT table1.Column1,table2.Column2
FROM table1
LEFT JOIN table2
ON table1.CommonField(pk)=table2.CommonField(fk);
Ex:
SELECT Customers.C_ID, Customers.NAME, Orders.OrderDate,
Orders.Amount
FROM Customers
LEFT JOIN Orders
ON Customers.C_ID=Orders.CustomerID;

RIGHT JOIN:
Syntax:
SELECT table1.Column1,table2.Column2
FROM table1
RIGHT JOIN table2
ON table1.CommonField(pk)=table2.CommonField(fk);

Ex:
SELECT Customers.C_ID, Customers.NAME, Orders.OrderDate,
Orders.Amount
FROM Customers
RIGHT JOIN Orders
ON Customers.C_ID=Orders.CustomerID;

FULL JOIN:
Syntax:
SELECT table1.Column1,table2.Column2
FROM table1
FULL JOIN table2
ON table1.CommonField(pk)=table2.CommonField(fk);

Ex:
SELECT Customers.C_ID, Customers.NAME, Orders.OrderDate,
Orders.Amount
FROM Customers
FULL JOIN Orders
ON Customers.C_ID=Orders.CustomerID;
Select Cs.C_ID As Customer, Cs.NAME As CustomerName,
Od.OrderDate,Od.Amount As OrderAmount
FROM customers Cs
INNER JOIN orders Od
ON Cs.C_ID=Od.CustomerID;
11/01/2022:
Agenda: SELF JOIN, INDEX, VIEW, Stored Procedure, Nth
Highest Salary
SELF JOIN:
- A SELF JOIN is normal SQL JOIN tat joins one table to
itself
- Joining a table to itself can be useful when you want to
compare values in a column to other values in the same
column
- It can either be INNER JOIN or OUTER JOIN
- We have a table with Employee Data and each row
contains information about employee and his/her manager
- One of the columns in the Same table contains ID of a
Manager, Who is also an employee of the same company
and their managers are present in the same table
- We want to Display Employee Name & their Managers

EmployeID Employee Name ManagerID


1 Mike 3
2 David 3
3 Rogger Null
4 Joseph 2

Syntax/Example:
SELECT E1.Name AS EmployeeName,
E2.Name AS ManagerName
From EmployeeSelf E1
INNER JOIN EmployeeSelf E2
ON E1.ManagaerID=E2.EmployeeID;
INDEX:
- Indexes are used to retrieve data from the database more
quickly than otherwise.
- Users cannot see these indexes but they are used to speed
up the searches/queries.
Syntax:
CREATE INDEX index_name
ON table_name(Column1,Column2,…,ColumnN);
Ex:
CREATE INDEX VCTCMockResult on VCTC(Mockresult);

To See Indexes:
Show Index from table_name;
Show Index From VCTC;
To Remove Index:
DROP INDEX VCTCMockresult ON VCTC;
VIEW:
- A VIEW is a virtual table based on the result set of an
SQL Statement.
- A view Contains rows and columns just like real table
Syntax:
CREATE VIEW view_name
AS
SELECT Column1,Column2
FROM table_name
WHERE Condition;

Ex:
CREATE VIEW MockResultVCTC
AS
SELECT * FROM VCTC WHERE Mockresult>5;
12/01/2022:
Agenda: Stored Procedure, Nth highest Salary, Sub Query,How to
find duplicate records?, CASE Statement in SQL.

Stored Procedure:
- A stored procedure is a prepared SQL code that you can
save, So that code can be reused over and over again
- So if you have a query that you write over and over again,
save it as a procedure and then just call it to execute.
How to Create Stored Procedure?
Syntax in MySQL:
DELIMITER//
CREATE PROCEDURE Procedure_name
Begin
SQL Query
End
DELIMITER;

Syntax to call the Procedure:


Call Procedure_name;
Ex:
Delimiter//
CREATE PROCEDURE sp_getCustomers_list()
Begin
Select * from Customers WHERE SALARY>1500;
End//
Delimiter;

Call sp_getCustomers_list();
Syntax in SQL Server:

CREATE Procedure procedure_name


AS
SQL Statement
GO;

Syntax to call the Procedure:


EXEC Procedure_name;

Nth Highest Salary:

SELECT * FROM table_name ORDER BY Column_name DESC


LIMIT n-1,1;
This query will return the first row after the n-1 rows that should be
the nth highest record.
n=2—Second Highest Salary
select * from employeenthsalary order by salary desc LIMIT 2-1,1;
select * from employeenthsalary order by salary desc LIMIT 1,1;
n=3—Third highest Salary
select * from employeenthsalary order by salary desc LIMIT 3-1,1;
select * from employeenthsalary order by salary desc LIMIT 2,1;

Second Highest:
Select Max(Salary) From employeenthsalary where Salary<(Select
Max(Salary) from Employees);
Nth Highest Salary(2nd and 3rd ):
For nth highest Salary in MySQL:

How to select nth Highest Record in MySQL

In this section, we are going to learn how we can select the nth highest record in a database
table with the help of various techniques.
We can get the maximum (highest) or minimum (lowest) record in the database table very
easily by using the MAX() or MIN() function. But suppose we want to get the nth highest
record from the table (for example, get the second-most expensive salary from the employee
table). In that case, there is no function available to find it quickly, which makes it
complicated.

By performing the following steps, we can select the nth highest record in a MySQL database
table:

1. The first step is to sort the desired column in ascending order to get the n highest records,
which is the last record in the resultant output. See the below query:

SELECT * FROM table_name ORDER BY colm_name ASC LIMIT N;

2. After that, we need to sort the resultant output in descending order and get the first record.

SELECT * FROM (
SELECT * FROM table_name
ORDER BY colm_name ASC LIMIT N) AS temp_table
ORDER BY colm_name DESC LIMIT 1;

The above query can also be rewritten by using the LIMIT clause that constrains the number
of rows in the resultant output as follows:

SELECT * FROM table_name ORDER BY colm_name DESC LIMIT n - 1, 1;

This query will return the first row after the n-1 rows that should be the nth highest record.

Example:

Let us understand how to get the nth highest record from the table with the help of an
example. First, we will create an Employee table using the below query:

CREATE TABLE Employee (id int, name varchar(40), salary int);

Next, insert records using the below query:

INSERT INTO Employee VALUES


(1, 'Mike', 3000),
(2, 'John', 4000),
(3, 'Shane', 3000),
(4, 'Biden', 5000),
(5, 'Bravo', 7000);

Suppose we want to get the second highest salary of an employee (n = 2) in the Employee
table; we can use the below statement:

SELECT name, salary FROM Employee ORDER BY salary DESC LIMIT 1, 1;

Suppose we want to get the third-highest salary of an employee (n = 3) in the Employee


table; we can use the below statement:

SELECT name, salary FROM Employee ORDER BY salary DESC LIMIT 2, 1;

Get the nth highest record using a subquery:

We can also get the nth highest record with the help of subquery, which depends upon the
main query and processed for every record returned by the main query. This technique is
rarely used because of its slow performance/execution speed.

See the below query that returns nth highest record using the subquery:

SELECT name, salary FROM Employee AS emp1


WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM Employee emp2
WHERE emp2.salary > emp1.salary)

See the below query that returns the second highest salary from the employee table using the
sub query:

SELECT name, salary FROM Employee AS emp1


WHERE 2-1 = (SELECT COUNT(DISTINCT salary) FROM Employee AS emp2
WHERE emp2.salary > emp1.salary);

Nth highest Salary in SQL Server:


Use the following script to create Employees table

Create table Employees

(ID int ,

FirstName varchar(50),

LastName varchar(50),

Gender varchar(50),

Salary int

);

Insert into Employees Values(1,'Ben','Hoskins','Male',70000);

Insert into Employees values(2,'Mark','Hastings','Male',60000);

Insert into Employees values(3,'Steve','Pound','Male',45000);

Insert into Employees values(4,'Ben','Hoskins','Male',70000);

Insert into Employees values(5,'Philip','Hastings','Male',45000);

Insert into Employees values(6,'Mary','Lambeth','Female',30000);

Insert into Employees values(7,'Valarie','Vikings','Female',35000);

Insert into Employees values(8,'John','Stanmore','Male',80000);

/* Create a table called NAMES */

Create table Employees

(ID int ,
FirstName varchar(50),

LastName varchar(50),

Gender varchar(50),

Salary int

);

/* Create few records in this table */

Insert into Employees Values(1,'Ben','Hoskins','Male',70000);

Insert into Employees values(2,'Mark','Hastings','Male',60000);

Insert into Employees values(3,'Steve','Pound','Male',45000);

Insert into Employees values(4,'Ben','Hoskins','Male',70000);

Insert into Employees values(5,'Philip','Hastings','Male',45000);

Insert into Employees values(6,'Mary','Lambeth','Female',30000);

Insert into Employees values(7,'Valarie','Vikings','Female',35000);

Insert into Employees values(8,'John','Stanmore','Male',80000);COMMIT;

/* Display all the records from the table */

SELECT * FROM Employees;

To find the highest salary it is straight forward. We can simply use the Max() function as
shown below.

Select Max(Salary) from Employees;

To get the second highest salary use a sub query along with Max() function as shown
below.

Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees);

To find nth highest salary using Sub-Query

SELECT TOP 1 SALARY


FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY;

Sub Query:

A subquery is a SQL query nested inside a larger query.

A subquery may occur in:

- A SELECT clause
- A FROM clause
- A WHERE clause

A subquery is usually added within the WHERE Clause of another SQL


SELECT statement.

- You can use the comparison operators, such as >, <, or =. The
comparison operator can also be a multiple-row operator, such as IN,
ANY, SOME, or ALL.
- A subquery can be treated as an inner query, which is a SQL query placed
as a part of another query called as outer query.
- The inner query executes first before its parent query so that the results of
the inner query can be passed to the outer query.

Ex:
SELECT first_name, last_name
FROM employees
WHERE department_id
IN (SELECT department_id FROM departments WHERE
department_name='IT');

How to find/delete Duplicate records?

CREATE TABLE contacts (

id INT PRIMARY KEY AUTO_INCREMENT,

first_name VARCHAR(50) NOT NULL,

last_name VARCHAR(50) NOT NULL,


email VARCHAR(255) NOT NULL

);

Truncate table contacts;

INSERT INTO contacts (first_name,last_name,email)

VALUES ('Carine ','Schmitt','carine.schmitt@verizon.net'),

('Jean','King','jean.king@me.com'),

('Peter','Ferguson','peter.ferguson@google.com'),

('Janine ','Labrune','janine.labrune@aol.com'),

('Jonas ','Bergulfsen','jonas.bergulfsen@mac.com'),

('Janine ','Labrune','janine.labrune@aol.com'),

('Susan','Nelson','susan.nelson@comcast.net'),

('Zbyszek
','Piestrzeniewicz','zbyszek.piestrzeniewicz@att.net'),

('Roland','Keitel','roland.keitel@yahoo.com'),

('Julie','Murphy','julie.murphy@yahoo.com'),

('Kwai','Lee','kwai.lee@google.com'),

('Jean','King','jean.king@me.com'),

('Susan','Nelson','susan.nelson@comcast.net'),

('Roland','Keitel','roland.keitel@yahoo.com');

Select * from contacts;

SELECT * FROM contacts

ORDER BY email;

SELECT

email,

COUNT(email)

FROM
contacts

GROUP BY email

HAVING COUNT(email) > 1;

SELECT

first_name, COUNT(first_name),

last_name, COUNT(last_name),

email, COUNT(email)

FROM

contacts

GROUP BY

first_name ,

last_name ,

email

HAVING COUNT(first_name) > 1

AND COUNT(last_name) > 1

AND COUNT(email) > 1;

-- to remove duplicate records using Delete JOIN

DELETE S1 FROM contacts AS S1

INNER JOIN contacts AS S2

WHERE S1.id < S2.id AND S1.email = S2.email;

CASE Statement:
The CASE statement goes through conditions and returns a value when the first condition is met
(like an if-then-else statement). So, once a condition is true, it will stop reading and return the
result. If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.


CASE Syntax:

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

Example:

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

Example for Practice:

Create table Students(ID int,name varchar(100),marks int,Grade char(20));

Insert into Students(ID,name,marks) values(1,'FEMI UTTI',78),(2,'RANSOM


KUTTI',68),(3,'FEMI',62),(4,'INNOCENT',57),(5,'MUSA',53),(6,'JOHN',47),(7,
'MATHEW',43),(8,'RABIU',39);

Select * from Students;

UPDATE Students

SET Grade = (

CASE

WHEN marks > 90 THEN 'A+'

WHEN marks > 70 AND marks<80 THEN 'A'

WHEN marks > 50 AND marks<70 THEN 'B'

WHEN marks >= 40 AND marks<50 THEN 'C'


WHEN marks < 40 THEN 'Fail'

ELSE '(F) FAIL'

END

);

INSERT INTO SELECT:

The INSERT INTO SELECT statement copies data from one table and inserts it into another
table.

The INSERT INTO SELECT statement requires that the data types in source and target tables
matches.

Note: The existing records in the target table are unaffected.

INSERT INTO SELECT Syntax

Copy all columns from one table to another table:

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

How to connect to Database?

Prerequisite: Hostname, Username, Password, Default Schema


VIMP Links: https://www.w3resource.com/sql-exercises/challenges-1/index.php

Few Additional Topics:

What is DCL?
DCL (Data Control Language) includes commands like GRANT and
REVOKE, which are useful to give “rights & permissions.” Other permission
controls parameters of the database system.

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

Examples of DCL commands:


Commands that come under DCL:

 Grant
 Revoke

Grant:
This command is use to give user access privileges to a database.

Syntax:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

For example:
GRANT SELECT ON Users TO'Tom'@'localhost;

Revoke:
It is useful to back permissions from the user.

This command withdraws the user’s access privileges given by using the
GRANT command.

Syntax:
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}

For example:
REVOKE SELECT, UPDATE ON student FROM BCA, MCA;

What is TCL?
Transaction control language or TCL commands deal with the transaction
within the database.

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.

Commit
This command is used to save all the transactions to the database.

Syntax:
Commit;

For example:
DELETE FROM Students
WHERE RollNo =25;
COMMIT;

Rollback
Rollback command allows you to undo transactions that have not already
been saved to the database.

Rollbacks a transaction in case of any error occurs.

Syntax:
ROLLBACK;

Example:
DELETE FROM Students
WHERE RollNo =25;

SAVEPOINT
This command helps you to sets a savepoint within a transaction.

Syntax:
SAVEPOINT SAVEPOINT_NAME;

Example:
SAVEPOINT RollNo;

What is Trigger in SQL?


A SQL trigger is a database object which fires when an event occurs in a database.
We can execute a SQL query that will "do something" in a database when a change
occurs on a database table such as a record is inserted or updated or deleted. For
example, a trigger can be set on a record insert in a database table. For example, if
you want to increase the count of blogs in the Reports table when a new record is
inserted in the Blogs table, we can create a trigger on the Blogs' table on INSERT
and update the Reports table by increasing blog count to 1.

Types of Triggers
There are two types of triggers:

1. DDL Trigger
2. DML Trigger

What is Normalization?
Normalization is a database design technique that reduces data
redundancy and eliminates undesirable characteristics like Insertion,
Update and Deletion Anomalies. Normalization rules divides larger tables
into smaller tables and links them using relationships. The purpose of
Normalisation in SQL is to eliminate redundant (repetitive) data and ensure
data is stored logically.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to
identify a record uniquely

In our database, we have two people with the same name Robert Phil, but
they live in different places.
Composite key in Database

Hence, we require both Full Name and Address to identify a record


uniquely. That is a composite key

Database – Foreign Key


In Table 2, Membership_ID is the Foreign Key

Foreign Key references the primary key of another Table! It helps connect
your Tables

 A foreign key can have a different name from its primary key
 It ensures rows in one table have corresponding rows in another
 Unlike the Primary key, they do not have to be unique. Most often
they aren’t
 Foreign keys can be null even though primary keys can not
Why do you need a foreign key?
Suppose, a novice inserts a record in Table B such as

Suppose, a novice inserts a record in Table B such as


You will only be able to insert values into your foreign key that exist in the
unique key in the parent table. This helps in referential integrity.

The above problem can be overcome by declaring membership id from


Table2 as foreign key of membership id from Table1

Now, if somebody tries to insert a value in the membership id field that


does not exist in the parent table, an error will be shown!

You might also like