SQL Queries All
SQL Queries All
creating database
commands in database
use practiceDb
DML
-------
Insert, update, Delete
DDL
----
Create, Alter Drop
--Alter---It is used for modifiying the meta data information of specific objectsin
database
---DROP:- it is use for deleting the entire objects with structure from database
DCL
----
TCL
----
Commit, Rollback
commit:- It will commit the Data permenently in database after that we cont
rollback the data
Rollback-- It will re-load the previous data
DQL
---
Select--- To view the table data
Session:-2
----------
int
varchar(100)---non unicode data type
1 characteer--1 byte
nvarchar(19)---unicode data type
float
decimal
char()
text
money
sp_help employee
Begin tran
Delete from employee
Rollback
Sp_help employee
sp_help employee
Drop
--2)RELATIONAL OPERATORS:-
EXAMPLE;-
TRUNCATE COMMAND:
IT IS USED TO DELETE ALL RECORDS
DROP COMMAND:-
select distinct e_gender from employee ----(distinct is used o select only distinct
values from our column)
exam:-
Example:-
select * from employee where e_gender='female'
select * from employee where e_age=30;
select * from employee Where e_salary>100000;
ex-
select * from employee where e_gender='Male' AND e_age<30;
select * from employee where e_dept='operations' AND e_salary>100000;
LIKE operator synt :-let's extract recordds where the pattern matches
--select l_list from table_name WHERE Column_N like
--FUNCTIONS
MIN(min()function give you the smallest values
---COUNT(Count function returns the number of rows that match a specfic creteria
ex;-
ex;-
select sum(e_salary)from employee;
---------------STRING FUNCTION;-
Date functions:
select DATEDIFF(dd,'2000-01-04',getdate())--7205
select DATEDIFF(ww,'2000-01-04',getdate())--1029
select DATEDIFF(yy,'2000-01-04',getdate())--19
--STRING FUNCTIONS
--> LTRIM()
select' avulavenkatareddy'
select LTRIM(' avulavenkatareddy')
--->LOWER
Select 'THIS IS VENKATAREDDYYY'
Select Lower('THIS IS VENKATAREDDYYYY')
UPPER
REVERSE()
SUB STRING
---ORDER BY;- Order by is used to sort the data in ascending or descending order
ASCENDING DESCENDIG
-- Let's soft the records with order by clause
--select column list from tablename ORDERBY Col,Cole---ASC/DESC
----GROUP BY;- (Group by is used to get aggregate result with respect to group
----Let'ss group the data
-->
select avg(e_age),e_dept from employee GROUP BY e_dept ORDER BY Avg(e_age)DESC;
----(HAVING CLAUSE);-
Having clause is used in combination with GROUP BY to impose conditions on groups
--> let's impose conditions on groups with the having clause
ex-
select e_dept,avg(e_salary) as avg_salary from employee group by e_dept
JOINS:-
INNER JOIN;-(INNER JOIN RETURNS RECORDS THAT HAVE MATCHING VALUES IN BOTH THE
TABLES. IT IS ALSO KNOW AS SIMPLE JOIN.
syntax:-
select column from table,
Inner join table2 ON table1.column_x=table2,column_z
2) Left Join:(left join returns all the records from the lift table, and the
matched recordds from the right table)
ex;-
3)Right Join:- Right join return all the records from the right table, and the
matched recordds from the left table
4) Full Join
(It returns all rows from the left table and the Right table with Null values
inplace where the Join condtion is not met)
update employee
set e_age=e_age+10
from employee
join department on employee.e_dept=department.d_name
where d_location='Newyork'
Delete employee
from employee
join department on employee.e_dept=department.d_name
where d_location='Newyork'
UNION OPERATOR:-
union operator is used to combine the result-set of two or more select statement
ex:-
select * from studentdetails1
union
select * from studentdetails2
UNION ALL:- (union all operators gives all the rows from both the tables including
the duplicates
EXCEPT OPERATOR:-
Expect operator combines two select statements and returns unique records from the
left query which are not party
of the right query,
ex;-
INTERSECT OPERATOR:-
Intersect operator helps to combine two select statements and returns the records
which are common to both the select statements.
ex;-
DROP VIEW:-
ALTER TABLE:- Alter table statement is used to add, delete, or modify column in a
table
syntax
ex;-
Alter table employee Add e_dob date;
Merge(target)As T
using (source)AS S
on(join condition)
When Matched
Then (update statement)
When Not Matched by Target
Then (insert statement)
When Not Matched by source
Then(delete statement);
Ex;-
Merge emptargettable As T
using empSourcetable As S
ON T.e_id=s.e_id
When matched
Then update set T.e_salary=S.e_salary,T.e_age=S.e_age
When Not Matched by Target by Target
Then insert (e_id,e_name,e_salary,e_age,e_gender,e_dept)
values(S.e_id,S.e_name,S.e_salary,S.e_age,S.e_age,S.e_gender,S.e_dept)
Then delete;
--> select * from emptargettable
syntax:-
create funcation funcation_name(@param1 datatype,@param2 datatype..)
Returns return_datatype
AS
BEGIN
----Function body
Return value
End
Ex;-
select dbo.add_five(100)
--Stored programs are the sub progrmas that are permanently stored in database.
--Stored programs are excuting will be fast when compared with individuaal sql
statements.
--STORED PROGRAM:
-- When you are creating a stored subprogram then during creation itself parsing,
-- execution plan generation and cost estimation will be done for every statement
-- in the stored program and exection plan with low cost for every statement will
-- be saved peanently in database . as execution plan readily available ,
-- execution will be fast and will increase performence.
-- Default arguments:
EXEC EMPLOYEE_DETAILS
SP_HELPTEXT 'EMPLOYEE_DETAILS'
sp without parameter;-
Ex:-
Exec employee_details
ex:-
exec employee_gender='Male'
select @c=@a+@b
select @c
--or
--Print @c
--FUNCTIONS;
--User defined functions are the stored subprograms that can be return a value with
return statement.
select dbo.addition(1,2)
--Calling function
select * from getdetails(5)
return
end
--Calling function
select * from getdetails1(2)
EXEC getdetails1
--Built in Functions
--They are
--1.Scalar functions
--2.Aggregte functions
--3.Ranking functions
-->Numeric functions
-->String functions
-->Date functions
--Theyare:
select ABS(99.90)--99.90
select RADIANS(30.00)---0.523598775598298790---convert degress to radians
select DEGREES(0.523598775598298790)---29.999999999999996000---convert radians to
degress
select SIN(RADIANS(30.00))---0.5
select COS(RADIANS(30.00))--0.866025403784439
select TAN(RADIANS(30.00))--0.577350269189626
select LOG(2)---0.693147180559945
select LOG10(2)---0.301029995663981
select EXP(3)---20.0855369231877----e raised to the power of n
select CEILING(56.354)---57 -----nearest integer >=n
select FLOOR(56.354)-----56 -----nearest integer <=n
select ROUND(75.467,2)---75.4600
select ROUND(75.437,2)---75.440
select SQUARE(25)---5
select POWER(5,2)--25
--STRING FUNCTIONS
--Date functions:
select DATENAME(mm,getdate())---April
select DATENAME(DW,getdate())---Wednesday
select DATEDIFF(dd,'2000-01-04',getdate())--6308
select DATEDIFF(ww,'2000-01-04',getdate())--901
select DATEDIFF(yy,'2000-01-04',getdate())--17
--Coversion Functions:
CONSTRAINST
QTY_ORDERED INT
)
CURSORS
--CURSOR: IS USED TO READ or EXECUTING THE DATA FROM THE TABLE ROW BY ROW.
-- 0--READ DATA
-- 1--THERE IS NO DATA
-- 2--DELETED
-- -1--COME OUT OF LOOP
--4>CLOSE CURSOR
--5>DEALLOCATE CURSOR
--.
IDENTITY:-
select * from #2
delete from #2
insert into #2(name)
values('venkat'),
('raja'),
('rani')
select * from #2
truncate table #2
select * from #2
INDEXES
--Table Scan:Scanning of each and every row in the table for the given codition.
--Types:
--Clustered index: when you create clustered index on a column then the rows in the
table will be physically stored in memory in
--sorted order in memory.
--Draback: Insert and update will be slow.
--overcome: by clustered index specify the FillFactor.
-- SYNTAX:
-- CREATE [CLUSTERED/NON-CLUSTERED]
-- INDEX <INDEX NAME> ON <TABLE NAME>
-- (<COLUMN NAME>)
--NON-CLUSTERED:
CREATE INDEX ID_IDX ON EMP(empno)
--CLUSTERED:
CREATE CLUSTERED INDEX ID_IDX ON EMP(empno)
PREDICATES
--Predicates
--.............
--Every operater that is used within the condtion in where class is called as
Predicates.
--Between ... And: This is used to verify whether the given value is available
within the given range of values.
--................
--Ex: Find the employees where salary is more than or equal to 2000 and less than
are equal to 3000
--In: This is used to check whether the given value is with in the given list of
values.
---
Like: This is used to search for a particular pattern within a given column.
----
We can use two wild card characters
%---Multiple characters
_ A single Character
Ex:
Find the employees whose name starts with the alphabet 'S'
Find the employees whose name ends with the alphabet 'S'
Find the employees whose name contain alphabet 'S' any where in their name
select * from emp where nmae like '%S%'
Find the employees whose name contain the alphabet 'L' as 2nd letter in their name
Find the employees whose name contain the alphabet in the range of 'A' to 'K' as
but one char in their name.
SUBQUERIES
--Sub Queries
--A query that was written within another query is called sub query.
select * from emp where dept=(select did from dept where dname='sales')
--Find the employees who are drawing highest salary dept wise.
select * from emp where sal in(select max(sal) from emp group by dept)
--Find the employees whose salary is more than the avg salary of sales dept.
select * from emp where sal>(select avg(sal) from emp where dept=
(select did from
Dept where dname='sales'))
--A sub query that refers to a column of main query within its where class.
--Find the employees whose salary is more than avg salary of same dept in which
employee working.
select * from emp e where sal>(select avg(sal) from emp s where s.dept=e.dept)
--Note: Co-Related sub query executed multiple times once for each row of the main
query.
select * from emp e where sal=(select max(sal) from emp s where s.dept=e.dept)
TRIGGERS
--Triggers:
--Triggers are execute automatically whenever action is occure.
--WE CAN ALTER ,DROP TRIGGERS.
--2Types
--......
--DML TRIGGERS:USED AT DATA BASE LEVEL
--DDL TRIGGERS:USED AT SERVSER LEVEL
--ACTION CLASSES:
--INSERT
--UPDATE
--DELETE
--AFTER TRIGGERS:
--CREATE TRIGGER NAME
-- ON EMP <ACTION>INSERT---> FUCTIONALITY
-- --MAINLY USED FOR AUDIT PURPOSE.
VIEWS
--Views
--A view is like window through which use can access the data from the table.
--Not: Restrict access to only specific rows in the table
--Simple view
--Complex view
--Simple view:
--Create the view on single table is called Simple view.
--Complex view:
--Create the view on morethan one table is called complex view.
--Once the view is created we can use it like a table and perform
--select ,
--insert ,
--update and
--delete same as on a table
--Note:By default column names in the view are same as column names in the view
--If you want to different names in the view we can write like below
--Schema binding: When the view is created with schema binding option ,then
--it will not be possible to alter the view until the view is deleted.
--The above command is not execute because the view is created with schemabinding
--We can't change the main table schema untill you drop the schemabinding
--Noote: * is not allowed in view with schemabinding
--IMP: Can't create index on view because the view is not a schemabinding