0% found this document useful (0 votes)
77 views26 pages

SQL

The document discusses how to create and manage databases and tables in SQL. It shows how to create a database called "Testing16", create a table called "student" with various columns, and insert data into the student table by specifying values for each column. It also demonstrates how to select, filter and sort data from the student table using WHERE and other clauses. Various SQL operators, joins and constraints are defined along with examples.

Uploaded by

Sonal Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
77 views26 pages

SQL

The document discusses how to create and manage databases and tables in SQL. It shows how to create a database called "Testing16", create a table called "student" with various columns, and insert data into the student table by specifying values for each column. It also demonstrates how to select, filter and sort data from the student table using WHERE and other clauses. Various SQL operators, joins and constraints are defined along with examples.

Uploaded by

Sonal Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 26

---How to create database----

create database Testing16

----Ho wto go to a particular database-----


use Testing16

---How to create tabel----


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))

----How to insert the data from a table-----


select * from student
tru
----How to insert data into the table----
insert into student
values(1,'Jhon','10','datascience','+917856','jhon@hotmail.com')
insert into student values(2,'mark','11','ETL','+917576','mark@hotmail.com')
insert into student values(3,'Steve','8','Testing','+917899','')
insert into student values(4,'Moore','3','Bigdata','+917456','moore@hotmail.com')
insert into student values(5,'Kate','5','python','+917567','kate@hotmail.com')
insert into student values(6,'tony','11','ML','+9175123','tony@gmail.com')

---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

--what is clause ? diffrent types of clauses


--Clause is used for filtering purpose
--types of clauses
--1.Where --Comaprison operator.arithmatic,logical
--2.Having - Min(),MAX(),SUM(),AVG() COUNT()
--3.group by -

--how to display particular row ----


select * from student where Student_ID ='1'
select * from student where Student_Clas ='3'

--how to display student name with his class----


select Student_Name from student where Student_Clas = '11'

select * 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))

----How to select the data from a table-----


select * from student
tru
----How to insert data into the table----
insert into student
values(1,'Jhon','10','datascience','+917856','jhon@hotmail.com')
insert into student values(2,'mark','11','ETL','+917576','mark@hotmail.com')
insert into student values(3,'Steve','8','Testing','+917899','')
insert into student values(4,'Moore','3','Bigdata','+917456','moore@hotmail.com')
insert into student values(5,'Kate','5','python','+917567','kate@hotmail.com')
insert into student values(6,'tony','11','ML','+9175123','tony@gmail.com')

--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 student having id 6------


select * from student where Student_Subject != 'bigdata'

---how to display student information whose id not equql to 4


select * from student where Student_ID !='4' --not
select * from student where Student_ID <>'4' --not
select * from student where Student_Subject != 'bigdata'
--how to display the student student information whose id is leass than 4
select * from student where Student_ID <'4'

--how to display the student student information whose id is leass than or equql to
4
select * from student where Student_ID <='4'

--how to display the student student information whose id is greater than 3


select * from student where Student_Subject > 'ml' -- by using chareter data alaos
we can compare
select * from student where Student_ID > '4'

--how to display the student student information whose id is greater than 3


select * from student where Student_Subject >= 'ml' -- by using chareter data
alaos we can compare
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'

--Q: What is the diffrence between IN and Between.


--Q: What is the diffrence not between and Between.
---not between----
select * from student where Student_id not between 5 and 1
select * from student where Student_id not between '1' and '5'

---In

select * from student where Student_subject in ( 'ML','AI')


select * from student where Student_id not in (1,4,2)

---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

select * from student


select * from student where Student_Email like'%K%'

--K% --- Strat with k later it will display


--%K --- End with k later it will display
--%k% --- anywhere inside the record
--By using like statement we can use below wildcards
--%
--'_'
'__M%'

insert into customer values(1,'rina','chandanichowk','delhi')


insert into customer values(2,'ram_patil','koregaon','Bombay')
insert into customer values(3,'seema','ravet','pune')
insert into customer values(4,'Rohan','motera','gujrat')
insert into customer values(5,'sameer_more','seacostal','goa')

--To display the structure of the table -----


sp_help customer

select * from customer where Cust_ID like '2%'


truncate table customer
-- Constraints---
--Q;What is constraints?
--To Maintain the accuracy and integrity of the data
--1.Primary Key
--2.FOREIGN Key
--3.Unique Key
--4.Not Null Key
--5.Check Key
--6.Default Key

--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))

select * from prime

insert into prime values(1,'rina','chandani c','delhi')


insert into prime values(2,'ram_patil','koregaon','Bombay')
insert into prime values(3,'seema','ravet','pune')
insert into prime values(4,'Rohan','motera','gujrat')
insert into prime values(5,'sameer','seacostal','goa')

--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))

select * from department

insert into department values (1,'Civil')


insert into department values (2,'Mech')
insert into department values (3,'E&c')

create table student_D(


S_ID int primary key,
S_Name varchar(10),
dept_ID int foreign key references department(dept_ID))
select * from department
select * from student_D

insert into student_D values(1,'Praveen',3)


insert into student_D values(2,'sohan',1)
insert into student_D values(3,'mohan',2)
insert into student_D values(4,'priya',1)
insert into student_D values(5,'Renuka',2)

CREATE TABLE Persons (


PersonID int Primary key,
FirstName varchar(20),
LastName varchar(20),
age int)

insert into Persons values (1,'Jhon','Moore',32)


insert into Persons values (2,'Steave','Jobs',55)
insert into Persons values (3,'Mark','Wagh',33)
insert into Persons values (4,'Ross','Tyalor',43)
insert into Persons values (5,'Kane','mark',65)

select * from Orders


---join between PK and FK tables
select * from persons pe join orders od on pe.PersonID = od.PersonID

CREATE TABLE Orders (


OrderID int PRIMARY KEY,
OrderNumber int ,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
)
select * from persons pe join orders od on pe.PersonID =od.PersonID
insert into orders values (1,7856,4)
insert into orders values (2,1345,2)
insert into orders values (3,2345,1)
insert into orders values (4,3421,3)
insert into orders values (5,6754,4)
insert into orders values (6,6754,5)
select * from Persons
select * from Orders

--Q:Create product table and provide the refrences of Product model and product
location?

--3.NOT Null Key


--Not Null constraint restricts a column from having a "NULL" value.
--Once not null constraint is applied to column you cant pass "NULL" value.
--if we define not null constraint to column it should not accept a null value.
--It allows duplicate value into column.

create table NOTNULL (N_ID int primary key,


N_Nmae char(10) NOT NULL ,
age int not null)

drop table NotNull


select * from NotNull

update notnull set n_nmae = NULL where N_ID =3

insert into NotNull values(1,'Praveen','')


insert into NotNull values(2,'Praveen',23)
insert into NotNull values(3,'',23)
insert into NotNull values(4,'',24)
insert into NotNull values(5,Null,Null)
insert into NotNull values(6,null,null)

select * from NotNull

--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.

create table checkkey (C_ID int primary key,


N_Nmae varchar(10),
age int check (age>15))

insert into checkkey values(1,'Praveen','17')


insert into checkkey values(2,'Riya',15)
insert into checkkey values(3,'Harsha',16)
insert into checkkey values(4,'Sohan',13)
insert into checkkey values(5,'mohan',10)

select * from checkkey

--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.

create table defaulties(


d_id int,
dname varchar(10),
dpost int default '411061')

insert into defaulties values (1,'meena','411061')


insert into defaulties values (2,'meena','')
insert into defaulties values (3,'heena', default)
insert into defaulties values (2,'tina')
insert into defaulties (d_id,dname) values(4,'kiya')

--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)

select * from defaulties

--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.

create table unique1(


d_id int unique,
dname varchar(10),
dpost int default '411061')

select * from unique1

insert into unique1 values (1,'meena','411027')


insert into unique1 values (2,'Rihan','411051')
insert into unique1 values (3,'heena', default)
insert into unique1 values (NULL,'heena', default)

insert into unique1 values (NULL,'Meera', default)

--Types of SQL Statements---


--1.DML -(Data Manipulation Language) - Select,Insert,Update,Delete. (S_UID)
--2.DDL -(Data Defination Language) -Create,Alter,Drop,Truncate.(Dr.CAT)
--3.DCL -(Data Control language) - Grant, Revoke
--4.TCL - (Transaction Control Language) - BEGIN TRAN,COMMIT TRAN, ROLLBACK.

--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

update customer set loc='Paddar Road' where cust_name ='Rina'

--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'

select * from customer

insert into customer values(4,'Rohan','kurla','Mumbai')

--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))

insert into emp values (1,'rajesh','30000','Warngal')


insert into emp values (2,'Sada','40000','karnool')
insert into emp values (3,'sohan','70000','hyderabad')
insert into emp values (4,'phani','25000','vijaywada')
insert into emp values (5,'pushpa','45000','rayalshema')

--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

select * from emp


--adding E_Contact column into the EMP table
--we can add multiple columns at a time
alter table emp add E_contact varchar(10),E_Address varchar(15)

update emp set E_Contact = '123' where E_ID = 1

--Check the structure of the table


sp_help emp

--deleting the E_contact from EMOP table


--This syntax works properly if data type is not provided to that column.
-- We can delete multiple columns at atime.

alter table emp drop column E_Contact ,E_Address

--Q: Define table column with constraint(Primary key) and use alter operation to
drop that column?

--change the data type of E_salary column to decimal.


alter table emp alter column E_sal decimal

-- Change the size of E_Loc column from 10 to 15 in varchar Data type


alter table emp alter column E_Loc varchar(15)

--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.

select * from emp

truncate table emp

--Q.What is the diffrence between DML AND DDL Command.?


--Q.What is the diffrence between Delete AND Truncate Command.?
--Q.What is the diffrence between Drop AND Truncate Command.?
--Q.What is the diffrence between Drop AND Delete Command.?
--Q.how to update more than one columna at once?

--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.

Create table employee (


E_id int,
E_Name varchar(20),
E_Org varchar(20),
E_sal int)

insert into employee values(1,'Rina','IBM',70000)


insert into employee values(2,'simran','CTC',60000)
insert into employee values(3,'Rihana','Capgi',65000)
insert into employee values(4,'sohan','Google',90000)
insert into employee values(5,'mohan','Infy',55000)
insert into employee values(6,'naveen','Mastercard',85000)
insert into employee values(7,'','Mastercard',85000)
insert into employee values(8,'','BOA','')
insert into employee values(9,NULL,'jhonson',NULL)
insert into employee values(NULL,NULL,NULL,NULL)
insert into employee values(11,'10','@123',NULL)
insert into employee values(12,'Mohan','123@',25000)
--we can use alias to any column in select list for our better understaning about
the column by using 'as' as syntax/keyword.
select min(E_sal) as minimum from employee
--2.max()
--this function return the largest value of the selected columns.
select * from employee
select max(E_sal) as maximum_value from employee

--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 Count(*) from employee

select * from employee


select count(E_name) as ename from employee
select count(E_sal) from employee

--Must ask Interview syntax about count


select count(1) ---o/p = 1
select count('scodeen') --o/p= 1

--Note: Count() function always requires only one argument


-- in count argument is always mandatory.

select count('scodeen','analyst') ---Error

select count(anup) --- error

select count() --- error

select count(12454768) + count(10) ---- o/p = 2

select count('anup') + count(1) ---- o/p = 2

select 8 ---o/p -8

select 8,* from employee


select 8 as new from employee ---- As per the record prsent in employee table
that many times 8 will display.
--4.Top
--Top() function is used to specify the number of records to return
--Top() function is useful on large tables or which contains millions of records.

select top 2 * from employee where E_id >5


select top 2 * from employee

--5.Sum
--It is used to to add the complete column.
--sum() function returns the total sum of numeric column.
--NULL values are ignored

select * from employee

select sum(E_Sal) as totalsalary from employee where e_id in (5, 7)

--6.Avg
--This function is used to find the average of the column or with specifed
condition.
--NULL values are ignored.
select * from employee

select Avg(e_sal) as avgsalary from employee where e_id >5

--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 ?

select * from employee

select * from employee order by E_id asc --0-9


select * from employee order by E_Org -- special charecter,0-9,A-Z a-z (In varchar
Column) -ASC

select * from employee order by E_sal desc

--Q.what is subquery?
--To write query within query to call subquery.

--Q.How to find the highest salary from a table? ---Max


--Q.How to find the minimum salary from a table? ---Min
--Q.How to find the 5th highest salary from a table?
--Q.How to find the 4th lowest salary from a table?
--1

select * from employee order by E_sal desc

--- fifth highest salary-----


select min(E_sal) from employee where E_sal in
(select top 6 E_sal from employee
order by E_Sal desc)

---4th lowest salary


select max(E_sal) from employee where E_Sal in
(select top 4 E_sal from employee
order by E_sal ASC)

create table emp1(EID int primary key,


EName varchar(15),
EDEPT varchar(15),
ESAL int)

insert into emp1 values (1,'Jhon','HR',1000)


insert into emp1 values (2,'Mark','Finance',5000)
insert into emp1 values (3,'Tony','ERP',3000)
insert into emp1 values (4,'MONI','HOO',2500)
insert into emp1 values (5,'Shaun','Account',3500)
insert into emp1 values (6,'Kane','CSR',1500)
insert into emp1 values (7,'Shakira','HumanWelfare',4000)
insert into emp1 values (8,'michel','Public',1000)
select * from emp1 order by esal desc

--Q display only the 4th lowest and 5th highest salary avoiding the same salary
from order by clause?

select min(esal) from emp1 where esal in


(select top 4 (esal) from emp1 order by esal desc)

----will discuss this once we complete joins(self join) -----


select * from emp1 e1
where 4 =(select count(esal) from emp1 e2 where e1.esal <= e2.esal) --1 <= 8

--we need to display 4th highest salary with complete details.


--we need to display 3rd lowest salary with complete details.
select * from emp1

select * from emp1 where esal in


(select top 4 (esal) from emp1 order by esal desc)

select top 4 (esal) from emp1 order by esal desc


--select min(esal) from emp1
--Q Use the above query without primary key?

select top 4 (esal) from emp1

select * from emp1 order by esal asc

--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.

create table emp_IBM(EID int primary key,


EName varchar(15),
EDEPT varchar(15),
ESAL int)
select * from emp_IBM

insert into emp_IBM values (1,'Jhon','HR',1000)


insert into emp_IBM values (2,'Mark','Finance',5000)
insert into emp_IBM values (3,'Tony','Finance',3000)
insert into emp_IBM values (4,'MONI','HR',2500)
insert into emp_IBM values (5,'Shaun','Account',3500)
insert into emp_IBM values (6,'Kane','CSR',1500)
insert into emp_IBM values (7,'Shakira','HR',4000)
insert into emp_IBM values (8,'michel','Public',1000)
insert into emp_IBM values (9,'ricky','Account',1800)
insert into emp_IBM values (10,'Mike','Public',1000)
insert into emp_IBM values (11,'Jhon','HR',1100)
insert into emp_IBM values (12,'Jhon','HR',NUll)
insert into emp_IBM values (13,NULL,'HR',NUll)
select distinct(edept) from emp_IBM

select max(esal),EDEPT,ename from emp_IBM where EDEPT = 'HR'group by EDEPT,ename

select max(esal),EDEPT,ename from emp_IBM group by EDEPT,ename where EDEPT = 'HR'


--Error because where clause can be used before group by
select * from emp_IBM group by EDEPT ,EName,EID

select * from emp_IBM where ESAL in


(select max(esal) from emp_IBM)

select max(esal),EDEPT,ename from emp_IBM where EDEPT = 'HR'group by EDEPT,ename


order by EName
select EDEPT from emp_IBM group by(EDEPT)

select ESAL from emp_IBM group by

--Display department wise highest salry ?


--Q.display department wise highest salary with department name?

select EDEPT,max(esal) from emp_IBM


group by EDEPT

--Q.display department wise highest salary with employee details?

select * from emp_IBM


where ESAL in
(select EDEPT,max(esal) from emp_IBM
group by EDEPT)

--Having
--having clause was added in SQL because we cant use WHERE clause with aggregate
functions.

select * from emp_IBM

--Display a group of edept which is having count is <=2


select count(EID) AS NUMBER_EMP,EDEPT from emp_IBM group by EDEPT having
count(edept) <=2

--Display a group of edept which is having count is >2


select count(EID) ,EDEPT from emp_IBM group by EDEPT having count(edept) >2

--Q.In group by where you can use having and where clause?
select * from emp_IBM

select count(EID) AS NUMBER_EMP,EDEPT from emp_IBM where edept = 'CSR'group by


EDEPT having count(edept) >2

---How to take backup of table


select * into EMP_TCS from emp_IBM

select * from EMP_TCS

--Insert into select


-- this syntax copies the only records from one table into another by specifying
the condition
--if we want to copy data(records) from one table to another then data types should
match.
--EMP_TCS_HR
create table EMP_TCS_HR(EID int,
EName varchar(10),
EDEPT varchar(15),
ESAL int)
drop table EMP_TCS_HR

select * from EMP_TCS_HR

insert into EMP_TCS_HR


select * from EMP_TCS where EDEPT ='HR'

--Q.Diffrence between Where and having?


--Q.Diffrence between order by and group by?
--Q.How to take table back up?
--Q.How we can insert selective records from one table into another table?
--Q.How to display the structure of the table?
--Q.how to change or rename the column name?

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.

--Q.How to take the data base backup?


BACKUP DATABASE testing16 TO DISK = 'C:\SQL2019'

select * from EMP_TCS_HR


sp_help EMP_TCS_HR

Sp_rename 'EMP_TCS_HR.EDEPT' ,'DEPARTMENT'

--Q.How to find the schemas of tables?


--Q.How will identify the table name from database if your are not remember a table
table name?

select * from INFORMATION_SCHEMA.tables

--Q.How to find the number of columns from particular table ?


select Count(*) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'emp1'

--Q.How to find the columns names from particular table ?


select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'emp1'

--Q.How to find the complete details about particular table ?


select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'emp1'

select * from INFORMATION_SCHEMA.TABLES where Table_name like 'e%'

--Q.How to find duplicate records from a table ?


--Syntax for Duplicate
--select <PK1>,<PK2>,Count(*) as Duplidate from Table_name group by <PK1>,<PK2>
having count(*) > 1
--select All The columns from table ,Count(*) as Duplidate from Table_name group by
All The columns from table having count(*) > 1
select * from student

select Student_Subject ,count(*) as duplicate from student group by


Student_Subject having count(*) > 1

--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

--Q.How to delete or drop the database?


Drop database tue

--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.

--Q.How to test for NULL values?


--we can test NULL value by using IS NULL and IS NOT NULL.

select *from emp_IBM where ESAL is null


select *from emp_IBM where ESAL is not null

select * from emp_IBM

--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))

insert into A Values (1001,'Rohan')


insert into A Values (1002,'Vishal')
insert into A Values (1003,'Riya')
insert into A Values (1004,'Priya')
insert into A Values (1005,'Mohan')
insert into A Values (1006,'Simon')
select * from A

create table B (Bid int,


LOC varchar(15),
Aid int)

insert into B Values (101,'Pune',1004)


insert into B Values (102,'Sangali',1003)
insert into B Values (103,'Latur',1005)
insert into B Values (104,'Mumbai',1002)
insert into B Values (105,'Kota',1001)
insert into B Values (106,'Kota',1007)
insert into B Values (107,'Kota',1007)

select * from A
select * from B

--Inner Join of table A and B


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

--You can select specific columns after joining the two tables

select A.Aid,A.Aname,B.LOC from A join B on a.Aid = b.Aid

create table C (Cid int,


Country varchar(15),
Bid int)

insert into C values (1,'US',101)


insert into C values (2,'UK',102)
insert into C values (3,'USSR',103)
insert into C values (4,'UAE',104)
insert into C values (5,'Japan',105)
--Join three tables A<B and C
select * from A join B on a.Aid= b.Aid
join c on b.Bid = c.Bid

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.

--JOINs work if there are FK or not.

--FK's work if you extract data with or without JOINs.

--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.

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

--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).

create table EMP_CTS(E_ID int,


E_Name varchar(15),
M_ID int)

insert into EMP_CTS values (1,'Praveen',3)


insert into EMP_CTS values (2,'Sohan',1)
insert into EMP_CTS values (3,'Ragini',4)
insert into EMP_CTS values (4,'Sujita',5)
insert into EMP_CTS values (5,'MOhan',2)

select * from EMP_CTS

select * from EMP_CTS E,EMP_CTS M


where E.M_ID =M.E_ID

select Employ.E_ID,Employ.E_Name,Manager.M_ID from EMP_CTS Employ,EMP_CTS Manager


where Employ.M_ID =Manager.E_ID

select E.E_ID,E.E_Name,M.E_Name as Employee_Manger from EMP_CTS E,EMP_CTS M


where E.M_ID =M.E_ID

--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?

select * from INFORMATION_SCHEMA.TABLES

--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.

create table set1(S_ID int,


Fname varchar(15),
LName varchar(15),
Loc Varchar(15),
City varchar(15))

create table set2(S_ID int,


Fname varchar(15),
LName varchar(15),
Loc Varchar(15),
City varchar(15))

create table set3(S_ID int,


Fname varchar(15),
LName varchar(15),
Loc Varchar(15),
City varchar(15))

insert into set1 values(1,'Amit','Patil','SP','Sangali')


insert into set1 values(2,'Sohan','Mane','STC','Miraj')
insert into set1 values(3,'Rahul','Rane','ABC','Kokan')
insert into set1 values(4,'Viraj','Sharma','Andheri','Mumbai')
insert into set1 values(5,'SIta','Varma','West','Goa')
insert into set1 values(6,'Kumar','Varma','CBC','Patna')

insert into set2 values(1,'Amit','Patil','SP','Sangali')


insert into set2 values(2,'Sohan','Mane','STC','Miraj')
insert into set2 values(3,'Rahul','Rane','ABC','Kokan')
insert into set2 values(6,'Kumar','Varma','CBC','Patna')
insert into set2 values(7,'Kiran','Rijju','TBC','Manipur')

insert into set3 values(6,'Kumar','Varma','CBC','Patna')


insert into set3 values(7,'Kiran','Rijju','TBC','Manipur')
insert into set3 values(8,'Pavn','Tamang','YBC','Rohatang')

select * from set1


select * from set2
select * from set3

select * from set1


union
select * from set2
union
select * from set3
--2.Unoin ALL
--This operator is used to list two or more tables using select statement when both
the tables have the same no of columns and same order.
--Combine two tables into a single with all the values , it means that it will
allow duplicate values in it.

select * from set1


select * from set2
select * from set3

select * from set1


union all
select * from set2
union all
select * from set3

--3.Intersection
--It will return only distinct(Common records) values from the tables.

select * from set1


select * from set2
--select * from set3

select * from set1


intersect
select * from set2
intersect
select * from set3

--SET Operator Concept:


-- A={1,2,3,4}
-- B={3,4,5,6}
--A union B - O/P --{1,2,3,4,5,6}
--A union all B - O/P --{1,2,3,4.3.4.5.6}
--A intersect B -O/P --{3,4}

--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?

---date and time function----


select GETDATE() +1 as Tommorowdate ----Tommorow date
select getdate() -1 as yesterdaydate ----yesterday date
select GETDATE() as todaysdate ----- today's date

---Date diffrence function------


-----(YY,MM,DD,HH,MINUTE,SS) diffrence btween years,month,days,hours,minutes and
seconds
--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 = Week
--weekday, dw, w = Weekday
--hour, hh = hour
--minute, mi, n = Minute
--second, ss, s = Second
--millisecond, ms = Millisecond
select DATEDIFF(YY,'2020/01/01','2021/07/01')

---how to calculate age-----

select Datediff(YY,'1987/09/13',GETDATE())

Create Table bank_account(AcctNO int identity(12345461,1) primary key check (acctno


<20),
accname Varchar(20),
acct_open_date date,
Branch varchar(20))

insert into bank_account values ('Venkat','2017/07/23','Delhi')


insert into bank_account values ('Sampath','2015/08/27','Mumbai')
insert into bank_account values ('Nagesh','2019/11/22','Chennai')
insert into bank_account values ('Virat','2017/09/24','Kota')
insert into bank_account values ('Sohan','2020/05/17','Jaipur')
insert into bank_account values ('Ramraju','2018/04/11','Ahemdabad')
insert into bank_account values ('Ramraju','2021/04/12','Ranchi')

select * from bank_account

----what is the age of your account in bank----

select accname ,branch, Datediff(YY,acct_open_date,getdate()) as accountage from


bank_account

----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())

---date name ----


select datename(MM,getdate()) as months
select DATEname(DW,getdate()) as weekdays
select DATEname(dayofyear,getdate()) as dayoftheyear
select datename(MM,getdate()),DATEname(DW,getdate()),DATEname(dayofyear,getdate())

---last year and lastmonth----


select datepart (mm,getdate()) -1 ----last month
select datepart(yy,getdate()) -1 -----lastyear
select datename(MM,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.

Create Table bankaccount(AcctNO int identity(1111288780,5) primary key,


accname Varchar(20),
acct_open_date date,
Branch varchar(20))

insert into bankaccount values ('Venkat','2017/07/23','Delhi')


insert into bankaccount values ('Sampath','2015/08/27','Mumbai')
insert into bankaccount values ('Nagesh','2019/11/22','Chennai')
insert into bankaccount values ('Virat','2017/09/24','Kota')
insert into bankaccount values ('Sohan','2020/05/17','Jaipur')
insert into bankaccount values ('Ramraju','2018/04/11','Ahemdabad')

select * from bankaccount

--NULL Fuctions
--Three different ways by which we can identify the null values
--IS NULL
--COALESEC
--Case

create table team (tid int, t_name varchar(15),manger_id varchar(15))

insert into team values(1,'steave',4)


insert into team values(2,'Kate',1)
insert into team values(3,'Mark',NULL)
insert into team values(4,'Bob',2)
insert into team values(5,'Tony',2)
insert into team values(Null,'Tony',5)
insert into team values(6,NULL,5)
insert into team values(7,'Tony',NULL)

select * from team

delete team where tID = 7

--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

--error - The isnull function requires 2 argument(s).


select t.t_name as teamname ,isnull(m.t_name) as manager from team t
left join team m on t.manger_id = m.tid

--NVL Function---- with oracle (SQL


--IFNULL Fuction--- with MysSQL

--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.

select * from team


select t.t_name as teamname,
case when m.t_name IS NULL then 'No Manager' else 'manager is present'
end as managerSearch
from team t left join team m on t.manger_id = m.tid

---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.

select t.t_name as teamname ,coalesce(m.t_name,'No Manager') as manager from team t


left join team m on t.manger_id = m.tid
select coalesce(tid,manger_ID) as T_Name from team

create table Teams (tid int, F_name varchar(15),M_Name varchar(15),L_Name


varchar(15))

insert into teams values(1,'Praveen',NULL,NULL) --1,Praveen


insert into teams values(2,NULL,'Rohan',NULL) --2,Rohan
insert into teams values(3,NULL,NULL,'Mohan') --3.Mohan
insert into teams values(4,'Komal',NULL,NULL) --4,Komal
insert into teams values(5,NULL,'Sohan',NULL) --5,sohan
insert into teams values(5,NULL,'NIkam','Jayant') -- 5,Nikam
insert into teams values(6,NULL,NUll,NULL) -- 6,NULL
insert into teams values(NULL,NULL,'NIkam','Jayant')

-- 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.

select tid,coalesce(F_Name,M_Name,L_Name) as T_name from Teams


select * from Teams
select coalesce(F_Name,M_Name,L_Name) as T_name from Teams

select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME ='Employee_Capita'

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)

select * from Employee_Capita

select gender,count(*) ,min(salary) as minsal,max(salary) as maxsal ,Avg(salary) as


avgsal from employee_capita
group by gender

--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

--Better way of doing the above query by using Over by clause.

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 sum(salary) from Employee_Capita where Gender ='F'


select count(*) from Employee_Capita where gender= 'F'
select count(gender) over (partition by gender) 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;

(select top 2 salary from Employee_Capita order by salary desc)


where salary in (select max(salary) from Employee_Capita group by Gender)
select * from Employee_Capita
select *,RANK() over (order by salary desc) as ranks from Employee_Capita
select *,DENSE_RANK() over (order by salary desc) as denseranks from
Employee_Capita

--2nd Highest salry by using Rank()


with result as (
select *,
rank() over (order by salary desc) as ranks
from Employee_Capita)
select top 1 * from Result where ranks = 3

--2nd Highest salry by using dense_Rank()


with Result as
(
select *,
DENSE_RANK() over (order by salary desc) as denserank
from Employee_Capita
)
select top 1 * from Result where denserank= 2

--third highest salry of female employee.


with Result as
(
select *,
DENSE_RANK() over (Partition by gender order by salary desc) as denserank
from Employee_Capita
)
select top 1 * from Result where denserank= 3 and Gender ='F'

--CTE(Comman Table expression)


--It is temporary result set.
--It can be referred within a SELECT,INSERT,UPDATE and DELETE Statement that
immediately follows the CTE.
--Syntax
--With CTE_Name (Col1,col2.....)
--AS
--(CTE_Query)

create table EMP16 (


ID int,
ename varchar(15),
gender varchar(2),
deptid int)

insert into EMP16 values (11,'jhon','M',3)


insert into EMP16 values (12,'mona','F',2)
insert into EMP16 values (13,'Shina','F',1)
insert into EMP16 values (14,'Tony','M',4)
insert into EMP16 values (15,'Siya','F',1)
insert into EMP16 values (16,'Mark','M',3)

create table DEPT16 (


deptid int,
dname varchar(15))

insert into DEPT16 values(1,'IT')


insert into DEPT16 values(2,'PAYROLL')
insert into DEPT16 values(3,'HR')
insert into DEPT16 values(4,'ADMIN')
insert into DEPT16 values(5,'Finance')

select * from EMP16


select * from DEPT16

--Displaying only those department which has employees


with empcount1 (deptid,totalemp)
as
(select deptid,count(*) as totalemp from EMP16 group by deptid
)
select dept16.dname,empcount1.totalemp from DEPT16 join empcount1 on
dept16.deptid= empcount1.deptid
order by totalemp

--all the department whether it has employessa or not


with empcount1 (deptid,totalemp)
as
(select deptid,count(*) as totalemp from EMP16 group by deptid
)
select dept16.dname,empcount1.totalemp from DEPT16 left join empcount1 on
dept16.deptid= empcount1.deptid
order by totalemp

select * from DEPT16


select * from EMP16

--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)

select * from student

insert into student


values(1,'Jhon','10','datascience','+917856','jhon@hotmail.com')
insert into student values(2,'mark','11','ETL','+917576','mark@hotmail.com')
insert into student values(3,'Steve','8','Testing','+917899','')
insert into student values(4,'Moore','3','Bigdata','+917456','moore@hotmail.com')
insert into student values(5,'Kate','5','python','+917567','kate@hotmail.com')
insert into student values(6,'tony','11','ML','+9175123','tony@gmail.com')

select student_ID,Count(*) AS DUPLICATE from student group by student_ID having


count(*) > 1

--How delete the duplicate records


with result
as
(
select *,ROW_NUMBER() over ( Partition by student_id order by student_id) as
rownumber from student
)
delete from result where rownumber > 1

select * from student

--SQL Function
--1.UPPER()
--UPPER() function converts the value of field/Column to Uppercase.
--Syntax : select UPPER(Column_name) from Table_Name

select upper (student_name) as uppercase from student

--2.LOWER()
--LOWER() function converts the value of field/Column to lowercase.
--Syntax : select lower(Column_name) from Table_Name

select lower (student_name) as lowercase from student

--3.Substring
--The substring function used to extract charecter from text field
--Synatx : select substring(Column_Name,Start,end[lenth]) from table_Name

select *,SUBSTRING(student_name,1,3) 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()
--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

--5.CONCAT() and CONCAT PLUS


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

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


select * from student
select CONCAT(student_name,' ',student_subject) as namensubject from student
select Student_Name + student_subject as namensubject from student
select 'praveen' +' '+'Patil'

--6.LTRIM
--It will remove leading spaces

select Ltrim(' Scodeen ')


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

--7.Reverse
--it will reverse the string.
select REVERSE('Pune')

--8.Round
create table round1 (value1 decimal)

insert into round1 values (23.45)


insert into round1 values (23.56)
insert into round1 values (11.45)
insert into round1 values (34.50)
insert into round1 values (38.76)

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 student

create view studentNameEmail as


select student_name,Student_email from student

select * from studentNameEmail

select * from

create view vDeptnameEmpCount as

with empcount1 (deptid,totalemp)


as
(select deptid,count(*) as totalemp from EMP16 group by deptid
)
select dept16.dname,empcount1.totalemp from DEPT16 join empcount1 on
dept16.deptid= empcount1.deptid
order by totalemp

select * from vDeptnameEmpCount

drop view vDeptnameEmpCount

You might also like