You are on page 1of 11

use db2

--display all
select ename from emp;

--display jos
select distinct job from emp;

--display job count


select count(job) from emp;

--select job count and not repeat


select count(distinct (job)) from emp;

--display only records whose count is more than 3


select job,count(job) as 'Number of employees' from emp
group by job
having count(job)=4
order by 'Number of employees' desc;

--display total salary of all employees--


select sal+comm as totalsalary from emp ;

--select date
select getdate()+5;

--logical operators all values


select * from emp where job='clerk' and sal>1000;

--output as same for two below queries


select * from emp where job in('clerk','analyst','student');
select * from emp where job='clerk' or job='analyst' or job='analyst';

--display all those wher there is null value in commission


select * from emp where comm is null;
select * from emp where comm is not null;

--both queries has same output


select * from emp where sal between 1000 and 1600;
select * from emp where sal>=1000 and sal<=1600;

--like operator
select * from emp where ename like '_A%';
select * from emp where ename like '%s';
select * from emp where ename like '____';

--length operator
select * from emp where len(ename)=4;

--display all the employees in ascending order of department number and descending
order of jobs
select * from emp
order by deptno asc, job desc;

-- display all those employees join before 1981


select * from emp where hiredate<'1981';

--claculate the annual salary for all the employees


select empno,ename,sal*12 as annualsalary from emp ;
--display all the details of the employees who are working under jones
select * from emp
where mgr=(select empno from emp where ename='jones');

-- list the employees who are joined in the month of august


select * from emp where month(hiredate)='12' ;

select * from emp where hiredate='1980-12-17 00:00:00' ;

--display the structure of the table


sp_help emp;

--to add primary key constraint


alter table deptno add constraint pk_deptno primary key(deptno);

--to modify column to not null


alter table deptno add constraint deptno primary key(deptno);

--delete all records


delete from deptno;
alter table deptno add constraint deptno primary key(deptno);
insert into deptno values(1);

-to give check constraint


alter table altertest
add age int check(age between 20 and 40)

--displaying constraint
alter table deptno nocheck constraint pk_deptno_age_619B8048

--enabling constraint
alter table deptno
check constraint ck_altertest_age_619B8048

--default constraint adding column city with default value 'hyderabad'


alter table altertest
add city varchar(10)
default 'hyderabad'

--adding col DOJ having deafult values as today's date


alter table altertest
add DOJ datetime default getdate() with values

--dropping the constraint default on DOJ

sp_help altertest
alter table altertest
drop constraint df_alter_doj

--adding a foreign key constraint on a_id


alter table refertable
add constraint fk_aid

select len('k sai karthik');


select ltrim(' sree sai');
select rtrim('hai baba ');
select len(ltrim(' sree sai'));
select left('sai baba',2);
select right('sai baba',4);
select substring('sreebhandhavi',4,5);
select replace('sreebhandhavi','eebhand','saibaba');
select reverse('loveme');
select charindex('r','sree');
select patindex('%ee%','sree');
select lower('SAI karthik');
select upper('sai KARTHIK');
select concat('kulayan','alagu','thirunavukkarasu','saikarthik');
select cast(email as char);

--coalesce contains any number of argumnets but it will returns non nullable
values
select COALESCE ("expression 1", "expressions 2", ...);

--numeric functions
select round(12345.53556,2);
select isnumeric(5);
select isnumeric('k');
select abs(-10);
select CEILING(14.3);
select FLOOR(234.2);
select SQUARE(16);
select sqrt(25);
select rand();

--date functions
select getdate();
select day('11/14/1989'); --fromat (mm/dd/yyy)
select month('11/14/1989');
select year('11/14/1989');
select datename(month,getdate());
select datepart(wk,getdate());
select convert(varchar (10),getdate(),101) as [dd-mm-yyyy];--101 is standard for us
select datediff(day,'2018-01-01','2018-10-05');
select datediff(wk,'2018-01-01','2018-10-10');
select datediff(month,'2018-01-01','2018-05-10');

--display experience of employees in emp table

select *, datediff(year,hiredate,getdate()) as EXPERINCE from emp;

--calculate your age in years months and days


select datediff(year,'11-07-1996',getdate()) as Year
, datediff(month,'11-07-1996',getdate()) as Month
, datediff(day,'11-07-1996',getdate()) as Day ;

--logged user in data base shown


sp_who @@SPID

--it displays what are the databases you are created


sp_databases

select * from emp;

--error ambuguity jpin statement


select empno,ename,sal,deptno,dname,locfrom emp,deptwhere emp.deptno=dept.deptno

--shows correct joins statement


select e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc
from emp e,dept d
where e.deptno=d.deptno

--ansi syntax
select e.empno,e.ename,e.sal,d.deptno,d.dname from emp e join dept d on
e.deptno=d.deptno

--explicit inner join use inner join keyword


select e.empno,e.ename,e.sal,d.deptno,d.dname
from dbo.emp as e
inner join dbo.dept as d
on e.deptno=d.deptno
where d.deptno=30

--implicit inner join


select *
from emp , dept
where deptno=30

--natural inner join if all the column name of the both tables has same columns
select * from emp natural join dept

--cross join in ansi way


select * from emp cross join dept

--normal way of writing cross join


select * from emp,dept

--c sharp corner .com


--outer join
create table emp1(
empid int
)

--self join
select e1.empno,e1.ename as Employee,e2.ename as Manager from emp e1,emp e2
where e1.empno=e2.mgr

7593
T-sql(sql server):
================
transaction sql

procedure:
==========
1.no return value
2.create even errors

functions:
==========
1.alway return value
2.does not exceed if errors

1.severity can be from 0-25


2.user defined errors is 0-18
3.less tah 0 is zero
4.more than 25 is 25
5.admin defined errors is 0-25

sp_addmessage;
===============
stores user defined error messages in sql server catalog 'sys.messages'.

functions in sql server:


=========================
1.scalar
2.inline
3.multistatement table-valued functions

scalar function options


=======================
1.encryption
2.schema binding

Inline table-values functions:


==============================

-used to return a table as an output


-the return value is given through a single statement statement
-It doesn't have associate return variable.

multistatement table-valued function:


=====================================
It is similar to inline but contain multiple statemen ts. The structure of the
table can be defined by us.
views:it is a virtual table.the table inside in this is called as base table
=====
1.create view with one table it is called as simple view
2.create view with more than one table it is called as complex table

3 types of views
1.normal or standard view.
2.indexed or permanent
3.partition view

advantages of view:
==================
1.query simplicity
2.structural simplicity

disadvantage of views:
=====================
1.time consuming
2.updation problem incase of complex use

indexes:
=========
indexes are used to improve the performance of the database they can be created on
single or multiple columns
a table can have only one clustered index but multiple non clustured indexes.we cal
crete unique indexes for both clustered
and non clustered indexes

3 types of indexes
1.clustered index
2.Non clustered index
3.Filtered index

clustered index:
=================
1.have intermediate level
2.clustered index determined the logical order in whic table data is stored .the
leaf node contains the actual database o f the table .it is created an clustered
index key. the clustered index key must be unique
clustered index:
=================
1.not have intermediate level
2.non clustered index they are stored seperately from the table outside of the
datbasethey can be either
unique or nonunique.the leaf node has data pages which are not similar to the
pages

partitions:
===========
sql server 2017 supports upto 15000 partitions outside of db they can be either
unique or non unique the leaf node has datapages which are
not similar to the table.

advantages:
==========
1.maintance
2.efficient access to data
3.data integrity maintained

steps to create partition table:


=================================
create a partition function
create a partition scheme
create a partition table.

cursor in sql server:


======================
1.Is private sql area in memory
2.To process set of records based on condition

eg:uodate employee details based on job type

cursor operations:
==================
declare, open, fetch, and deallocate

types of cursor:
===============
1.static cursor--read only and rollable ie., move forward and move backward
2.dynamic cursor--
3.forward only cursor
3.1 forward_only_static_cursor
3.2 fast forward cursor.
4.keyset driven cursor

disdvantages: performance
============
syntax:
=======
1.@@fetch status
2.@@cursor_rows
3.@@cursor_status

further references sitename is msdn.


further reference site name is dotnet tricks.com

create procedure addition (@x int ,@y int)


as
declare @res int
begin
set @res =@x+@y
print @res
end
exec addition 10,20

--procedure without parameter mode


create procedure p33(@x int,@y int,@z int output)
as
begin
set @z=@x+@y
print @z --(optional)
end

declare @res int


exec p33 10,20,@res output
print @res

--procedures with (default values)


create procedure p5(@dept int=10,@job varchar(20))
as
begin
select ename from emp where deptno=@deptno and job =@job
end

exec p5 @deptno=30,@job='clerk'
exec p5 @deptno=default,@job='manager'
exec p5 @job='clerk'
select * from emp

--error handling in stored procedures -- to override default internal errors use


raise errors
create procedure p3333(@x int,@y int)
as
declare @z int
begin
begin try
set @z=@x/@y
print @z
end try
begin catch
print error_message()
end catch
end
exec p3333 20,0--select this only then execute thne error message is "Divide by
zero error encountered."

--error handling in stored procedures (raising error)


=====================================================
create procedure pu(@x int,@y int)
as
declare @z int
begin try
if(@y=0)
raiserror ('cannot be zero',1,1)
else
set @z=@x/@y
end try
begin catch
print error message()
end catch
end
--error handling in stored procedure (storing new user defined message)

create procedure pu1(@x int,@y int)


as
declare @z int
begin
begin try
if(@y=0)
raiserror(5000,1,1)
else
set @z=@x/@y
end try
begin catch
print error_message()
end catch
end

exec sp_addmessage 50001,3,'cannot divide by zero'


exec pu1 20,0

---functions in sql server

create function area(@length float,@width float) returns float


as
begin
return @length*@width
end

select dbo.area(10.0,20.0)

sp_helptext area --see the function written actually

--encryption

create function area2(@length float,@width float) returns float with encryption


as
begin
return @length*@width
end

select dbo.area2(10.0,20.0)
sp_helptext area2

create function exam() returns table with schemabinding


as
return (select EMPNO,ename from dbo.emp)
select * from dbo.exam()

create function gd2(@deptno int) returns table


as
return (select e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc from dbo.emp e inner
join dbo.dept d
on e.deptno=d.deptno where e.deptno=@deptno)
select * from gd2(10)

create function f(@n int)


returns @factorial table (number int, factorial int)
as begin
declare @i int, @f int
select @i=1,@f=1
while @i<=@n begin
set @f=@i*@f insert into @factorial values(@i,@f)
set @i=@i+1
end
return
end
select * from dbo.f(5)

--views
create view viewname(alias name1,name2)--syntax starts
with encryption
with schemebinding
as
select statement[with check option]--syntax

--create view wothout check option


create view v1
as
select * from emp
where deptno =10

select * from v1
insert into v1 values (8,'karthik','clerk',7992,1992-11-17,900,null,20)--will
insert into dept view,..though here it allows insertion
select * from v1
select * from emp

--create view with check option

alter view v1
as select * from emp where deptno=20 with check option --now u cant insert values
with depid other than 1
select * from v1
insert into v1 values (8,'karthik','clerk',7992,1992-11-17,900,null,20)--will
insert into dept view,..though here it allows insertion

--select text to show the view definition


select text from syscomments where id= OBJECT_ID('v1')

--encryption option
alter view v1 with encryption as select * from emp where deptno=20 with check
option
select text from syscomments where id= OBJECT_ID('v1')

create view v2
as
select * from emp,dept where emp.empno=dept.deptno
select * from v2
insert into v2 values(3,'ggg',3,'111')--cant be update

use master
create database dbp2
on primary
(
name='pfg',
filename='c:\pg1.mdf',
size=10MB,
maxsize=100MB,
filegrowth=10MB
),
filegroup fg1(
name='fg_1',
filename='c:\fg1.ndf',
size=10MB,
maxsize=100MB,
filegrowth=10MB
),
filegroup fg2(
name='fg_2',
filename='c:\fg2.ndf',
size=10MB,
maxsize=100MB,
filegrowth=10MB
) // error is user access is denied

You might also like