SQL
SQL
---insert values by using complete columns names without entering all the column
details
INSERT [student] (Student_ID, Student_Name, Student_Clas, Student_Subject,
Student_contact) VALUES (7,'richard','9','UNIX','+917654')
---If i want to display only student id and student name----
select Student_ID,Student_Name from student
use Testing16
--sql
--operator
--1.arithmatic : +,-,/,*
--2.logical: AND,OR,NOt
--3.comparisson :<,> <=,>=,!
create table student(
Student_ID int,
Student_Name varchar(50),
Student_Clas varchar(50),
Student_Subject Varchar(50),
Student_contact Varchar(50),
Student_Email varchar(50))
--Comaprioson operator
--1.equal to =
--2.not equal to != ,<>
--3.less than <
--4.greater than >
--5.less than equal to <=
--6.greater than equql to >=
--7.between -----VIMP
--8.In ,Not In-----VIMP
--9.Like -VIMP
--how to display the student student information whose id is leass than or equql to
4
select * from student where Student_ID <='4'
select * from student where Student_Subject > '5' ----Issue will take this and
discuss
---Between---
--How to display the data between 1 to 5
select * from student
select * from student where Student_id between 1 and 5
select * from student where Student_id between '1' and '5'
---In
---Like
--This is used for searching pattern from a given string or charecter
--like operator mostly we are using with charecter and we can use with integer also
--like operator is used in where clause
--1.Primary Key
--Not NULL + Unique
--uniquely identifies each record in the table
--primary key is used only with numeric value
create table prime (P_id int primary key,---0-9
P_name varchar(10),--0-9.a-z,special charecter
P_Loc varchar(10) not null,
P_city varchar(10))
--2.FOREIGN Key
--Ensure that all values in a column are diffrent
--One null value can be applied at column level or table level
--it means that it can accept one null valueand it can not be NULL twice.
create table department (
dept_ID int primary key,
Dept_Name Varchar(10))
--Q:Create product table and provide the refrences of Product model and product
location?
--4.Check key
--it ensure that all values in a column satisfies a specific condition,
--check constarint is used to restrict the value of a column between range.
--it is just like condition checking before inserting a data into column.
--Q: Check whether chek key we can use with diffrent data types?
--Q:what is the diff between not null key and primary key
--Q: what is the diffrence unique and null key?
--Q: How many Null values we can insert into unique key column?
--Q- What is the diffrence between primary key and foriegn key?
--5.Default
--sets a default value for column when vlaue is specified.
--to insert the default value below t are the two ways we can insert thee data into
table
--1
insert into defaulties (d_id,dname) values(5,'Riya')
--2
insert into defaulties values (6,'shina', default)
--6.unique key
--It ensure that all the columns hould have unique value or diffrent values.
--One Null value can be supplied at column level.
--it means that it can accept one null value but not twice.
--1.DML
--Update
--We can update the complete column/attribute at once
--We can upadte a single column by providing the condition.
--We can play with table data not with table columns.
select * from customer
insert into customer values(6,'sonal','kurla','Mumbai')
--To Display how many tables rae present in particular data base when we are not
aware about the table names.
select * from INFORMATION_SCHEMA.TABLES
--Delete
--Delete syntax is used to delete the complete data of the table but not structure
of that table.
--we can delete particular record by giving specific condition.
Delete customer where cust_name = 'Rohan'
--2.DML
--1.Create
--By using create we can creste fresh database and new table.
Create table emp(
E_ID int,
E_name Varchar(10),
E_Sal int,
E_Loc varchar(10))
--2.Alter
--By using alter we can play with table attributes(columns)
--we can add columns
--We can delete columns
--we can change the data types of particular column
--We can increase or decrease the size of that column
--Q: Define table column with constraint(Primary key) and use alter operation to
drop that column?
--3.drop
--it will drop the table inculding its structure and records.
select * from emp
drop table emp
--4.truncate
--It will allow you to delete the records from a table at once.
--Ii wont affect to the structure of the table.
--Functions
--1.Min
--2.Max
--3.Count
--4.Top
--5.sum
--6.avg
--1.min
--Min() function returns the smallest value of the selected columns.
--3.count()
--it will display the number of records present in table or in column.
--It wont count if NULL values are prsent in column level.
--it will consider the row in count if all the values are NULL.
select 8 ---o/p -8
--5.Sum
--It is used to to add the complete column.
--sum() function returns the total sum of numeric column.
--NULL values are ignored
--6.Avg
--This function is used to find the average of the column or with specifed
condition.
--NULL values are ignored.
select * from employee
--Order by Clause---
--This clause is used to sort the result in ascending or decending order.
--syantax will be order by
--by default order by sort in ascending order
--If the column contains NULL value while doing order by always NULL value should
be first in ASC and Last in DESC.
--Q:Perform by adding values and strings in varcharcolumn which will sort first ?
--Q.what is subquery?
--To write query within query to call subquery.
--Q display only the 4th lowest and 5th highest salary avoiding the same salary
from order by clause?
--group by
--it is basically used to group rows that have same values.
--it is often used used with functions COUNT(),MAX(),MIN(),SUM() and AVG() to group
the result.
--Having
--having clause was added in SQL because we cant use WHERE clause with aggregate
functions.
--Q.In group by where you can use having and where clause?
select * from emp_IBM
sp_rename 'EMP_TCS_HR.ESAL','SALARY'
--while rename the column it will give you the below caution
--Caution: Changing any part of an object name could break scripts and stored
procedures.
--When the table does not contain or not defined any primary key then we will use
all the columns to identify the duplicate records.
select
Student_ID,Student_Name,Student_Clas,Student_Subject,Student_contact,Student_Email,
count(*) as duplicate_Student
from student group by
Student_ID,Student_Name,Student_Clas,Student_Subject,Student_contact,Student_Email
having count(*) > 1
--NULL values
--A column with NULL value is with No value.
--if column optinal we can insert or update record.
--NULL value is different from zero or column contains spcaes/blanck space/empty.
--we can test NULL value by using IS NULL and IS NOT NULL.
--with result as (select esal, ROW_NUMBER() over (PARTITION by esal order by esal
desc) as rw from emp_IBM)
--delete from result where rw> 1
--Join
--1.Inner Join
--2.Self Join
--3.Outer Join
--a.Right Join
--b.Left Join
--c.Full Join
--1. Inner join
--It display only matching records from both the tables.
create table A (Aid int,
Aname varchar(15))
select * from A
select * from B
--You can select specific columns after joining the two tables
select * from A
select * from B
--This another way to join the tables and it will work as inner join
select * from A e1 , B e2, c e3 where e1.Aid = e2.Aid
and e2.Bid = e3.Bid
--A FOREIGN KEY enforces data integrity, making sure the data confirms to some
rules when it is added to the DB.
--A JOIN is used when you extract/query data from the DB by giving rules how to
select the data.
--CONCLUSION: FK and JOIN don't allow you to achieve the same goal!
--Left Join
--It displays the complete table from left side and only matching records from
right side table.
--For example if we tabke A left join B then it will display complete data from
table A and matching records from B.
--Right Join
--It displays the complete table from right side and only matching records from
right side table.
--For example if we tabke A right join B then it will display complete data from
table B and matching records from A.
select * from A right join B on a.Aid= b.Aid
--Full Join
--It will display the data from both the tables.
--It will display complete records whether its matching or not matching.
select * from A
select * from B
select * from A Full join B on a.Aid= b.Aid
select * from A Full join B on a.Aid= b.Aid
select * from A Left join B on a.Aid= b.Aid
select * from A Right join B on a.Aid= b.Aid
--Self Join
--It joins a table on itself with equal and non equal condition.
--Table joins itself (Join within join).
--Q.What is join?
--Q.What are the diffrent types of join.
--Q.What is the diffrence between inner join and outer join?
--Q.What is the diffrence between join and full join?
--Q.What is the diffrence between left join and left outer join?
--Q.What is the diffrence between right join and right outer join?
--Q.What is self join?
--SET Operator
--It is mainly used to detrmine the same type of data from two or more tables
--1.Union
--2.Union All
--3.intersection
--1.Unoin
--This operator is used to combine two or more tables using select statement when
both the tables have the same no of columns
--Combine two or more tables into a single without duplicate.
--3.Intersection
--It will return only distinct(Common records) values from the tables.
--Q. Change the order of Columns in a table and perform SET operator?
--Q. Use union on two tables and apply intersect with another table?
--Q.Can we join Two tables by using SET operator?If Yes HOW?
select Datediff(YY,'1987/09/13',GETDATE())
----who are the customer opening the accounts in the cureent year-----
select accname ,branch, Datediff(YY,acct_open_date, getdate()) as age from
bank_account
where Datediff(YY,acct_open_date, getdate()) =0 ---Current year account
select getdate()
---date part----
select DATEPART(DD,getdate()) as dates
select DATEPART(YY,getdate()) as years
select DATEPART(MM,getdate()) as months
select DATEPART(HH,getdate()) As hours1
select datepart(MCS,getdate())
----dateadd()----
select DATEADD(dd,35,GETDATE()) as nextdate
select DATEADD(YY,30,GETDATE()) as nextyear
select DATEADD(dd,-30,GETDATE()) as previousdate
--YYYY-MM-DD
--Auto Increment
--Auto increment in SQL provide you the auto-increment of number if you have not
provided inside insert statement.
--NULL Fuctions
--Three different ways by which we can identify the null values
--IS NULL
--COALESEC
--Case
--ISNULL function----
select t_name,manger_id ,isnull(manger_id,'NO Manager') as newcolumn from team
select * from team
select t.t_name as teamname ,isnull(m.t_name,'NO MAnager') as manager from team t
left join team m on t.manger_id = m.tid
--Case statement
--Syntax-- CASE WHEN expression THEN 'condition/expression' else
'condition/expression' END
--Caps written words in above syntax is mandotory in the case statement.
---COALESCE function
--It will find or try to locate first appearance of Non-NULL value if it is not
present then it will display NULL at last for that row.
-- it will always take the parameter of same data type in its list
--if we trying to pass the parameter in data type like int and varchar then it will
display the below error
--ERROR -Conversion failed when converting the varchar value 'NIkam' to data type
int.
create Table bank_account1(AcctNO int identity(1,1) primary key check (acctno <6),
accname Varchar(20),
acct_open_date date,
Branch varchar(20))
select * from bank_account1
insert into bank_account1 values ('Venkat','2017/07/23','Delhi')
insert into bank_account1 values ('Sampath','2015/08/27','Mumbai')
insert into bank_account1 values ('Nagesh','2019/11/22','Chennai')
insert into bank_account1 values ('Virat','2017/09/24','Kota')
insert into bank_account1 values ('Sohan','2020/05/17','Jaipur')
insert into bank_account1 values ('Ramraju','2018/04/11','Ahemdabad')
insert into bank_account1 values ('Ramraju','2021/04/12','Ranchi')
--While inserting after sixth row then it shows the below errors
--Msg 547, Level 16, State 0, Line 1164
--The INSERT statement conflicted with the CHECK constraint
"CK__bank_acco__AcctN__4F47C5E3". The conflict occurred in database "Testing16",
table "dbo.bank_account1", column 'AcctNO'.
--The statement has been terminated.
--Msg 547, Level 16, State 0, Line 1165
--The INSERT statement conflicted with the CHECK constraint
"CK__bank_acco__AcctN__4F47C5E3". The conflict occurred in database "Testing16",
table "dbo.bank_account1", column 'AcctNO'.
--The statement has been terminated.
--Over Clause
--Over clause combined with partition by clause and is used to breakup data into
partitions.
--The specified funstions operates for each partition.
--Synatx :
-- function () over (PARTITION BY col1, col2......)
--any of the following function can be used i.e
Count(),avg(),max(),min(),sum(),row_number(),rank() and denserank()
CREATE TABLE Employee_Capita(
Employee_id int IDENTITY(1,1) NOT NULL,
FirstName varchar(50) NULL,
Gender nvarchar (1) NULL,
Salary int NULL
)
select * from Employee_Capita
insert into Employee_Capita values('Luci', 'M',4000)
insert into Employee_Capita values('Stacy', 'F',3500)
insert into Employee_Capita values('MIran', 'F',6500)
insert into Employee_Capita values('Shon', 'M',7000)
insert into Employee_Capita values('Mark', 'M',2500)
insert into Employee_Capita values('jhon', 'M',4600)
insert into Employee_Capita values('rihana', 'F',3200)
insert into Employee_Capita values('sinet', 'F',8800)
insert into Employee_Capita values('george', 'M',7400)
insert into Employee_Capita values('kate', 'F',8800)
insert into Employee_Capita values('Micheal', 'F',7400)
insert into Employee_Capita values('monty', 'M',8800)
--Q.What if we want no aggreagte values in our result set along with aggregate
values.
select firstname,salary,employee_capita.gender,gen.gendertotal,
gen.maxsal,gen.minsal,gen.avgsal
from employee_capita
inner join
(select gender,count(*) as gendertotal,min(salary) as minsal,max(salary) as
maxsal ,Avg(salary) as avgsal from employee_capita
group by gender) as gen
on gen.gender = employee_capita.gender
select firstname,salary,gender ,
count(gender) over (partition by gender) as gendertotal,
Max(salary) over (partition by gender) as maxsal,
Min(salary) over (partition by gender) as minsal,
avg(salary) over (partition by gender) as avgsal
from employee_capita
select firstname,gender,salary,
sum(salary) over (partition by gender order by employee_ID) as runningsalary
from employee_capita where Gender = 'F'
--Rank()and DenseRank()
--it will return a rank starting at 1 based on ordering of rows and imposed by
order by clause.
--order by clause is required or mandotory
--PARTITION BY clause is optional.
--when the data is partitioned by rank it is set to rank 1 when the partition
changes.
--Q. Diffrence between rank and dense rank ?
--Rank function skips ranking if there is same value or tie
--where denserank will not skip tha value or rank or number.
--RANK() - 1,1,3,4,5
--DenseRank() -1,1,2,3,4
select * from Employee_Capita order by Salary desc;
--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 1when the partition changes.
--syantx
--ROW_NUMBER() OVER(ORDER BY Col1,col2)
--SQL Function
--1.UPPER()
--UPPER() function converts the value of field/Column to Uppercase.
--Syntax : select UPPER(Column_name) from Table_Name
--2.LOWER()
--LOWER() function converts the value of field/Column to lowercase.
--Syntax : select lower(Column_name) from Table_Name
--3.Substring
--The substring function used to extract charecter from text field
--Synatx : select substring(Column_Name,Start,end[lenth]) from table_Name
--4.DATALENGTH()
--This function returns the number of bytes used to reprsent the expression.
select DATALENGTH('Scodeen')
select DATALENGTH(Student_Name) from student
select len('Scodeen')
select len(Student_Name) from student
--6.LTRIM
--It will remove leading spaces
--7.Reverse
--it will reverse the string.
select REVERSE('Pune')
--8.Round
create table round1 (value1 decimal)
select ROUND(78.22,2)
select ROUND(78.56,2)
--VIEW
--A view is nothing but more than SQL query.
--A view can also considered as virtual table.
--Syntax : Create View VIEW_NAME AS
select * from