SQL181920
SQL181920
--What is SQL?
--Structured Query language.
--Q.what is data?
--Collection of meaningful information.
--Disadvantage
--It stores lessa amount of data.
--no relationship between two files or two sheets.
--Q.What is table?
--It is collection of rows and columns.
--Class-2
--Data types
--Type of data which holds in object is nothing but data type.
--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.Real
--it will store floting point numbers, ranging from -3.4E to 38 to 3.4E to 38
--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);
--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
--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.
--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
--METHOD-II
--This method will allow you to insert the data randomly or column sequence
mentioned inside the insert statements.
--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
--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
--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.
alter table firsttable1 add FSAL int, CITY varchar(10) --To add two columns
sp_help student
--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 from student -- this select statement will display whatever you have
mentioned into the select and it will display w.r.to number of records
--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
--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
--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
--METHOD-II
--This method will allow you to insert the data randomly or column sequence
mentioned inside the insert statements.
--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))
--Q. Define table column by BIT data type with primary key and verify the isert
method?
--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.
---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.
--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.
--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.
--Method -I
insert into default1 values('Ashish','Nasik')
insert into default1 values('Ashish',default)
--Method-II
insert into default1 (DNAME,CITY) values('rohan','sangli')
--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')
--CLASS-7
--Clauses
--Clauses are used for filter the data by using specific condition.
--Purpose of clauses is filtering the data.
--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))
--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.
--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.
--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
--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 %.
--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
--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)
--NOT IN
select * from operators where lastName Not between 'A' and 'o'
--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
--'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 '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 '[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 '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]%'
--I want to search such name whose second letter starts with 'A'
select * from operators where firstName like '_A_E%'
--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
--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
--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, b where a.Aid = b.AID --without applying join statement we can
join two or more 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.
--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.
--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
--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))
--Note : Whenever you are not using join keyword while joing the two tables then it
is called as equi-join.
--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]
--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.
--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
--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
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
--getdate
select getdate() as Todays_date-- Todays 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)
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())
select getdate()
select DATEPART(DD,GETDATE())
select * from Account_details
--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))
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.
--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
--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
--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.
--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
--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
--the above query through an exception saying Windowed functions can only appear in
the SELECT or ORDER BY clauses.
--Syntax:
--WITH CTE_NAME (col1,col2,col3...)
--as
--(CTE query statements)
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;
--2.All the column from table need to include in select and group by list
SP_Help student
--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
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)
--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)
--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('Praveen', 1, 2)
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
--The CONCAT_WS() function adds two or more strings together with a separator.
--syntax : CONCAT_WS(separator, string1, string2, ...., string_n)
select CONCAT(s_id,' ' ,Loc) as NameLocation from student -- whenever you are
using concat function no need to think about the data type.
--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)])
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)
--11.CONVERT()
--The CONVERT() function converts a value (of any type) into a specified datatype.
--Syntax :CONVERT(data_type[(length)], expression, [(style)])
--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)
--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)
--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
--Syntax
--how to create a view
create view vEmployeeDetails as
select * from employee
--Below view will through an exception i.e Incorrect syntax near the keyword
'select'.
create view vEmpDeptDetails as
select * from employee;
select * from dept;
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.
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
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
calculator