Friday, October 11, 2013

VIEWS IN SQL SERVER

Dept Table




Views:

A view is like a window through which user can access a table.
A view has the following three main purposes
1 Restrict the user from performing insert, update and delete only on specific rows of the table
2 Restrict the user from accessing only specific rows of the table.
3 Simplify the complex queries like set operators joins and sub queries when we have to repeatedly execute that statement.

Creating a View:

To create a view use the create view command that has the following syntax:

Create view <view name> ((columnist)) [with encryption][,][schema binding]] as <select statement>
[with check option]

Create a view to restrict the user to access only the details of employee working in deptno=20

create view emp20 as select * from emp where deptno=20


 Important:
Once the view is created it can be used like a table and you can perform select, insert, update, and delete on the view same as on the table.
But a view does not contain any data physically and whatever you select any data from a view, it will execute the select statement specify while creating a view gets data from the table and displays it to you.

When you perform insert, update, delete on a view than it will perform that insert, update & delete on the table on which the view was created. Hence the view is called as a logical object and not the physical object.

Views will not store data and will not use memory. Views contains only the structure or columns by using those views will display values from the tables. View will not contain data of its own the data which it displays will be from the table.
 The following examples retrieves data from the view emp20
select * from emp20

Example:
The following example inserts a row into the view emp20

insert emp20 values(1001,'A','clerk',7902,'10/21/1980',2000,NULL,30)

Check option: The above statement will successfully insert a row even if it is not satisfying the condition specified in select statement of the view.

Emp20 that is dept no 20 because the condition is specified in select statement of the view will be checked only during the select and not during insert, update, delete.

To check the condition specify in the select statement of the view during insert, update and delete also you must specify the “check option” while creating the view.

The following example alter the view emp20 to include check option
alter view emp20 as
select * from emp where DEPTNO=20
with check option


Note:

Using grant and revoke we can restrict user operations.

But by using view we can restrict data (particular columns)

Now we will execute the same insert query again and check what happens
insert emp20 values(1005,'A','clerk',7902,'10/21/1980',2000,NULL,30)

Error: The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.
The statement has been terminated.

Types of Views:

Simple view
Complex view

Simple view:
-        These Views as based upon a single table, which access the data from the single table.
-        They contain a Sub Query which retrieves the data from one base table.

Syntax
Create view <viewname>
(<with option>)
As
Select statement
[where condition]

Example:

createview v1 as
selectempno,ename, sal from emp

When the above view is created select statement is stored in dB, that why view is also called as stored query.

CREATE VIEW SIMPLE_VIEW
AS SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP
Once the view is created we can access the data from it as if it was a table as following:
    SELECT * FROM SIMPLE_VIEW
SELECT EMPNO, ENAME, SAL, SAL*12 AS [ANNUAL SAL], DEPTNO FROM SIMPLE_VIEW


-We can also perform DML operations on the Simple Views which will effect on the base table.

INSERTINTO SIMPLE_VIEWVALUES(1234, 'SANTOSH', 4300, 20)
DELETEFROM SIMPLE_VIEWWHERE DEPTNO=20
UPDATEEMP SET SAL=5600 WHERE EMPNO=1001

All the columns that are referenced in the view can be modified through the view.
We cannot perform insert operations on the view if he view does not contain all the not null columns of the base table.

Example
createview v4
as
selectempno, sal,deptno from emp
wheredeptno=10
withcheck option


insertinto v4 values(100,900,10)


insert into v4 values(100,900,30)

 

Invalid because the view is created with check option

Complex Views:

-        If the View is based on multiple tables it is a complex view
-        If it is based on a single table with any of the following:
o  Group By Clause
o  Having Clause
o  Group Functions
o  Distinct Function
o  Function Calls

CREATEVIEW EMP_GRADE
    AS
    SELECT E.EMPNO, E.ENAME, E.SAL, S.GRADE, S.LOSAL, S.HISAL
    FROM EMPE INNER JOIN SALGRADE S
    ON E.SAL BETWEEN S.LOSAL AND S.HISAL

CREATEVIEW EMP_DEPT
AS
SELECTE.EMPNO, E.ENAME, E.SAL, D.DEPTNO, D.DNAME, D.LOC
FROMEMP E INNER JOIN DEPT D
ONE.DEPTNO=D.DEPTNO




       CREATE VIEW EMP_GRADE1
    AS
    SELECT E.EMPNO, E.ENAME, E.SAL, S.GRADE, S.LOSAL, S.HISAL
    FROM EMPE INNER JOIN SALGRADE S
    ON E.SAL BETWEEN S.LOSAL AND S.HISAL



CREATEVIEW EMP_DESIGNATIONS
AS
SELECTJOB FROM EMP WHERE DEPTNO=10
UNION
SELECTJOB FROM EMP WHERE DEPTNO=20
UNION
SELECTJOB FROM EMP WHERE DEPTNO=30






CREATEVIEW EMP_MAX_SAL
AS
SELECTDEPTNO, MAX(SAL) AS [HIGH SAL] FROM EMP GROUP BY DEPTNO

Create a view that provides access to details of employees along with manager Name of the employee, grade of the employee based on salary ,and deptname and location in which employee is working.

createview empdetails
as
selecte.EMPNO,e.ENAME,e.JOB,e.MGR,m.ENAME as manager,e.SAL ,losal,hisal,grade,e.DEPTNO,d.DNAME,d.LOC
 from emp e inner join emp m on e.MGR=m.EMPNO inner join salgrade on e.SAL between losal and hisal inner join dept d on e.DEPTNO =d.DEPTNO






Note:

When a view is complex view then insert, update, delete are not allowed on that view but when the view is created on multiple tables, than if you write insert, update statement that effect only one table then they are not allowed.

Query fired on view takes more time than query fired on base table. Views degrades performance.

We can also classify views as Updateable Views and Non Updateable Views:
-        A View, which allows manipulations on it, is known as Updateable View.
-        A View, which will not allow manipulations on it, is known as Non Updateable View.

If we want to perform manipulations on the Complex Views we have the following restrictions:
Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
  • The columns being modified cannot be affected by GROUP BY, HAVING, or DISTINCT clauses.
With Check Option:
-        Forces all data modification statements executed against the view to follow the criteria set within select statement.
-        When a row is modified through a view, the WITH CHECK OPTION makes sure the data remains visible through the view after the modification is committed.
-         
-        CREATE VIEW SALES_EMP
-        AS
-        SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE DEPTNO=20
-         
-        INSERT INTO SALES_EMP VALUES(1050, ‘RAJU’, 3500, 30)
-         
-        -The above insert statement executes even if it does not satisfy the condition in the View, if this has to be restricted the view has to be created by using With Check Option clause.

ALTER VIEW SALES_EMP
AS
SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE DEPTNO=20
WITH CHECK OPTION

View Attributes:
Encryption:
If the view is created with encryption, then view definition will be hidden in information schema views table.
Schemabinding:
-        When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition.
-        We need to specify the column names individual in the select statement, cannot use “*” in the select statement.
-        All referenced objects must be in the same database.
-        Tables that participate in a view created with the SCHEMABINDING clause cannot be dropped unless that view is dropped or changed so that it no longer has schema binding.

-        CREATE VIEW EMP_BIND
-        WITH SCHEMABINDING
-        AS
-        SELECT EMNO, ENAME, JOB, MGR FROM DBO.EMP
-         
After the view is created EMP table cannot be dropped.

When a view is created with schema binding option than it is not possible to alter the columns that are selected into the view within the table until the views exists.

While creating a view with schema binding option, within the select statement of the view you must specify the table name in the format “schemaname.tablename” where schema name is same as username.

The following examples creates a view that provides access to empno, ename, job, Sal and comm by specifying schema binding.



Create view empview
With schema binding as
Select empno, ename, job, Sal, comm from dbo.emp

Now, we will try to alter.

Alter table EMP alter column sal small money
Error


Getting List of Views:

To get list of view available in the dB, you can use any of the following two options
It gets the definition of the view, table name
Select* from INFORMATION_SCHEMA.VIEWS

Select* from sys.views

(View date, created data, modified data)



To get list of the tables on which view was created use the following select statement.


Getting definition of a view:

To get the definition of a view, use the stored procedure sp_helptext that has the following syntax:

sp_helptext ‘view name’

Example
sp_helptext'v4'

Note:

When you don’t want to display the definition of your view to anyone then specify encryption option while creating the view.



To delete the view
To delete the view use the drop view command that has the following syntax

Drop view <view name>


The following examples deletes the view v4
Dropview v4

Sunday, October 6, 2013

DATE FUNCTIONS IN SQL SERVER

DATE FUNCTIONS

getdate(): returns current system date & time

Eg: select getdate()

day(): returns day part from the date

Eg: select day(getdate()

select day('10/24/78')

Month(date)
returns month part from the date

Eg: 
select month(getdate())
select month('10/24/78')

Year():
Returns year part of the date.

Datepart
Abbreviations
year
yy, yyyy
quarter
qq, q
month
mm, m
dayofyear
dy, y
day
dd, d
week
wk, ww
weekday
dw
hour
hh
minute
mi, n
second
ss, s
millisecond
ms



Eg:
select year('10/24/78')
select year(getdate())

Display employee records joined in leap year
select * from emp where year(hiredate)%4=0


Display employee records between January and April.
select * from emp where month(hiredate) between 1 and 4

Display employee records who are joined in first 15 days of January month in year 1981
select * from emp where day(hiredate) between 1 and 15 and month(hiredate)=1 and year(hiredate)=1981

DatePart(part,date)
It is used to extract specified part from the given date.
select datepart(dd,getdate())
o/p-7    (Day of the month)
     
select datepart(mm,getdate())
o/p-10    (month of the year)

select datepart(yy,getdate())
o/p-2013   (year of the date)

select datepart(dw,getdate())
o/p -2    (day of the weak)

select datepart(ww,getdate())
o/p-41   (weak of the year)

select datepart(qq,getdate())
o/p-4   (quarter of the year)

select datepart(hh,getdate())
o/p-22   (hours of the date)

select datepart(ss,getdate())
o/p-19   (seconds of the date)
select datepart(mi,getdate())
O/p-52   (minutes of the date)

DateName()
This function is same as date part expect that while extracting month and day of the week it will return month name and weak name instead of Name.
given date.
select datename(dd,getdate())
o/p-7    (Day of the month)
     
select datename (mm,getdate())
o/p-october    (month of the year)

select datename (yy,getdate())
o/p-2013   (year of the date)

select datename (dw,getdate())
o/p -Monday    (day of the weak)

select datename (ww,getdate())
o/p-41   (weak of the year)

select datename (qq,getdate())
o/p-4   (quarter of the year)

select datename (hh,getdate())
o/p-22   (hours of the date)

select datename (ss,getdate())
o/p-19   (seconds of the date)
select datename (mi,getdate())
O/p-52   (minutes of the date)

Display smith joined on Sunday as outpu
select ename + ' joined on ' +datename(dw,hiredate) from emp

   
DateAdd()
It is used to add or subtract n no of specified parts to the given date and return a date.
Add 6 days to the getdate
select DATEADD(dd,6,getdate())
output:2013-10-18 09:52:49.720

Add 6 months to the getdate
select DATEADD(mm,6,getdate())
output: 2014-04-12 09:53:42.340

Subtract 6 days to the getdate.
select DATEADD(dd,-6,getdate())
output: 2013-10-06 09:54:41.340

DateDifference()

It is used to get the difference between the two different dates in specified format.

Select datediff(dd,'03/01/2012',getdate())
Output: 590

Select datediff(mm,'03/01/2012',getdate())
Output: 19

Select datediff(ww,'03/01/2012',getdate())
Output:84


getUTCDate()

Returns the date time value representing the current UTC time(Coordinated universal Time or Greenwich Mean Time).
Select GETUTCDATE()

Find the employees who are joined in the company in Dec Month of every year.
select * from emp where datepart(mm,hiredate)=12

or if you want only 2013 year
than write the query as
select * from emp where datepart(mm,hiredate)=12 and datepart(yy,hiredate)=2013

Find the programmer whose DOB is on system date.

select * from PROGRAMMER where datepart(dd,dob)=datepart(dd,getdate()) and datepart(mm,dob)=datepart(mm,getdate())

PREDICATES OR SPECIAL OPERATORS

PREDICATES OR SPECIAL OPERATORS


DEPT TABLE


EMP TABLE



Every operator that is used within the conditions in " where clause" is called as predicates.

Tsql provides special predicated to simplify the conditions in where clause which are collectively called as “predicates”

a.          Between
b.          Not between
c.          In
d.          Not in
e.          Is null
f.          Is not null
g.          Like
h.          Not like



Between:

Is used to verify wheather or not the given value is within the specified range.

Between operator always works with lower limit & upper limit but not upper limit & lower limit

Find the employee whose salary is in the range of 2000 and 4000

select * from emp where sal between 2000 and 4000


To display the employees who joined in the company in the year 1982
select * from emp where hiredate between '1/1/1982' and '12/31/1982'

Find the employees whose salary is not in the range of 2000 and 4000
select * from emp where sal not between 2000 and 4000



IN OPERATOR

This operator is used to verify whether or not the given value is within a specified list of values

Examples

Find the employees whose salary is either 800 or 950 or 1600
Select * from emp where sal in (800,950,1600)

Find the employees whose job is either clerk or manager
Select * from emp where job not in('clerk','manager')

Display employee list who are not working for 10 or 20 the department.
Select * from emp where deptno not in(10,20)


Find the employees whose salary is not either 800 or 950 or 1600
Select * from emp where sal not in(800,950,1600)


Display employee records earning between 2000 and 5000 and earning multiple of 50 and working as clerk or manager & not deptno in 10 and 20
select * from emp where sal between 2000 and 5000
and sal%50=0
and job in ('clerk','manager')
and deptno  not in(10,20)

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



LIKE

It is used to search for a particular pattern within a column
While working with like predicates you have to use two wild card characters

1 %--> it is used for representing multiple characters.
2 _underscore: it is used for representing single character.


Find the employees whose name starts with alphabets s

select * from emp where ename like 's%'


Name ends with s

select * from emp where ename like '%s'

Name starts with s and ends with s
select * from emp where ename like 's%s'

Find the employees whose name contains alphabet a
select * from emp where ename like '%a%'

Find the employees whose name contains alphabet a minimum twice in the name
select * from emp where ename like '%a%a%'

Find the employees whose name contains alphabet L as second letter in the name

select * from emp where ename like '_l%'

Display employee records name starts between a and p
select * from emp where ename like'[a-p]%'

where name doesnot start with a and p
select * from emp where ename not like'[a-p]%'
select * from emp where ename like '[^a-p]%'


Display employee records name starts with a or b or s or t
select * from emp where ename like '[abst]%'

Find the employees whose name contains the alphabet I or R OR N as 3 letter in the name

select * from emp where ename like '__[i,r,n]%'


Find the employees whose name contains any alphabet in the range of a to k as 2 letter in the name
select * from emp where ename like '_[a-k]%'

Find the employees whose name does not contain alphabet A as second letter in the name.
select * from emp where ename like '_[^a]%'

Find the employees whose name does not start with alphabet s
select * from emp where ename not like 'S%'

Find the employee whose name contain alphabet L as second letter in the name but not alphabet e as last but one character in the name
select * from emp where ename like '_l%[^e]_'

Isnull
Is used to search for null in a column

Find the employees who are not drawing commissions
select * from emp where COMM is null


Find the employee who have no manager
select * from emp where mgr is null


Find the employees who  are drawing commission
select * from emp where comm is not  null






Isnull function in SQL SERVER

Isnull function


Any arthimetic operation with null results in null. Hence whenever you have to perform arithmetic operations on a column containing null use the function “ISNull”

DEPT TABLE



EMP TABLE





Display empno,ename, sal, comm along with total and annual salary
select empno,ename,sal,comm ,sal+isnull(comm,0),(sal+isnull(comm,0))*12 from emp


OR BY USING COL ALIAS

select empno,ename,sal,comm ,sal+isnull(comm,0) AS "TOTAL SALARY",(sal+isnull(comm,0))*12 AS "ANNUAL SALARY"from emp



Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...