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

--CLASS-1

--What is SQL?
--Structured Query language.

--Q.what is data?
--Collection of meaningful information.

--Q.What is Data base management system(DBMS) ?


--It is collection of data in a file format.

--Ex: Word file (.doc),Text file (.txt),Notepad ,.csv etc

--Disadvantage
--It stores lessa amount of data.
--no relationship between two files or two sheets.

--Q.What is Relational Data base management system(RDBMS)?


--It is collection of table related information.
--It stores huge amount of data and to extract the data we have language i.e. SQL
--While storing the data in term of tables we can create the relationship
among/between them.

--Q.What is table?
--It is collection of rows and columns.

--there are two types of databases


--1.System defined database --by default it database will point to 'master'
--2.User defined database

--1.Syatem defined database


--There are four types of system defined databses
--1.master -default dDB for SQl
--2.Model
--3.msdb
--4.tempdb

--2.User defined database


--the databse which is created by user for its operation or to store the data.

--blue color words - Syatem defined keywords.


--pink color words - Syatem defined functions.

--Q.how to create the database?


create database SQL181920

--to execute sql query


--we need to go top bar and click on excute button
--we can execute the sql query by pressing 'F5' key from keyboard.

--Q.How to select/Navigate user created database?


use SQL181920

--SQL is not case sensitive


--It means that the meaning of 'HARSHA' is same as 'harsha'

--Diffrent vendors are available in market


--1.SQL server -SSMS(SQL server management Studio)-Microsoft -
2005/2008/2012/2016/2017 etc.
--2.SQL developer -Oracle
--3.MySQl
--4.Teradata
--5.Postgrey SQL
--6.Toad
--7.DB2 - IBM etc.

--Class-2
--Data types
--Type of data which holds in object is nothing but data type.

--1.Numeric Data Type


--It will store the dat in terms of numbers.

--1.BIT
--It stores value '0' and '1'

--2.TINYINT
--It will store the value ranging from 0 to 255.

--3.SMALLINT
--It will store the value ranging from -32768 to 32767

--4.Decimal
--It will store an exact fixed point number.

--5.INT
--it stores the value ranging from -2147483638 to 2147483637

--2.Approximate numeric data type


--1.Float
--it will store floating point number, ranging from -1.8Eto308 to 1.8Eto308
--fo ex: 4.56666666666666666666666

--2.Real
--it will store floting point numbers, ranging from -3.4E to 38 to 3.4E to 38

--2.String or charecter data types


--1.char
--If we want to store dat in text format then we use char data type
--It is static data type or it will use static memory allocation
--Size of char is 8000 bytes/charectres
--it will store non_unicode data that means for 1 charecter it will occupy 1byte

--synatx : char(size)
--for ex: name char(20) -- AMIT - size is 4 but in memory it occupy 20 char space
-- 16 char waisted.

--2.nChar
--If we want to store dat in text format then we use char data type
--It is static data type or it will use static memory allocation
--Size of char is 4000 bytes/charectres
--it will store unicode data that means for 1 charecter it will occupy 2 bytes.
--It will accpet A-Z,a-z and alphanumeric value

--char
declare @value char(10) = 'XYZ123.89'
print @value;
print datalength(@value) ;
print len(@value);

--nchar
declare @value1 nchar(20) = 'XYZ123';
print @value1;
print datalength(@value1) ;
print len(@value1);

--3.varchar
--If we want to store dat in text format then we use char data type
--It is dynamic data type or it will use dynamic memory allocation
--Size of varchar is 8000 bytes/charectres
--it will store non_unicode data that means for 1 charecter it will occupy 1byte
--It will accpet A-Z,a-z and alphanumeric value

--synatx : varchar(size)
--for ex: name char(20) -- AMIT - size is 4 but in memory it occupy 4 char space
-- 16 char released for other usage.

--2.nvarChar
--If we want to store dat in text format then we use char data type
--It is dynamic data type or it will use dynamic memory allocation
--Size of nvarchar is 4000 bytes/charectres.
--it will store unicode data that means for 1 charecter it will occupy 2 bytes.
--It will accpet A-Z,a-z and alphanumeric value

--varchar
declare @value2 varchar(10) = 'XYZ123'
print @value2;
print datalength(@value2) ;
print len(@value2);

--nvarchar
declare @value3 nvarchar(20) = 'XYZ123';
print @value3;
print datalength(@value3) ;
print len(@value3);

--4.Date and time


--1.Date
--you can define or insert date in multiple formats like
YYYY/DD/MM,YYYY/MM/DD,DD/MM/YYYY etc.
--by default sql format is YYYY-MM-DD

--2.Time
--it will allow you to insert the time and format is HH:MM:SS:MS

--3.Datetime
--it will used to insert date and time
--Ex: 2021-08-25 20:35:34.437

--4.Timestamp
--it will combine date and time into format of numbers
--Ex: 2021-08-25 20:35:34.437
--CLASS-3
--SQL statements
--Types of SQL statements
--1.DDL (Data Defination Language) --(DR.CAT) --Tab
--Create,Drop,Truncate,Alter

--2.DML(Data Manipulation Language)


--Select,Insert,Update delete

--3.DCL(Data Control language)


--GRANT,REVOKE

--4.TCL(Transaction Control Language)


--COMMIT,SAVEPOINT,ROLLBACK

--1.DDL
--These statements are basically used to perform structure related operation w.r.to
Table.
--while using the DDL stements Table key word is mandotory.

--Create
--it is used to create the table or database any many more things.

--Q.How to create Database?


create database NEWDB

--Q.How to create table?


--Syntax
create table FirstTable1(
FID int,
Fname char(10),
Age int)

select * from FirstTable

--Insert
--insert statement will allow you to insert the data into the tables.

--METHOD-I
--this method will allow you to insert the data in table defined column sequence.
--Syntax

insert into FirstTable values(1,'Sameer',23)

insert into FirstTable values(23,'Sheeta',2)

insert into FirstTable values(0,'meena',29)

select * from FirstTable1

insert into FirstTable1 values(1,'meena',29)


insert into FirstTable1 values(5,'mithali','')
insert into FirstTable1 values(6,' ',43)

--METHOD-II
--This method will allow you to insert the data randomly or column sequence
mentioned inside the insert statements.

Insert into FirstTable1 (Age,FID,Fname) values (34,3,'Shon')


Insert into FirstTable1 (FID,Fname) values (4,'kate')

select * from FirstTable1

--1.DDL (Data Defination Language) --(DR.CAT) --Tab


--Create,Drop,Truncate,Alter

--DROP
--It will allow you to delete the table Structure along with table data.
--It is also used to delete/drop the database.
select * from FirstTable

--We can drop table


drop table FirstTable

--we can drop the database


Drop database SQL181920

-- if we are trying to delete/drop the cureent database which is in current use


then it will through an exception
--Exception- Cannot drop database "SQL181920" because it is currently in use.

--Truncate
--It will allow you to delete the records from a table at once.
--It wont delete the table structure.
--It wont allow you delete the data from table row by row/record by record by
specifying the condition.
--Syntax

select * from FirstTable1

truncate table firsttable1

--Alter
--By using Alter statements we can manipulate/play with table
columns/attributes/fields.
--By using truncate we can perform multiple opeartions
--We can add one or more columns at a time.
--We can delete/drop the one or multiple columns.
--We can change the data type of particular column
--we can drop the constraint of the table.
--We can increase or decrease the size of particular columns.

--Adding a column into table.


alter table firsttable1 add Floc varchar(10) --To add one column

alter table firsttable1 add FSAL int, CITY varchar(10) --To add two columns

select * from FirstTable1

--Deleting or droping the columns from table


select * from firsttable1

alter table firsttable1 drop column city --Delete single column

alter table firsttable1 drop column floc,fsal --deleting multiple columns

--If we want to know the structure of the table


sp_help department

insert into firsttable1 values(1,'Mohit',23,'Katraj',27000,'PUNE')

--Droping the constarint of column


alter table department drop constraint PK__departme__C0365630E6053696

sp_help student

alter table student drop constraint PK__student__A3DFF16DFE08B446

alter table student drop constraint FK__student__DID__32E0915F


--if the constraint is referenced with other table then it is not possible to drop,
it will through an below exception
--EXCEPTION:
--The constraint 'PK__departme__C0365630E6053696' is being referenced by table
'student', foreign key constraint 'FK__student__DID__32E0915F'.
--Msg 3727, Level 16, State 0, Line 288
--Could not drop constraint. See previous errors.

--CLASS-4
--2.DML(Data Manipulation Language)
--Select,Insert,Update delete

--Select
--Select command is basically used to fetch the data from statement or table.
--select command can used with sql operator,claues and functions.

select 8 -- statement

select 8+2 -- along with operator

select len('scodeen') --along with SQL server functions

select * from INFORMATION_SCHEMA.TABLES

select * from student -- alow us to fetch the data

select 8 from student -- this select statement will display whatever you have
mentioned into the select and it will display w.r.to number of records

--Q.How will take back up of table?


--By using select along with INTO keyword we take backup of table or we can copy
old table into new table.
--Syntax -select * into NEW_TABLE from OLD_Tabel where Condition -Taking the
backup into the same database

--Syntax -select * into NEW_TABLE IN 'Database_name'from OLD_Tabel where Condition


-Taking the backup into the another database
select * from student
--Same database
select * into STUDENT_BACKUP from student
select * from student where DID is not NULL
select * into STUDENT_BACKUP1 from student where DID is not NULL

select * from student where DID is not NULL


select * from STUDENT_BACKUP1

--Another or diffrent database


select * into STUDENT_BACKUP3 in Practice from student --

--Insert
--Insert will allow you insert the data into table along with 'INTO' keywords.
--By using insert we can insert the data sequence wise or randomly.

--METHOD-I
--this method will allow you to insert the data in table defined column sequence.
--Syntax

insert into FirstTable values(1,'Sameer',23)

insert into FirstTable values(23,'Sheeta',2)

insert into FirstTable values(0,'meena',29)

select * from FirstTable1

insert into FirstTable1 values(1,'meena',29)


insert into FirstTable1 values(5,'mithali','')
insert into FirstTable1 values(6,' ',43)

--Insert Into select


--The above statement copies data from one table and insert it into another table.
--the condition is that data type of source and target table should match
select * from student

select * from STUDENT_BACKUP

insert into STUDENT_BACKUP select * from student

insert into STU select * from student


select * into STU from student

create table A (aid int , ANAME varchar(10))


insert into A values (1,'Praveen')
insert into A values (2,'amit')
insert into A values (3,'Rohan')
insert into A values (3,'Mohan')

create table B (aid int primary key , ANAME varchar(10))

insert into B select * from A

--Update
--Update statement is used to update or modify existing records from column.
--While updating column if you have not specified the condition then it will modify
the complete column.
--Syntax: UPDATE TABLE_NAME SET COL1 = Value,COL2=Value,.. WHERE condition
select * from student

update student SET DID = 10 where S_ID =14

update student SET DID = 7,S_NAME = 'SUMIT' where S_ID =11

--Delete
--Delete is used to delete the rows from table.
--Delete statement delete the records from table ROW-by-ROW.
--Syntax: DELETE FROM TABLE_NAME WHERE condition
select * from STUDENT_BACKUP
delete from STUDENT_BACKUP1 --complate data from table

delete from STUDENT_BACKUP where did =3 --selective records from table

--METHOD-II
--This method will allow you to insert the data randomly or column sequence
mentioned inside the insert statements.

Insert into FirstTable1 (Age,FID,Fname) values (34,3,'Shon')

Insert into FirstTable1 (FID,Fname) values (4,'kate')

select * from FirstTable1

--CLASS-5

--SQL Constraints
--To Maintain the accuracy and integrity of the data.
--1.Primary Key
--2.Foreign Key
--3.NULL Key
--4.Unique Key
--5.Check Key
--6.Default key

--1.Primary key
--NOT NULL + Unique value
--Uniquely identifies each record into the table.
--In genral primary key is used with numeric value.
use SQL181920
create table primary_Table(
PK int primary key,
PNAME varchar(10),
PCITY varchar(10))

select * from primary_Table

Insert into primary_Table values(1,'kate','perth')


Insert into primary_Table values(NULL,'kate','perth')

--Q. Define table column by BIT data type with primary key and verify the isert
method?

--To find out the structure of Table?


SP_HELP primary_Table

--Auto increment
--It will automatically insert or increment the values once that has been defined
on column.
--It will allow you to specify the range of values by which we need to increment.
--Automatically generate the unique sequence.

create table auto_increment(


AID int primary key identity(1111288710,1),
ANAME varchar(10),
Aloc varchar(10))
drop table auto_increment

insert into auto_increment values ('AMIT','PUNE')


insert into auto_increment values ('Sumit','Nasik')
insert into auto_increment values ('Rohit','Mumbai')

select * from auto_increment

---1,5,10,15,20

--2.Foreign Key
--A foreign key is column or collection of columns in one table that refers to the
primary key in another table.
--NULL value can be allowed in foreign key column.

create table department(


DID int primary key,
DEPARTMENT_NAME varchar(20))

insert into department values(1,'MECH')


insert into department values(2,'CIVIL')
insert into department values(3,'IT')
insert into department values(4,'ECE')

create table student(


S_ID int primary key,
S_NAME varchar(10),
DID int foreign key references department(DID) )

insert into student values (11,'Mohit',4)


insert into student values (12,'Rohit',3)
insert into student values (13,'Sumit',NULL)
insert into student values (14,'amit',NULL)
insert into student values (15,'Sheena',3)
insert into student values (16,'Meena',10)

--CLASS-6
--NULL values
--A column is with NULL value is a column with no Value.
--NULLvalue is diffewent from a zero value or spce or balnk.

--Q.How to test NULL values from a table?


--There are two functions by using those we can test the NULL values.
--1.IS NULL --It will display the columns having NULL value.
--2.IS NOT NULL --It will display the columns without NULL value.

select * from student where did is NULL

select * from student where did is not NULL

select * from student where did = NULL

--3.NOT NULL key/Constraint


--NOT NULL constarint restricts a column from having "NULL" value.
--Once NOT NULL constraint is defined to column you can't pass the NULL values.
--It will allow duplicate values.

create table NOTNULL (NID int,


FirstName varchar(20) NOT NULL,
AGE varchar(20) NOT NULL)

insert into NOTNULL values (1,'Amit',26)


--The below statement through an excpetion
insert into NOTNULL values (1,'Amit',NUll)
--exception : Cannot insert the value NULL into column 'AGE', table
'SQL181920.dbo.NOTNULL'; column does not allow nulls. INSERT fails.

select * from student where DID is NULL


select * from student where DID is not NULL
--4.Check key
--It ensures that all values in a column satisfies a specific condition.
--Check constraint is used to restrict the value of column.
--It is just like condition which checks before inserting the value into a column.

create table CHECK_KEY (CID int,


FirstName varchar(20) NOT NULL,
AGE int check (AGE >=18) NOT NULL)

insert into CHECK_KEY values(1,'Sumit',18)

insert into CHECK_KEY values(2,'Kiran',17)


--Exception: The INSERT statement conflicted with the CHECK constraint
"CK__CHECK_KEY__AGE__37A5467C".
-- The conflict occurred in database "SQL181920", table
"dbo.CHECK_KEY", column 'AGE'.

select * from CHECK_KEY

--5.Default Constarint/Key
--Sets a default value for a column when value is not specified or inserted after
creating a table.
--To insert the default value we have two ways.

create table default1(DID int primary key identity,


DNAME varchar(20),
CITY varchar(20) default 'PUNE')

--Method -I
insert into default1 values('Ashish','Nasik')
insert into default1 values('Ashish',default)

select * from default1

--Method-II
insert into default1 (DNAME,CITY) values('rohan','sangli')

select * from default1

--6.UNIQUE Key
--It ensure that all the values in column should be unique or diffrent value.
--It will accept one NULL into column.
create table Unique1(U_ID int primary key identity,
UNAME varchar(20) unique,
CITY varchar(20) default 'PUNE')

select * from Unique1


insert into Unique1 values('Rohit','Nasik')
insert into Unique1 values(NULL,default)

--Q.What is the diffrence between Primary key and unique?


--Q.What is the diffrence between Primary key and FK?
--Q.How many NULL values we can insert into unique key column?
--Q.Create a employee table by using all the constarint.?

--CLASS-7

--Clauses
--Clauses are used for filter the data by using specific condition.
--Purpose of clauses is filtering the data.

--Below are some of the important clause we have in sql


--1.WHERE
--2.ORDER BY
--3.GROUP BY
--4 Having

--1.WHERE
--Where is basically used with Arithmatic,Logical,comparision operators.
--WHERE caluse we cant use with Aggregate function
create table student1(S_ID int,
FirstName varchar(20),
Sub1_Marks int,
sub2_marks int,
dept varchar(20),
city varchar(20))

insert into student1 values (1,'Prateek',54,56,'CIVIL','PUNE')


insert into student1 values (2,'Sheetal',48,56,'EC','Sangli')
insert into student1 values (3,'Rohit',44,45,'IT','Satara')
insert into student1 values (4,'Mohit',58,57,'EC','Nagpur')
insert into student1 values (5,'Amit',38,66,'CIVIL','Nagpur')
insert into student1 values (6,'Rahul',NULL,66,'CIVIL','Pune')
insert into student1 values (7,'Rahul',51,NULL,'CIVIL','Pune')
insert into student1 values (8,'Mohan',41,NULL,'','')

select * from student1 where dept ='CIVIL'

select * from student1 where dept ='CIVIL'

select * from student1 where S_ID > 1 and dept ='CIVIL'

select * from student1 where S_ID > 1 or dept ='CIVIL'

select * from student1 where sum(Sub1_Marks) > 40 --Exception


--An aggregate may not appear in the WHERE clause unless it is in a subquery
contained in a HAVING clause or a select list,
--and the column being aggregated is an outer reference.

--2.ORDER BY
--ORDER BY clause is used to sort the data either in Ascending or decending order
--always if we use ORDER BY clause then by default it is in Ascending order
--if we want to specify Ascending (ASC) and Descending (DESC)
--If the column contains NULL value in it then in ASC it will display first and in
DESC it will at last.

select * from student1 order by sub2_marks desc

select * from student1 order by FirstName desc

select * from student1 order by dept,city asc

select * from student1 order by sub2_marks,FirstName asc

--3.GROUP BY
--It is basically used to group rows that have the same values.
--It is often used with aggregate functions like min,max,count,sum and avg.

select dept from student1 group by dept


--Q.How many students are their in respective department?
select dept , count(*) from student1 group by dept

--Q.select those depratment whose having student equal to or greater than 2?


select dept , count(*) from student1 group by dept having count(*) > = 2

select dept,S_ID,sub2_marks from student1 group by dept


--exception:Column 'student1.S_ID' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
--So when ever your using group by clause on columns all those columns should be in
select list.

--4.Having Clause
--Having clause is basically used with agregate functions and after group by
clause.

select dept , count(*) from student1 group by dept having count(*) > = 2

--Diffrence between WHERE and HAVING Clause


-- WHERE
HAVING
--1.where clause can be used with 1.Having
clause can be used with the SELECT stsements
-- INSERT,SELECT,UPADTE
--2.WHERE clause is used before aggregation(GROUP BY) 2.Having Clause is used
after aggregation (GROUP BY)
--3.Aggregation function can not used in the WHERE clause 3.Aggregation functions
can be used having clause.

--CLASS-8
--Operators
--Types of operators in SQL
--1.Arithmatic
--2.Logical
--3.Comparision

--1.Arithmatic Operator
--It is used to perform mathematical operation.
-- we have +,-,*,/ and %.

create table operators(ID int, firstName varchar(15), LastName varchar(15),Salary


int)

insert into operators values(1,'sita','Sharma',3000)


insert into operators values(2,'Geeta','Verma',4000)
insert into operators values(4,'Mita','Patil',5000)
insert into operators values(5,'Amit','Jadhav',6000)
insert into operators values(6,'Sumit','khar',7000)
insert into operators values(3,'neha','Naik',8000,'IT')
insert into operators values(7,'james','Nair',9000,'IT')
insert into operators values(8,'Vamsi','Reddy',8500,'IAT')
select * from operators

select *,Newsalary = salary +1000 from operators

select *,Newsalary = salary -1000 from operators

select *,Package = salary *12from operators

select *,perday = salary /30 from operators

select firstname +' ' + LastName from operators

--Q. How To display even records from table ?


select * from operators where ID % 2 =0

--Q. How To display odd records from table ?


select * from operators where ID % 2 = 1

alter table operators add Dept varchar(10)

update operators SET dept = 'Finance' where id =4

select *,HrDept = salary +(salary/10) from operators where dept = 'HR'

--2.logical operators
--1.AND
--It is just like multiplication operation.
--Input output
--A B O/P
--True False False
--1 0 0
--False True False
--0 1 0
--False False False
--0 0 0
--True True True
--1 1 1
select * from operators
select * from operators where dept = 'HR' and ID = 3

--2.OR
--It is just like Addition operation.
--Input output
--A B O/P
--True False True
--1 0 1
--False True True
--0 1 1
--False False False
--0 0 0
--True True True
--1 1 1

select * from operators where dept = 'HR' or ID = 3

--3.NOT(Negation / opposite)
--Input Output
--1 0
--True False

--3.Comaprison operator
--these operators are used to comapre the condition provided along with SQL
statements.
-- >,>=,<,<= and != or <>(not equal to)

select * from operators where id >2 -- greater Than

select * from operators where id >=2 --greater Than equal to

select * from operators where id <2 --Less than

select * from operators where id <=2 --Less than equal to

select * from operators where id !=2 --Not equal to

select * from operators where id <>2 --Not equal to

select * from operators where id = 2,5 --error

--IN and NOT IN Clause/opeartor


--this operator will allow us to navigate whatever the values we specified inside
the IN operator.
--NOT IN operator performs exactly Vice-Versa opeartion .
--IN
select * from operators where id in (2,5)

select * from operators where lastName in ('Verma','Sharma')

--NOT IN

select * from operators where id not in (2,5)

select * from operators where lastName not in ('Verma','Sharma')

--BETWEEN and NOT BETWEEN


--This operator will allow yoy to display the values or records between a specific
range.
--NOT BETWEEN will perform Vice-versa operation as of BETWEEN.
--While using BETWEEN operator "AND" operator is mandotory.

select * from operators where id between 2 and 5


select * from operators where id not between 2 and 5

select * from operators


select * from operators where lastName between 'A' and 'o'

select * from operators where lastName Not between 'A' and 'o'

--Create a employee table which having EID,ENAME,ESAL,DEPT,HRA(10% Of


ESAL),PF(12%of ESAL)

--CLASS-9
--LIKE
--LIKE operator is used to search for a specified pattern in a column.
--Mostly like operator is used in where clause.
--Like operator used wildcards fro searching a pattern
--1. % - Represents zero,one or multiple charecters or numbers./ A substitue for
Zero or more characters
--2. _ - Represents one or single charecters./A A substitue for exactly one
character.
--3.[Charlist] - Any single charecter in charlist
--4.[^Charlist] -any charecter not in charlist

--ex: Seeta,meeta,geeta sena, sona siya

--'S%' - start with 'S' charetcer and it will display all the names which starts
with S.
--'%S' - End with 'S' charetcer and it will display all the names which END with S.
--'%S%' -Anywhere inside record/column if 'S' charetcer and it will display all the
names which starts or ends or anywhere inside into a column.

select * from operators where firstName like 's%' -- At the start

select * from operators where firstName like 'S%' -- at the end

select * from operators where firstName like 'G%a' --Start with G and End with A.

select * from operators where firstName like '%s%' -- Anywhere inside the column

select * from operators where firstName like '%s'

select * from operators where firstName like '[abj]%' -- the names which starts
with character A,B & J will display.

select * from operators where firstName like '%[abj]' -- the names which Ends with
character A,B & J will display.

select * from operators where firstName like '%[abj]%' -- the names which
Starts,Ends and Anywhere inside character A,B & J will display.

select * from operators where firstName like '[^Abj]%'

select * from operators where firstName like 'a%' or firstName like 'S%'
select * from operators where firstName like '[as]%'
select * from operators where firstName like '[A-j]%' --It will display the names
in between the range of letters A to J.
select * from operators where Salary like '36%'
select * from operators where Salary like '[36]%'

select * from operators where Salary like '3%5' ---- 3005,3125


--start s aur ensd need s
-- S%S

select * from operators where Salary like '5%' -- At the start

--I want to search such name whose second letter starts with 'A'
select * from operators where firstName like '_A_E%'

select * from operators where Salary like '%0' -- at the end

select * from operators where Salary like '%5%'

--CLASS-10
--JOIN
--join Statement is used to combine two or more tables based on relationship.
--While joining the two tables their should be common column name is required.
--Cross product + condition =JOIN

--Example
--Table one - A,B,C
--Table Two - D,E,F
--We can't apply join between table one and two

--Table one - A,B,C,D


--Table Two - D,E,F
--We can apply join between table one and two i.e D is common column in between

--Types of Joins
--1.Inner join / join
--2.Outer join
-- 1.Left outer join/Left Join
-- 2.Right outer join/ Right join
-- 3.Full outer join /Full join
--3.Self Join
--4.Cross join

--1.Inner join / join


--It will return rows when their is al least one match in both tables.

--Suppose we have two table named as A and B and if we are applying right join
--For example A right join B then all the records from Table B will be displayed
and only matching records from table A against B will be displayed
--and non-matching records will displyed as NULL.

Create table A (Aid int, AName varchar(20))

Create table B (Bid int, BName varchar(20),AID int)

insert into A values (1,'Aman')


insert into A values (2,'Amit')
insert into A values (3,'Mohit')
insert into A values (4,'Rohit')
insert into A values (5,'Ravi')
insert into A values (8,'Kiran')
insert into A values (9,'Mohan')
insert into A values (Null,'sohan')

insert into B values (11,'Sumit',1)


insert into B values (12,'Shital',2)
insert into B values (13,'Arjun',3)
insert into B values (14,'Slok',4)
insert into B values (15,'Harsha',5)
insert into B values (16,'Shital',6)
insert into B values (17,'Meena',7)
insert into B values (18,'Sheena',NULL)

select * from a, b where a.Aid = b.AID --without applying join statement we can
join two or more tables

select * from A join B on a.Aid = b.AID --with join statement

--1.Right join/Right outer join


--It will display all the records from right table and matching records from left
table.

--Suppose we have two table named as A and B and if we are applying right join
--For example A right join B then all the records from Table B will be displayed
and only matching records from table A against B will be displayed
--and non-matching records will displyed as NULL.

select * from A right outer join B ON A.aid =B.Bid

--2.leftt join/left outer join


--It will display all the records from Left table and matching records from right
table.

--Suppose we have two table named as A and B and if we are applying right join
--For example A left join B then all the records from Table A will be displayed and
only matching records from table B against will be displayed
--and non-matching records will displyed as NULL.

select * from A left outer join B ON A.aid =B.Bid

--3.Full join/Full outer join


--It will display all the records from both the tables whether it is matching or
not-matching.
-- If the records are not matching either of the table then it will display NULL
values to either of the table side.

select * from A full join B on a.Aid = b.AID

select * from A Full outer join B ON A.aid =B.Bid

--Avoid the matching records and display only unmatching records from table
select * from A full join B on a.Aid = b.AID where a.Aid is null or b.AID is null
--Example
--A - 1,2,3,4,NULL
--B - 3,4,5,6,NULL

--Inner join -3,4


--Left join - A left join B
-- 1 Null
-- 2 NUll
-- 3 3
-- 4 4

--Right join - A right join B


-- 3 3
-- 4 4
-- NULL 5
-- Null 6

--Full join - A right join B


-- 1 NULL
-- 2 NULL
-- 3 3
-- 4 4
-- NULL 5
-- Null 6

--A full join B -- 1,2,3,Null,Null


-- 1,2,NULL,4,5

--CLASS-11
--3.Self Join
--The table which is joing itself is nothing but self join.
create table SELF_JOIN (E_ID int,E_NAME varchar(20), M_ID varchar(20))

insert into SELF_JOIN values (1,'Shon',3)


insert into SELF_JOIN values (2,'Tino',4)
insert into SELF_JOIN values (3,'Mark',5)
insert into SELF_JOIN values (4,'Kate',Null)
insert into SELF_JOIN values (5,'Ravi',3)
--join = cartesian product + condition

select * from SELF_JOIN E2 --, where M1.E_ID = E1.E_ID


select E1.E_ID,E1.E_NAME,E1.M_ID,M1.E_NAME from SELF_JOIN E1,SELF_JOIN M1 where
M1.E_ID = E1.M_ID

--Note : Whenever you are not using join keyword while joing the two tables then it
is called as equi-join.

--Self join can be used as


--1.inner join
select * from SELF_JOIN E1 join SELF_JOIN M1 on M1.E_ID = E1.M_ID
--2.left join

select * from SELF_JOIN E1 left join SELF_JOIN M1 on M1.E_ID = E1.M_ID

--3.right join
select * from SELF_JOIN E1 right join SELF_JOIN M1 on M1.E_ID = E1.M_ID

--4.Cross join
--it is cartesian product.
-- If you have 5 records in table A and 5 records in table B then output will
contain 25 records.
select count(*) from A
select count(*) from B
select * from A , B

--Class-12
--SET Operator
--It is mainly used to determine the same type of data from two or more tables
--All queries combined using a UNION, INTERSECT or EXCEPT operator must have an
equal number of expressions in their target lists.
--There are various types of SET opeartor present in sql
--1.Union
--2.Union all
--3.Intersection
--4.Except/ minus

--1.Union
--This set oeprator is used to fetch matching records from table.

--A =[1,2,3,4,5]
--B =[4,5,6,7,8]

--A union B - o/p =[1,2,3,4,5,6,7,8]


--A union all B - o/p =[1,2,3,4,5,4,5,6,7,8]
--A intersection B -o/p =[4,5]
--A except B -o/p =[1,2,3]
--B except A -o/p =[6,7,8]
create table set1(s_id int, SName varchar(20))

create table set2(s_id int, SName Varchar(20))

drop table set2


insert into set1 values(1,'A')
insert into set1 values(2,'B')
insert into set1 values(3,'C')
insert into set1 values(4,'D')
insert into set1 values(5,'E')

insert into set2 values(4,'D')


insert into set2 values(5,'E')
insert into set2 values(6,'F')
insert into set2 values(7,'G')
insert into set2 values(8,'H')

select * from set1


Except --minus
select * from set2

select * from set2


Except
select * from set2

--Null fucntion
--There are diffrent functions or ways we can test or identify 'NULL' values from
table
--1.ISNULL
--2.COALESEC
--3.Case statement

--1.isnull
--This fuction will help you to replace the NULL values with user defined value.
--It will accept two arugument.

create table NullValue (NID int,NName varchar(20),ManagerID varchar(20))

insert into NullValue values(1,'Mohan','3')


insert into NullValue values(2,'sohan','2')
insert into NullValue values(3,'rohan',NULl)
insert into NullValue values(4,'aman',Null)
insert into NullValue values(5,'barman','4')
truncate table nullvalue
select NID,NName,isnull(ManagerID,'No Manager ID') as
MangerAllocation,isnull(NName,'No name') from NullValue

select * from NullValue where ManagerID is null

--2.COALESCE
--It will try to find or locate first appearance of NON-NULL value in a specific
records from that defined columns inside in it.
--If it is not possible to locate non-null value then it will display NULL value

create table coalesce_test(CID int, Firstname varchar(10),MiddleName


varchar(10),LastName varchar(10))

insert into coalesce_test values (1,'A','B','C')


insert into coalesce_test values (2,Null,'D','E')
insert into coalesce_test values (3,'H',NULL,'E')
insert into coalesce_test values (4,'X','D',NULL)
insert into coalesce_test values (5,Null,NULL,NULL)
insert into coalesce_test values (5,Null,NULL,'T')
insert into coalesce_test values (Null,Null,NULL,'T')

delete coalesce_test where cid =5


select * from coalesce_test

select coalesce(firstname,cid) from coalesce_test

select coalesce(cid,lastname) from coalesce_test

--CLASS-13
--3.Case Statement
--The case Statement will identify the condition and returns a values.
--When first condition is met (Like an IF-THEN-ELSE).so once condition is TRUE,it
will stop otherwise it will return ELSE result.

--If there is no ELSE statement and no condition is TRUE then it returns NULL
value.

--Syntax: CASE
-- WHEN condition1 THEN result1
-- WHEN condition2 THEN result2
-- ELSE result
-- END
sp_help student
select * from student

update student set DID = 10 where DID= 8

update student set DID =


case when DID =10 and S_ID <13 then 5
when DID =10 and S_ID >=15 then 4
else 6 end

select NID,NNAME,
CASE WHEN managerID is NULL then 'NO Manager' else 'Manager present'
END ,
case when NName is not null then 'Name is present' else 'Name is null'
end
from NullValue
select * from NullValue

--Date and Time Function


select getdate()

--getdate
select getdate() as Todays_date-- Todays date

select getdate() -1 as Yesterday_date --Yesterday date

select getdate() +20 as Tomorrow_date --Tomorrow date

select getdate() +2

--There are three diffrent functions in SQL to modify or perform any date related
task
--1.DATEDIFF()
--2.DATEPART()
--3.DATEADD()

--1.datediff() function
--The datediff function requires 3 argument(s).
--If we provide more than 3 arguments then it will through an exception
--syntax: datdiff(interval,date1,date2)

--(YY,MM,DD,HH,Minutes and seconds)

select DATEDIFF(YYYY,'1987/09/13','2021/09/13')

select DATEDIFF(dd,getdate(),GETDATE()+1)
--syntax : DATEDIFF(interval,date1,date2)
--interval
--Year,YYYY, YY = Year
--Quarter,QQ, Q = Quarter
--Month, MM, M = Month
--DAYOFYEAR - day of the year
--DAY,dy,y = day
--WEEK,WW,WK = weekday
--HOUR,HH = hour
--MINUTE,MI,N = Minute
--SECOND,SS,S = Second
--MILISECOND , MS = Millisecond

select datediff(M,'2015/01/01',getdate())

--Q.HOW to calculate your age ?

select DATEDIFF(YY,'1996/08/15',getdate()) as Present_Age

select DATEDIFF(YEAR,'MONTH',getdate()) as Present_Age

Create table Account_details (


ACCT_NUMBER int primary key identity(11112881,1),
ACCT_NAME varchar(20),
ACCT_OPEN_DATE date,
BRANCH Varchar(20))
select * from Account_details

alter table Account_details add currentdate date

update Account_details set currentdate = GETDATE()

insert into Account_details values ('Shubham','2015/12/09','MUMBAI')


insert into Account_details values ('Rihan','2016/01/12','Jaipur')
insert into Account_details values ('Sheetal','2017/08/11','GOA')
insert into Account_details values ('Priyanka','2017/01/01','Chennai')
insert into Account_details values ('Manik','2015/01/08','Agra')
insert into Account_details values ('Veena','2021/01/01','Patna')
insert into Account_details values ('Rohan','2019/07/01','Pune')
insert into Account_details values ('Laxmi',GETDATE(),'rohatak')
insert into Account_details values ('Jinal',GETDATE(),'Indore')
insert into Account_details values ('Jinal',GETDATE()-365,'Indore')

insert into Account_details values ('Pranav',GETDATE()-


365,'Udaypur',Getdate(),DATEDIFF(YY,GETDATE()-365,Getdate()))
select * from Account_details

--Accounts which has been opened in a current year


select ACCT_NUMBER,ACCT_NAME,ACCT_OPEN_DATE ,
DATEDIFF(YY,ACCT_OPEN_DATE,currentdate) as Ageofaccount from Account_details
where DATEDIFF(yy,ACCT_OPEN_DATE,GETDATE()) =0

alter table Account_details alter column currentdate datetime

update Account_details set currentdate = getdate()


--Q.What is the age of your bank account

select ACCT_NUMBER, ACCT_NAME, DATEDIFF(YY,ACCT_OPEN_DATE,getdate()) as ACCOUNT_AGE


from Account_details

--Q.Calculate the no of accounts which is opened during the current year.

select ACCT_NUMBER, ACCT_NAME, DATEDIFF(YY,ACCT_OPEN_DATE,getdate()) as


ACCOUNT_AGE,count(*) from Account_details
where DATEDIFF(YY,ACCT_OPEN_DATE,getdate()) =0
--2.DATEPART
--This will allow you to display the date part
--Syntax : DATEPART(interval,date/columnname)
select *,Datepart(HH,currentdate) from Account_details

select getdate()

select DATEPART(DD,GETDATE())
select * from Account_details

--if we want to validate date related column which is in terms of timestamp


--and it is very difficult to mention each and every time stamp related column with
every date
--in order to avoid that we can use date part so it will consider with mentioned
interval.

select count(*) from Account_details where DATEPART(YY,ACCT_OPEN_DATE) in


('2021','2015')

select datepart(yy,getdate()) as years, datepart(MM,getdate()) as months --- yers


and months

--3.DATEADD()
--it will allow you to add the dates.
--it will accept three arguments.
--syntax : DATEADD(interval,value,date/datecolumn)
select getdate() +365
select DATEADD(HH,30,GETDATE()) as after30days

--Exists
--Exists operator is used to test for the existence of record in a subquery.
--Exists returs TRUE if subquery returns one or more records.
create table supply (S_ID int, SName varchar(20))

insert into supply values (1,'Soap')


insert into supply values (2,'Cloths')
insert into supply values (3,'Paint')
insert into supply values (4,'Bricks')

select * from supply


create table product(Pid int, ProductName varchar(20),price int,s_id int)

insert into product values(11,'Santoor',20,1)


insert into product values(12,'Asian',32,3)
insert into product values(13,'dettol',35,1)
insert into product values(14,'BGV',10,4)
insert into product values(15,'Raymond',22,2)
insert into product values(16,'Dinesh',24,2)

select * from supply


select * from product

select * from supply s1


where exists (select * from product p1 where s1.s_ID = p1.S_ID and price = 10)

select * from supply where s_id = (select count(*) from product where price > 20 )
select * from supply s1 ,product p1 where s1.S_ID=p1.s_id

--Q. How will you display the supplier name and product name if price is greater
than 20.?
select s1.SName,p1.ProductName,p1.price from supply s1,product p1
where exists (select productname from product where p1.s_id = s1.S_ID) and price
> 20

--CLASS-14
--Sub-query(Nested) and co-related nested query
--Sub_query
--Sub query is nothing but inner query or non-corealted sub query.
--Outer query and inner query is independent and can excute separately.

Create table prod (id int, Name varchar(20),description varchar(20))

Insert into prod values (1,'bike','200 cc bike')


Insert into prod values (2,'car','hatchback,Sedan,MPV')
Insert into prod values (3,'cycle','sports/normal')

create table sales(S_id int,id int, price int,quantity int)

insert into sales values(1,3,200,5)


insert into sales values(2,2,400,7)
insert into sales values(3,3,600,3)
insert into sales values(4,3,800,9)

select * from prod


select * from sales

--Need to display product which is not sold


select id,name,description from prod
where id not in (select distinct(id) from sales ) --3,2

--we can replace sub query by joins easily


select p1.id,name,description from prod p1 left join sales s1
on p1.id = s1.id
where s1.id is null

--Co-relation query
--If the subquery or inner query depends upon the outer query for its value then
that query is called as co-realtional query.
--Co-relatinal inner query get excuted once for every row that is selected by the
outer query

select name ,
(select sum(quantity) from sales s1 where s1.id =p1.id) as totalQuantity
from prod p1

-- We have replaced Co-relation query by using joins


select p1.Name,sum(quantity) as TotQnty from prod p1 left join sales s1
on p1.id = s1.id
group by Name

--suquery = OQ - IQ = independent
--Corelational = OQ - IQ = IQ is dependent on OQ
--FI - False - (IQ = 4 execution)
--SI -TRue - car -7
--TI -TRUE - Cycle -17

--Q.What is the diffrence between Sub query and co-relational query?

--Over Clause
--Over clause combined with aprtition by clause and is used to divide data into
partitions.

--syntax:
--function() over (partition by col1,col2 ...etc)
--Along with functions like Count(),AVG(),Max(),Min(),sum(),rank(),dense_rank() and
rownumber etc.

create table over_Test(EMPID int, FirstName varchar(20),Gender varchar(2),salary


int)

insert into over_Test values(1,'Mohini','F',1000)


insert into over_Test values(2,'Rohit','M',2000)
insert into over_Test values(3,'Amit','M',4000)
insert into over_Test values(4,'Sonal','F',5000)
insert into over_Test values(5,'Minal','F',6000)
insert into over_Test values(6,'Amar','M',3600)
insert into over_Test values(7,'Shital','F',4500)
insert into over_Test values(8,'Sohil','M',6000)
insert into over_Test values(9,'praveen','F',9000)
insert into over_Test values(10,'Mithali','F',9000)

select * from over_Test

--Aggreagted male and female details


select gender,Count(*) as Gendercount, AVG(salary) as Avgsal,
min(salary) as minsal ,max(salary) as maxsal
from over_Test
group by Gender

--Aggregated data with name and employee details by using join but the query is
complex
select firstname,salary,o1.Gender,g1.Gendercount,g1.Avgsal,g1.maxsal,g1.minsal from
over_Test O1
inner join
(select gender,Count(*) as Gendercount, AVG(salary) as Avgsal,
min(salary) as minsal ,max(salary) as maxsal
from over_Test
group by Gender) as g1
On g1.Gender = o1.Gender

--Instead of writing the above statement we can replace bu using over clause
select FirstName,salary,Gender
,count(gender) over (partition by gender) as TotalgenderCount
,Avg(salary) over (partition by gender) as Avgsal
,min(salary) over (partition by gender) as Minsal
,max(salary) over (partition by gender) as maxsal
,sum(salary) over (partition by gender order by EMPid) as runningsal
,diffinavg =(Avg(salary) over (partition by gender) - salary)
from over_Test
where Gender = 'M'
--Q. Need to calculate the Running salary from emp_over table over partition by
Gender.
select EMPID, FirstName,salary,Gender
,sum(salary) over (partition by gender ) as Runningsalary
,sum(salary) over (partition by gender order by EMPID ) as Runningsalary
from over_Test

--Q.How To take data base backup?


backup database Testing18 to disk ='D:\Notes\SQL181920.bak'

--CLASS-15
--Rank() and DenseRank()
--It will return a rank starting at 1 based on oredering of rows and imposed by
order by clause.
--Order by clause is required mandotory.
--PARTITION BY Clause is optional.

--Example
--Marks RANK() DENSE_RANK() Partition by marks
--486 1 1
--486 1 1
--484 3 2
--482 4 3
--480 5 4
--480 5 4
--478 7 5

--Example
--[sal] = [1000,1000,2000,3000,4000]
--Rank() -- [1,1,3,4,5]
--dense_rank() --[1,1,2,3,4] -- school level mark inside the class

select * from INFORMATION_SCHEMA.tables

select * ,rank() over ( partition by salary order by salary ) as rank1 from


over_Test

select * ,dense_rank() over ( partition by gender order by salary ) as denserank1


from over_Test
--Q.What is the diffrence between Rank() and Dense_Rank()
--Rank() -- Rank function skips ranking if there is same value or number.
--Dense_Rank() --It will not skips ranking if their is same value or number.

--by using top function shows an ambiguty related to salary


select min(salary) from over_Test where salary in
(select top 2 salary from over_Test order by salary desc)

select min(salary) from over_Test where salary in


(select top 3 salary from over_Test order by salary desc)

select min(salary) from over_Test where salary in


(select top 4 salary from over_Test order by salary desc)

--Rank find 2nd 3rd and 4th highest salary


select *, rank() over (order by salary desc) as rank1 from over_Test where rank()
over (order by salary asc) =2

--the above query through an exception saying Windowed functions can only appear in
the SELECT or ORDER BY clauses.

--CTE(Comman Table Expression)


--It will store tempory result set will make use that in main query.
--It can be referred within SELECT,INSERT,UPDATE and DELETE statements that
immediately follows by CTE.

--Syntax:
--WITH CTE_NAME (col1,col2,col3...)
--as
--(CTE query statements)

----Rank find 2nd 3rd and 4th highest salary


with Maximumsalary as
(select *, rank() over (order by salary desc) as denserank1 from over_Test)
select * from Maximumsalary where denserank1=2;

with Maximumsalary as
(select *, dense_rank() over (order by salary desc) as denserank1 from over_Test)
select * from Maximumsalary where denserank1=3;

with Maximumsalary as
(select *, dense_rank() over (order by salary desc) as denserank1 from over_Test)
select * from Maximumsalary where denserank1=4;

--by using denserank


with Maximumsalary as
(select *, dense_rank() over (order by salary desc) as rank1 from over_Test)
select * from Maximumsalary where rank1=2

create table student (S_ID int,Firstname varchar(20),loc varchar(20), dept


varchar(20),email varchar(20))

select * from student

insert into student values(1,'praveen','pune','ETL','praveen@gmail.com')


insert into student values(2,'Rohit','Mumbai','Testing','rohit123@hotmail.com')
insert into student values(3,'Akash','Jaipur','HR','akash777@rediff.com')
insert into student values(4,'Sada','Warangal','HR','sada@yahoo.com')
insert into student values(5,'Rajesh','Hyderabad','Account','rajesh24@outlook.com')
insert into student values(6,'Umesh','Kolar','CCD','umesh9@infovis.com')
insert into student values(7,'randhir','Bijapur','Admin','randhir@startech.com')
select * from student
--Q.How to find Duplicate from table?
--1. We can identify duplicate records by using PK
--Select <PK1>,<PK2>,... ,count(*) as duplicate from Table_Name group by
<PK1>,<PK2>,... having count(*) > 1

--2.All the column from table need to include in select and group by list

SP_Help student

select s_id,firstname,loc,dept,count(*) as duplicate from Student


group by s_id,firstname,loc,dept
having count(*) > 1

--ROW NUMBER
--It will return the sequential number of row starting at 1
--Order by clause is required.
--PARTITION BY clauese is optional
--When the data is partitioned, row number reset to 1 when the partition changes.

--syantx
--ROW_NUMBER() OVER(ORDER BY Col1,col2)
select * from student
select *,ROW_NUMBER() over (order by s_ID) as Rownumber from student

select *,Row_Number() over (Partition by s_id,firstname,loc,dept order by


s_Id,firstname,loc,dept ) as rownumber from student

--Q.How to delete duplicate records from table?


select * from student

with deleteDuplicate as
(select *,Row_Number() over (Partition by s_id,firstname,loc,dept order by
s_Id,firstname,loc,dept ) as rownumber from student)
delete from deleteDuplicate where rownumber > 1

--By using single column we are deleting the records from table

--CLASS-16
--SQL server functions
--1.UPPER()
--UPPER() Function converts the value of field/Column to upper case.
--The upper case function requires 1 argument
--syntax :upper (text/column name)

select *,UPPER(loc) as uppercase from Student

--2.LOWER()
--Lower() Function converts the value of field/Column to lower case.
--The lower case function requires 1 argument
--syntax :lower (text/column name)

select *,LOWER(dept) as lowercase from Student

--3.Substring
--The substring function used to extract charecter from text field
--Synatx : substring(Column_Name,Start,end[lenth]) from table_Name
--Substring(string,start,end)
--Ex: substring ( 'varchar',int,int)

select SUBSTRING('Scodeen Global',1,4)

select SUBSTRING('Praveen', 1, 2)

select * from student


--abc@gamil.com
select *,SUBSTRING(Firstname,4,len(Firstname)) as PartOFString from student
select SUBSTRING('student',1,3)
select SUBSTRING('222222',1,3) --- Error : Argument data type int is invalid for
argument 1 of substring function.
--4.DATALENGTH() and LEN()
--This function returns the number of bytes used to reprsent the expression.
--Syntax : DATALENGTH(string)

sp_help student
select DATALENGTH('Scodeen ') --Number memory blocks occupied
select len('Scodeen ') -- it will only string length not bother about the
sapces
select *,DATALENGTH(firstname) from student

create table length_check (Lid int, Lname nvarchar(20))

insert into length_check values(1,'Praveen')


insert into length_check values(2,'Amit')
insert into length_check values(3,'Meena')
insert into length_check values(4,'Sohan')
insert into length_check values(5,'Rajni')

select *, datalength(Lname) from length_check


select *,len(Lname) from length_check
select len(S_Name) from student

--5.CONCAT() , CONCAT with + and CONCAT_WS()


--The CONCAT() function adds two or more strings together.
--Syntax: CONCAT(string1,string2....)

--The + operator allows you to add two or more strings together.


--syntax:string1 + string2 + string_n

--The CONCAT_WS() function adds two or more strings together with a separator.
--syntax : CONCAT_WS(separator, string1, string2, ...., string_n)

select CONCAT('Praveen',' ','Patil')

select concat('SQL',' ','is',' ','DB Language')

select * from student

select CONCAT(Firstname,' ',Loc) as NameLocation from student


select s_id +' '+ Loc from student

select CONCAT(s_id,' ' ,Loc) as NameLocation from student -- whenever you are
using concat function no need to think about the data type.

select CONCAT(Firstname,Loc) as NameLocation from student

select 'praveen'+' '+'Patil'

select CONCAT_WS('_','Scodeen Global','PUNE')


select CONCAT_WS('@','Scodeen Global','PUNE')

select * from student

select *,CONCAT_WS('_',s_id,Firstname,loc,dept) as withseparator from student

--6.LTRIM(), RTRIM() and TRIM()


--The LTRIM() function removes leading spaces from a string.
--The RTRIM() function removes trailing spaces from a string.
--TRIM() function removes leading as well as trailing spaces from string.
select len(' Scodeen'); --14
select DATALENGTH(ltrim(' Scodeen'))
select datalength(' '); --7
select len(' '); -- 0
select len('Scodeen ') --7
select len('Scodeen')
select (' Scodeen'); -- 13
select Rtrim('Scodeen '); --'Scodeen'
select ('Scodeen ') --'Scodeen '

select len(' Scodeen ');--'Scodeen'


select len(' Scodeen ')
select len('Scodeen')

--CLASS-17

--7.Reverse()
--The REVERSE() function reverses a string and returns the result.
--synatx : REVERSE(string)

select REVERSE('Pune')

select REVERSE('SQL')

--8.Round
--The ROUND() function rounds a number to a specified number of decimal/length
places.
--Syntax : ROUND(NUMERIC_EXPRESSION, length, [(function)])

--NUMERIC_EXPRESSION : it takes the number to be roundoff.


--Length : the number of digits that we want to round off.
-- if length is +ve then rounding is applied after decimal and if
length is -ve the before decimal
--function : is used to indicate rounding or truncation operation.
---- 0 -indicates rounding and non-zero indicates truncation, by default it
is 0.

select ROUND('value',1) -- Exception


select ROUND(78.56,0)
select ROUND(78.56,-1)
select ROUND(78.56,-1)
select ROUND(78.56,2)
select ROUND(78.467,0)

select round(750.556,2) -- Round to 2 places after the decimal point

select round(750.556,2,1) --Truncate anything after 2 places after the decimal


point.

select round(740.4456666,-2,1)
select round(750.4456666,1)
select round(750.4456666,2,2)
select round(750.4456666,3)
select round(750.4456666,3,1)
select round(750.4454666,3)
--0.5

--9.REPLACE()
--The REPLACE() function replaces all occurrences of a substring within a string,
with a new substring.
--Note: The search is case-insensitive.
--Syntax - REPLACE(string, old_string, new_string)

select REPLACE('Mohan','O','T')

select REPLACE(11111,'1','4')
select * from student
select *,REPLACE(dept ,'HR','Admin') as replacedColumn from student
-- A-a , B-b meaning is same in replace function.
--A,a,B,b
select replace ('scodeen','sc','SC')
select replace ('scodeen','SC','sc')
select Replace ('sCODEEN','sC','Sc')

--10.REPLICATE()
--The REPLICATE() function repeats a string a specified number of times.
--Syntax :REPLICATE(string, integer)

select REPLICATE('SCODEEN ',10) tentimes

--11.CONVERT()
--The CONVERT() function converts a value (of any type) into a specified datatype.
--Syntax :CONVERT(data_type[(length)], expression, [(style)])

create table DOJ (id int, NAME varchar(20),DOJ datetime)

insert into DOJ values (1,'Mansa','2020-01-01 10:10:10')


insert into DOJ values (2,'Vasavi','2015-06-01 10:20:10')
insert into DOJ values (3,'Pravlika','2014-04-01 11:10:10')
insert into DOJ values (4,'Jyoti','2017-08-01 12:10:10')
insert into DOJ values (5,'Pushpa','2016-05-01 01:23:10')
insert into DOJ values (6,'Harish',getdate())

select * from DOJ


select GETDATE()
select convert(varchar,getdate())

select id,NAME,convert(varchar(11),DOJ) as convertedDOJ from DOJ

select *, convert(varchar(11),DOJ) as NewCreatedDOJ from DOJ

select *, convert(varchar(11),DOJ,108) as NewCreatedDOJ from DOJ


select *, convert(varchar,DOJ) as NewCreatedDOJ from DOJ
select GETDATE
--Style
--Converting datetime to character:
--Without With Input/Output Standard
--century century
--0 100 mon dd yyyy hh:miAM/PM Default
--1 101 mm/dd/yyyy US
--2 102 yyyy.mm.dd ANSI
--3 103 dd/mm/yyyy British/French
--4 104 dd.mm.yyyy German
--5 105 dd-mm-yyyy Italian
--6 106 dd mon yyyy -
--7 107 Mon dd, yyyy -
--8 108 hh:mm:ss -
--9 109 mon dd yyyy hh:mi:ss:mmmAM (or PM) Default + millisec
--10 110 mm-dd-yyyy USA
--11 111 yyyy/mm/dd Japan
--12 112 yyyymmdd ISO
--13 113 dd mon yyyy hh:mi:ss:mmm Europe (24 hour
clock)>
--14 114 hh:mi:ss:mmm 24 hour
clock
--20 120 yyyy-mm-dd hh:mi:ss ODBC canonical (24
hour clock)
--21 121 yyyy-mm-dd hh:mi:ss.mmm ODBC canonical (24 hour
clock)
-- 126 yyyy-mm-ddThh:mi:ss.mmm ISO8601
-- 127 yyyy-mm-ddThh:mi:ss.mmmZ ISO8601
(with time zone Z)
-- 130 dd mon yyyy hh:mi:ss:mmmAM Hijiri
-- 131 dd/mm/yy hh:mi:ss:mmmAM Hijiri

--12.CAST()
--The CAST() function converts a value (of any type) into a specified datatype.
--Syntax :CAST(expression AS datatype [(length)])
select convert(varchar,GETDATE(),101)

select cast(getdate() as varchar)


select * from DOJ
select *,CAST(DOJ as varchar) as DOJConverted from DOJ

--13.CHARINDEX()
--The charindex() function searches for a substring in a string and returns
position.
--if the substring is not found, this function returns 0.
--syntax : CHARINDEX(Substring,string,start)

select CHARINDEX('@','acc@gmail.com@',1) as matchingpostion

--Q.How will you findout the place of charecter 'E' in 'SCODEEN'?


select CHARINDEX('E','SCODEEN')
select CHARINDEX('sc','scodeen') as matching

select *,CHARINDEX('@',email) from student

--Q.How find domain or server from email column ?VVVIMP****


select S_ID,SUBSTRING([email],CHARINDEX('@',[email])+1,len([email])) as domain from
student

select *,SUBSTRING((email), CHARINDEX('@',[email])+1,len([email])) from student

select *,SUBSTRING((email), 1,CHARINDEX('@',[email])-1) as beforedomain from


student

select substring ('Praveen123@gmail.com',12,20)

select CHARINDEX('@',[email])+1,len(email) from student

select CHARINDEX('@',[email]) from student --11+1 =12


select len(email) from student -- 20

--Q.How to find the number of occurance of 'e' charetcer in string?

SELECT (DATALENGTH('lleelleellee')-len(REPLACE('lleelleellee','e',''))) ---6


--or
select len(REPLACE('lleelleellee','e',''))

--CLASS-18
--View
--View is nothing but more than SQL query.
--A view can also be considered as virtual table
--Syntax : Create View vVIewName AS
-- SQL query

create table dept(DID int , DeptName varchar(20))

insert into dept values (1,'IT')


insert into dept values (2,'Admin')
insert into dept values (3,'Account')
insert into dept values (4,'HR')

create table employee(EID int,ENAME varchar(20),salary int,gender varchar(2), did


int)

insert into employee values (1,'Shon',2000,'M',2)


insert into employee values(2,'john',8000,'M',3)
insert into employee values(3,'Charli',4000,'M',2)
insert into employee values(4,'mita',1000,'F',4)
insert into employee values(5,'ben',3000,'M',1)

--Syntax
--how to create a view
create view vEmployeeDetails as
select * from employee

--How to fetch the view or how to see the view results


select * from vEmployeeDetails
insert into vEmployeeDetails values (6,'mike',54000,'M',3)

update vEmployeeDetails SET salary =4800 where EID =6


select * from employee
select * from vEmployeeDetails

--Below view will through an exception i.e Incorrect syntax near the keyword
'select'.
create view vEmpDeptDetails as
select * from employee;
select * from dept;

--View will allow you to enter one select statement


create view vEmpDeptDetails as
select e1.EID,e1.ENAME,e1.gender,d1.DeptName from employee e1 , dept d1 where
e1.did =d1.DID

select * from vEmpDeptDetails


--Alter the view
alter view vEmpDeptDetails as
select e1.EID,e1.ENAME,d1.DeptName from employee e1 , dept d1 where e1.did =d1.DID

--Drop the view


drop view vEmpDeptDetails

sp_helptext [vBeforeDomain]

--Store Procedure
--sp_help --to view the structure
--sp_rename --to rename the column of a table
--SP_HELPTEXT --It will allow you to view the script of view or Sp.

--It is block of script/code to perform an ceratin action whenever it is needed.


--it works like function.
--If you have a situvation, where you write the same query again and again,
--instead of writing again and again will save that query as stored procedure and
call it by its name

--How to create the Store procedure


--there are two ways of creating SP
--1.Without Parameter
--2.With parameter

--Synatx: CREATE PROCEDURE /PROC spStoreProcName


-- AS
-- BEGIN
-- SQL statements :
-- END
create proc spEmpdetails as
Begin
select * from employee;
select * from dept;
end
--How to exceute SP
--1
spEmpdetails
--2
exec spEmpdetails
--3
execute spEmpdetails

sp_helptext spEmpdetails
--sp_helptext
--if you want to identify the spcript of the stored procedure then we can use the
system store procedure i.e. SP_HELPTEXT
--it will show the complete script whenever we use along with user created stored
procedure.
sp_helptext

--1.Without Parameter
create procedure spEmpDeptDetails
as
begin
select e1.EID,e1.ENAME,e1.gender,d1.DeptName from employee e1 , dept d1 where
e1.did =d1.DID
END

sp_helptext spEmpDeptDetails
--Alter store procedure
alter procedure spEmpDeptDetails
as
begin
select e1.EID,d1.DeptName from employee e1 , dept d1 where e1.did =d1.DID
END

--Drop the SP
drop proc spEmpDeptDetails

--2.With parameter
--created calculator store procedure
alter proc calculator (@a int,@b int)
as
begin

declare @sum int


declare @sub int
declare @mul int
declare @div int

set @sum = @a + @b
set @sub = @a - @b
set @mul = @a * @b
set @div = @a/@b

print(@sum)
print(@sub)
print(@mul)
print(@div)
END

--how to execute SP with parameter


exec calculator 80,10

calculator

--Alter the store procedure


--Drop stored procedure

--Diffrence between view and Stored Procedure


-- VIEW
STORED PROCEDURE(SP)
--1.View does not accept parameters 1.SP accepts
parametrers.
--2.View can contain only single SELECT query 2.SP conatins
several SELECT staements with condition like if, else etc.
--3.By using view can not perform modification to table. 3.We can perform
modification to one or more tables
--4.View acts as virtual table 4.SP
is acts as function

You might also like