0% found this document useful (0 votes)
17 views20 pages

SQL Session

SQL is a standard language used for storing, manipulating, and retrieving data in databases. It is essential for tasks like manual testing, API testing, and front-end testing, as it allows for evidence collection from databases. The document covers various SQL commands, types, and operations, including data definition, manipulation, retrieval, and control, along with examples and syntax for each command.

Uploaded by

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

SQL Session

SQL is a standard language used for storing, manipulating, and retrieving data in databases. It is essential for tasks like manual testing, API testing, and front-end testing, as it allows for evidence collection from databases. The document covers various SQL commands, types, and operations, including data definition, manipulation, retrieval, and control, along with examples and syntax for each command.

Uploaded by

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

SQL: Standard Query Language

--> This language is used for Storing , manupulating and retriving data in database

--> Client ----- SQL-----Server(Database)

***********************************************************************************
******
Why to learn SQL
--> Manual Testing
--> API Testing
-- Evidence collection from DB
--> Front End Testing(UI Testing)
-- Evidence collection from DB
***********************************************************************************
*******

* Database:
-- It is group of objects(tables,views,synonyme,procedure,trigger,schema etc....)
- Collection of meaningful data

* DBMS( Database Management System)


- DBMS is management system which manages the database objects and data
Activity/Task
- Create C
- Inserting data U
- Retriving / Fetching data R
- Deleting data from objects D

***********************************************************************************
************
Database Software /Tools--

1. RDBMS(Relational Databse Management System)


- Relationship between the databse objects
E.x :- Oracle,MS-SQL server, IBM DB2, MySQL(free source), Sybase, Teradata....

--> DBMS
-- MS-Access, D-Base,FoxPro etc...
***********************************************************************************
****************

Database Component:

1. DB Client
This one is interface and used for connecting with database

2. DB Server
Its storage where all database objects and data are stored

SQL-- It is language used to communicate with the databse objetcs

***********************************************************************************
*********

Data:
Information that vavaible or recorded
--- text,audio,video,image etcc......
***********************************************************************************
**********
Different Ways to connect with Database

1) MySQL Workbench--: GUI Mode

2) Using Command line mode:- cmd


Go to your path location of mysql file with bin and type as cmd--> click enter----
> it will open cmd file
Type as :- mysql -u root -p
Enter password:- **********
use DB name(ex.world)
Describe tablename(e.x-country)

3)Using Shell
Type '\help' or '\?' for help; '\quit' to exit.
MySQL JS > \connect root@localhost:3306
Please provide the password for 'root@localhost:3306': **********

Convert JS(Javascript)to sql mode


MySQL localhost:3306 ssl JS > \sql

MySQL localhost:3306 ssl SQL > use world;


Default schema set to `world`.
Fetching table and column names from `world` for auto-completion... Press ^C to
stop.
MySQL localhost:3306 ssl world SQL > describe country;

4) Using command line client


Go to command line client tool which you have downloaded

Enter password: **********


mysql> use world;
Database changed
mysql> describe country
-> ;

***********************************************************************************
*************************
***********************************************************************************
*************************

SQL Command Types

1) Data Defination Language(DDL)


- Create
- Alter
- Drop
- Truncate
- Rename

2) Data Manipulation Language(DML)


- insert
- update
- delete

3) Data Retrival Language/Data Query Language(DQL)


- Select

4) Transaction control Language(TCL)


- commit
- rollback
- save point

5) Data control Language(DCL)


- grant
- revoke

***********************************************************************************
*************************

1. CREATE:
- This is belong to DDL
Create statement is used for
---> To create the DB
---> To create the table

a) CREATE Database

Syntax: create database <database_name>;


E.x: create database Banking;

b) Show Database
- this staement is used to find all databse list in your mysql
Syntax:
show databases;
e.x
show databases;

c) Create Table
-- In your DB lot of tables available or need to create
- This statement is used to create table in your DB

Syntax:
create table table_name(
col_name1 datatype,
col_name2 datatype,
col_name3 datatype)

E.x
create table EMP_DETAILS(
ID int (255), unique
Fname varchar(255), sddshdhdhdh845858568###@@@@@
Lname varchar(255),
Age int(512),
Mobile varchar(255), 99999999999
EmailID varchar(255),
Address varchar(200));

** INSERT INTO
- This statement used to insert records into table
Two Ways
1) If we need to insert all records of columns in a single time
Note: Order of vaules is same as order of column names available in table

Insert Into
Syntax:
INSERT INTO table_name

values(value1,value2,value3….....);

E.x insert into EMP_DETAILS


Values(1,'Ajay','Patil',26,9999999999,'[email protected]','Pune'),

(2,'Sachin','Pawar',28,8888888888,'[email protected]','Mumbai'),

(3,'Pooja','Jadhav',25,44444444444,'[email protected]','Pune'),
(4,'Ritu','Singh',22,222222222,'[email protected]','Banglore'),
(5,'Pradeep','Mehra',31,6666666666,'[email protected]','Chennai'),

(6,'Vivek','Kulkarni',38,77777777777,'[email protected]','Solapur');

Syntax:
INSERT INTO table_name
(ID,Fname,Lname, mailID,Address)
values(value1,value2,value3….....);

2) If we need to insert only single or couple of records at time without some


column names
E.X Suppose Age and Mobile number we are not intersted to insert with record then

Syntax:
INSERT INTO table_name
(ID,Fname,Lname, mailID,Address)
values(value1,value2,value3….....);

***********************************************************************************
***************************

--> DELETE:
- DML type
- This command is used to remove one or more rows from a table
- After removing the structure of table remains exist
- In this case we are working on data and not on table
- Rollback of data is possible
- When we are deleteing the complete table then all records of data is deleted but
its in sequence. So it is time consuming as compare to DROP and Truncate

SYNTAX
a) DELETE FROM <DATBASE>
b) DELETE FROM <Table_Name>
c) DELETE FROM Table_Name where col_name=value

E.x DELETE FROM MEASSY where id=1;


*************************************************************

---> DROP
- DDL
- Used to remove database and table from RDBMS
- used to remove existing table along with structure from database
- Rollback is not possible
SYNTAX:
DROP DATABASE <DATABASE_NAME>;
DROP TABLE <TAble_NAME>;

EX.
DROP TABLE emp1;

********************************************************************
--> TRUNCATE

- Used to remove all reords of table


- after removing the table Structure of Table is remains exist
- Rollback is not possible
- Synatax:
TRUNCATE database <DATABASE_NAME>
TRUNCATE table <Table_Name>

E.x

*******************************************************************************

Agenda
---> SELECT
--> Where
--> Distinct

# SELECT

Select is a command used to selecting records from table

---> Way1:
Select all records available from table

* --> Indicates that have been selected all records from table

SYNTAX:

Select * from table_name


E.x
Select * from measy

---> Way2:
We can select few columns or attributes from table

Select col1,col2,col3 from table_name

Select ID,Fname,Mobile from measy


**********************************************************************

## Where
- It is clause
- Whenever condiction will come o=into picture then befire that condition we need
toi mention where clause

SYNTAX
Select * from table_name where condition;

ID Fname Lname Age Mobile EmaiID Address


1 Ajay Patil 26 9999999999 [email protected] Pune
2 Sachin Pawar 28 8888888888 [email protected] Mumbai
3 Pooja Jadhav 25 4444444444 [email protected] Pune
4 Ritu Singh 22 2222222222 [email protected] Banglore
5 Pradeep Mehra 31 6666666666 [email protected] Chennai
6 Vivek Kulkarni 38 7777777777 [email protected] Solpaur

E.x Write a query to get the employee details whose are belong to Pune
select * from meassy where address='pune';

E.x Write a query to get the employee details whose having age is greater that 29
Select * from meassy where age >29;

E.x Write a query to get the ID , Fname and Mobile number whose name is Pooja
Select ID,Fname,Mobile from meassy where Fname='pooja';

###################################################################################
################

* Distinct

- This one used to return only distinct values


Note: If number of columns are consider in distinct query then system will skip the
records if both columns values are found to be duplicate

SYNTAX:

Select distinct col_name from table_name


or
Select distinct col_name1,col_name2 from table_name

E.x
Select distinct Address from meassy;

***********************************************************************************
***************************

---> UPDATE:

Update query is used to update the existing records in a table

SYNTAX:
UPDATE table_name SET col1=Value,col2=value where condition
E.x
UPDATE sheet3 set age=27,mobile=333333333 where ID=3;

***********************************************************************************
****************************
AND,OR, NOT Operators

- Where clause is combined with AND,OR,NOT operators


- Note: WHen we need to apply more than one condition for getting oupcome then we
are using AND,OR operator
AND: If both condition must be true
OR- If any one of condition is true

# AND
- It disply records from table if all condiotion are true
- Each condition is seperated by "AND"

E.x:
You are eligible for GOVT EXAM if you have SSC=60% AND HSC/DIPLOMA=60% AND
Degree=60%;

SYNTAX:
Select * from table_name where condition1 AND condition2 AND condition3.....;

E.x:
Select * from Worker where DEPARTMENT='Admin' AND SALARY>=500000;
***********************************************************************************
*************************************

## OR

- It disply records from table if any condition is true


- Each condition is seperated by "OR"

E.x:
You are eligible for EXAM if you have SSC=60% OR HSC/DIPLOMA=60% OR Degree=60%;

SYNTAX:
Select * from table_name where condition1 OR condition2 OR condition3.....;

E.x:
Select * from Worker where DEPARTMENT='Admin' OR SALARY>=500000;

***********************************************************************************
****************************************

## NOT
- It display the records if condion(s) is not true

Synatx:
Select * from table_name where NOT condition;

E.x
Select * from worker where NOT DEPARTMENT='Manager';
***********************************************************************************
**************************

## MIN,MAX,SUM,AVG,Count:---> Aggregate FUnction

* MIN():
- Minimum
- It returns the samllest value from selected column
Syntax:
Select min(column_name) from table_name;
E.X
Select min(Age) from Worker;

Way2: With Condition


Note: Query will be executed by considering condition only and find the min value
of that
Synatx:
Select min(column_name) from Table_Name where condition;E.x
E.x
select min(salary) from Worker where DEPARTMENT='Account';
***********************************************************************************
*

# MAX()
- Maximum
- It returns the largest value from selected column
Syntax:
Select max(column_name) from table_name;
E.X
Select max(Age) from Worker;

Way2: With Condition


Note: Query will be executed by considering condition only and find the max value
of that
Synatx:
Select max(column_name) from Table_Name where condition;E.x
E.x
select max(salary) from Worker where DEPARTMENT='Account';
select max(JOINING_DATE) from Worker where Salary<=90000;
***********************************************************************************
**********

# SUM()
- Summation
- It applies on numeric coulmn only
SYNTAX:

Select sum(Column_name) from table_name;

Select sum(column_name) from table_name where condition;

Select sum(Salary) from Worker where DEPARTMENT='HR';

***********************************************************************************
***********

# AVG()
- Average
- It applies on numeric column only

SYNATX:

Select avg(column_name) from table_name;

Select avg(column_name) from table_name where condition

***********************************************************************************
********************************

# count()
- It return the number of rows that matches with given condition

Note:If any records having null values then its not counted.

SYNTAX:
Select count(column_name) from table_name;
Select count(FIRST_NAME) from Worker ;

Select count(column_name)from tahble_name where condition


Select count(FIRST_NAME) from Worker where DEPARTMENT='HR';

***********************************************************************************
*******************************

* LIMIT/TOP

limit: Used in MYSQL


TOP: Used in SQL Server

Every time their is no need to d=fetch all records from DB.


- We need to fectch couple of recotds And this is defined by linmit querey
E.x: Suppose have 10,000 User in DB. And we need to fetch only 100 from them. so
for that

Synatx:
Select * from Table_name limit n;

n:- Total number of records which interested to fetch and display.


Select * from Worker limit 3;

***********************************************************************************
***************************

# Order BY
Used to sort the result set in ascending or descending order
--> By deafult sorting is ascending : "ASC"
--> To sort in descending order we need to use "DESC" keywords

Ascending: ASC: Optional


Descending: DESC

Syntax: Ascending Order


Select * from table_name order by column_name;
or
Select * from table_name order by column_name ASC;

Syntax:Descending Order

Select * from table_name order by column_name DESC;

***********************************************************************************
*******************************

--> Between Operrator


--> Group by statement
--> LIKE operator// Wild Card
--> Having clause

1. Between Operator

It gives/display records which supposed to be in range which provided

Range:
Initial Value-----------------Final value
The values can be number, text, date

SYNtax:
Select * from table_name where column_name between value1 and value2
E.x:
Select * from Worker where FIRST_NAME between 'Niharika' and 'Vivek';

Select * from Worker where WORKER_ID between '3' and '5';

********************************************************************************

2. Group By
- It gives the result of groups of rows that have same value into rows
- Always used to be used with aggreate functions( min(),max(),avg(),sum(),count())

Syntax:
Select * from table_name group by column_name

Select column_name, count(column_name) from table_name group by column_name

Select * from Worker group by DEPARTMENT;


Select * from Worker group by JOINING_DATE;
Select FIRST_NAME, count(WORKER_ID) from worker group by DEPARTMENT order by
DEPARTMENT DESC;

***********************************************************************************
**************************

** LIKE Operator || Wild Card

LIKE:
--> It always used with Where Clause
--> Used to search specififc conditional data in a column
Wild Crads:- underscore (_)
percentile (%)

Rules:

% --> zero,one or multiple character


_ --> represents one/single character
__ --> Two character
___ ---> Three character

Syntax:

Select * from table_name where column_name LIKE "pattern"


Select * from table_name where coulmn_name LIKE '%j';

a) End with specific alphabet


E.x: Pankaj ---> %j Pooja , Roopa,
Vinita ----> %a
Raj --> %j

E.x
Sagar ---> %r

b) Start with specific alphabet


E.x Pankaj ---> P% , Pandit, Prathmesh

3) E.X: Pankaj

P_____-----> Pankaj

Pooja ---> P____


Priya --> P____

4) Pooja----> ____a

5) Combine of _ and %

Roopa----> R%
Ro%
Roo%
Roop%

R____
Ro___
Roo__
Roop_

__op_
%p_

Monica ---> %n%a

***********************************************************************************
**********************************

## Salary

--> Highest Salary


--> 3rd Highest Salary
--> 15th Highest Salary
--> minimum Salary
--> Top 3 Highest salary

Synatx:
Select * from table_name order by column_name desc n,k;
where
n---> skip that value
k--> kth salary

Highest Salary n k
1 0 1
2 1 1
3 2 1
4 3 1

15 14 1
1,2,3 0 3
1,2,3,4,5 0 5
3,4,5 2 3

1. Highest Salary

E.x. Select * from worker order by salary desc limit 0,1;

2. 2 highest Salary

Select * from worker order by salary desc limit 1,1;

3. 15th Highest salary

Select * from worker order by salary desc limit 14,1;

4. Minimum 1st Salary

Select * from worker order by salary asc limit 0,1;

************************************************************************

TOP 3 salary

Syntax:
Select * from table_name order by column_name desc limit n,k
****************************************************************************
## By Using Aggregate functions we can find salary

For getting 3r highest salary:

Select max(salary)from table_name where salary <


(Select max (salary) from table_name where salary <
(Select max(salary) from table_name
))

***********************************************************************************
*******************************
***********************************************************************************
*******************************

-- Union/Union All
--> SQL Constraints

* Union
Union combines the result of two or more tables.
- This is operator

Rules:
1. The number of column in each select statement must match
2. The data types in the cloumns should be same
3. The columns in each select statement must be in same order

Note: The union operator selects only distinct values by default and it doesnt
select duplicate values::--- Applicable on single column name

Syntax:
Select * from table_name1
union
Select * from tabel_name2
union
Select * from table_name3

Syntax
Select column_name1, column_name2 from table_name1
union
Select column_name1, column_name2 from table_name2

E.x:
Select Fname from Gold
union
Select Fname from Silver

********************************
* Union All
Union all resolves concept of removing duplicate values if single coumn name is
selected

Select Fname from Gold


union all
Select Fname from Silver
***********************************************************************************
**************************

SQL Constrains
-- Rules that apply on type of data in a table

Syntax:
create table table_name (
column_name1 data_type constraints,
column_name2 data_type constraints,
.
.
);

E.x
create table Silver (
EmpID int (255) Not Null,
Fname varchar(255) Unique,
Lname varchar (255),
EmailId varchar (255) not null,
Age int (255) null,
city varchar (255));

Types of Constrains:
1) Not Null
2) Unique
3)Primary key
4) Foreign Key
5) Default
6) Check

1) Not Null
- Column can not have null values
- Null Value means have zero or blank record

Syntax:
Create Table Table_Name
(
ID int(255) NOT NULL,
Name varchar(255) NOT NULL,
Address varchar(255)
);

You will not be allowed to insert a new record in the table without specifu=ying
any values to this field.

2) Unique
This constraint helps to uniquely identify each row in the table
- All values are unique means no duplicate value allowed in column

Syntax:
Create table table_name(
ID int(255) NOT NULL UNIQUE,
Name varchar(255),
Address varchar(255)
);

- We can have more than one unique column in table

3) Primary Key:
- Its combination of NOT NULL + UNIQUE
- Only 1 primary key is available in a table

Syntax:
Create table table_name(
ID int(255) ,
Name varchar(255),
Address varchar(255)
Primary key(ID)
);

4) Foreign Key:
- Creating link to join two different tables
- prevents actions from destroying links between table

5) Default
Set a default value for a column if no value is specified
E.x: If at the time of entering new records in the table if the user does not
specify any value for those fields then deafult value will be assigned to them

Syntax:
Create table table_name(
ID int(255) ,
Name varchar(255),
Address varchar(255)
Age int(255) DEFAULT 18
Primary key(ID)
);

6) Check
- Using the check constraint we can specify a condition for a field which should be
satissfied at the time of entering values for this field.

Syntax:
Create table table_name(
ID int(255) ,
Name varchar(255),
Address varchar(255),
Age int(255) NOT NULL CHECK(AGE>=18),
Primary key(ID)
);

User will not be allowed to enter any records in the table with AGE<18

***********************************************************************************
**************************************************************
- JOIN
- Having Clause
- Alter
* Joins:
A join is used to combine rowsfrom two or more tables, based on a related column
between them.

1) Inner Join
2) Left(outer) Join
3) Right(outer) Join
4) Cross Join / Full Outer Join

1) Inner Join:

Syntax:

Select * from table1


Inner Join table2
ON table1.common_column_name= table2.common_column_name;

Select table1.CID,Cname,OID,Oamount from table1


Inner Join table2
ON table1.common_coumn_name= table2.common_column_name;

:::::>>>>> Refer the excel sheet for JOIN an its type

***********************************************************************************
******************************
* ALTER
* HAVING Clause

# ALTER
--> To Add, Delete or modify the column in existing table
a) ALTER TABLE- ADD Column
- Add new column in existing table
Syntax:
ALTER TABLE table_name
Add column_name data_type;

b) ALTER TABLE- DROP Column


- Drop the column from existing table
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

E.x
Alter table phase2
drop column Age;

c)ALTER TABLE- ALTER/MODIFY


- To change the data type of column in table
syntax:
ALTER TABLE table_name
modify column column_name datatype;

E.x:
Alter table phase2
modify column Age varchar(255);

***********************************************************************************
***********************************

Having Clause:

Where: Place the condition on selected column


Having: Place the condition on groups which created by GROUP BY clause

Syntax:

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

SELECT colimn1,column2
FROm table_name
WHERE [condition]
GROUP BY column1, column2
HAVING [condition]
ORDER BY column1

--> The HAVING clause always need to use with Aggregate


function( min,max,sum,avg,count)

You might also like