SQL Class Notes
SQL Class Notes
How to connect SSMS (SQL server management studio) once we install the SQL
server we will get ICON in the all programs
ALL PROGRAMS
MS SQL SERVER
Then it will open a window provide the server name as or Local, (local host)
CREATE
ALTER
DROP
TRUNCATE
DML (DATA MANIPULATION LANGUAGE)
INSERT
UPDATE
DELETE
TCL (TRANSACTION CONTROL LANGUAGE)
ROLL BACK
COMMIT
CREATION OF TABLE
Syntax: CREATE TABLE <TABLE NAME>
(
<COLUMN NAME><DATATYPE>,
<COLUMN NAME><DATATYPE>,
<COLUMN NAME><DATATYPE>
)
DROPING DATABASE:
ALTER: WILL CHANGE THE EXISTING STRUCTURE OF THE TABLE AVAILABLE IN THE
DATABSE.
Syntax: Alter table <table name > ADD <column name ><data type>
Syntax: Alter table <table name > DROP <column name >
Syntax: Alter table <table name > alter <column name ><data types>
INSERT: Insert will insert the data into corresponding tables. For the
specified columns
DELETE: It will delete the entire data or specific data from specified
table.
In this use where condition also
Delete is a DML command
We can rollback delete
Begin transaction
Update emp set empname=’SURESH’ where empid=345
Rollback
******** COPY THE STRUCTURE ONLY TO THE NEW TABLE NOT THE DATA********
Syntax INSERT INTO <EXISTING TABLE NAME> SELECT * FROM <OLD TABLE>
IN: If we are providing more than one value in the where condition
for a specified column then we have to use in operator.
Example select * from emp Where empsal between 10000 and 45000
Example select * from emp
Where substring (empname(1,1)) between ‘A’ and ‘K’
NOT IN: Not in will filter the data which we provided in the ‘not in’
clause and remaining rows will be displayed.
CONSTRAINTS
NOT NULL: Not null constraint will restrict the user, while inserting the
null values into the specified columns.
In the above example not null value applied on the empid column
whenever user inserts into the data it will restrict and throw
the error.
UNIQUE: Unique constraint will restrict the user to insert the duplicates
to the specified columns.
CHECK: Check constraint will check the values which are provided by the
user and validate the condition, if check constraint satisfies
then it will insert the data otherwise, it will throw an error.
PRIMARY KEY: Primary key is a key which will restrict the user to allow
null values as well as duplicates.
First we have to make the required columns as ‘not null’ and then
run the alter command
Foreign key: foreign key is a reference key, which will insert the data in
the’ fact customer’ table after checking it in the parent
table.
1 LUX 30 125 1 35
132 2 42
2 SANTOOR 20
140 7 37
3 LIRIL 15
142 4 32
4 CINTHOL 40
145 6 46
Parent table as DIM product table in this PID column as having primary key
Child table
WHERE: Where clause is used to filter the data in the tables for a
specified column or multiple columns by using the given
condition.
GROUP BY: Group by will group the data based on the provided column in the
group by clause to do the aggregate operations in the select
list.
HAVING: Having is used to filer the aggregated data after applying the
group by clause in a table.
CAST: Cast is used to convert the data type logically while selecting
the data from the table for example
TRY_CAST: Try_ cast is cast but only the difference is ‘cast’ will fail
entire column, if we have unwanted values in it. But ‘TRYCAST’
will not fail entire column and it will display null values in
place of unwanted values.
CONVERT: Convert is used to convert the data type from one to another
logically while selecting data from table
INNER JOIN: Inner join will give you the making records from both the
tables based on the key column.
Example: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A JOIN EMPADDRESS B
ON A.EID=B.EID
INNER LOOP JOIN: Inner loop join work as same as ‘inner join’, but we will
use this loop join in following synario
EXAMPLE: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A inner LOOP JOIN EMPADDRESS B
ON A.EID=B.EID
LEFT OUTER JOIN (LEFT JOIN): This join will give all the records from the
left table and matching records from the right table.
Example: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A LEFT JOIN EMPADDRESS B
ON A.EID=B.EID
Output:
RIGHT OUTER JOIN (RIGHT JOIN): This join will give all records from the
right table and matching records from the left table.
Example: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A RIGHT JOIN EMPADDRESS B
ON A.EID=B.EID
Output:
FULL OUTER JOIN (FULL JOIN): This join will give all the records from left
table and all the records from right table (complete
records from both the tables)
Example: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A full JOIN EMPADDRESS B
ON A.EID=B.EID
Output:
CROSS JOIN: Cross join will give all the possible combinations
from the both tables
Example: SELECT
A.EID,
A.ENAME,
A.ESALARY,
B.EMPADD1,
B.EMPADD2
FROM
EMPDETAILS A CROSS JOIN EMPADDRESS B
OUTPUT:
This cross join will give results like example if we
have ‘m’ records in left table and ‘n’ records in the
right table then we will get ‘m*n’ records .
SYSTEM FUNCTIONS
MATHEMATICAL FUNCTIONS
AGGREGATE FUNCTIONS
STRING FUNCTIONS
DATE FUNCTIONS
STRING FUNCTIONS:
LOWER: It will convert the given string or column into LOWER case.
UPPER: It will convert the given string or column into UPPER case
RTRIM: It will trim the unwanted space from RIGHT SIDE of the given
string or column.
REVERSE: It will reverse the given string or column value specified in the
reverse function.
REPLACE: It will replace the characters from the given string or column.
EXAMPLE PROGRAM
Chanbasha
Samba
Parshi
Karthik
Raju
CHAR INDEX: Char index will find the specified character position which
is available in the given string.
It will return the position of the specified character for the
first occurrence in the given string.
REPLICATE: Replicate will display the same values for this specified
no of times the given string or column.
EXAMPLE PROGRAMS
DATE FUNCTIONS
We have following date functions available in the SQL
server to perform the date operations.
GETDATE()
YEAR()
MONTH()
DAY()
DATEPART
DATEADD
DATENAME
DATEDIFF
GETDATE (): Getdate will give present date & time from the server
YEAR (): This function will extract the year from the given date.
MONTH (); This function will extract the MONTH from the given date.
DAY (): This function will extract the DAY from the given date.
YY - YEAR
MM - MONTH
DD - DAY
HH - HOUR
MI - MINUTES
SS - SECONDS
MS - MILLISECONDS
DW - DAY WEEK
WW - WEEK NUMBER
DATEADD: Dateadd function will add the mentioned part of the date to
this specified date value.
DATENAME: It will display the month name or date name from the given
date value.
SET OPERATORS
UNIONALL UNION INTERSECT EXCEPT
UNION ALL: Union all will combine two data inputs and display as
single result set.
For example if we have 5 records in the first table and 10
records in the second table then we will get 10+5 records
NOTE: THE COLUMNS WHICH WE MENTIONED IN THE SELECT LIST SHOULD BE SAME WITH
OTHER TABLE, IT WILL NOT ALLOW THE DIFFERENT NO OF COLUMNS FOR BOTH TABLES
UNION: UNION will combine two data inputs and display as single results
set.
Except: except will give all the records from the left table which are
not available in the right table
EXCEPT
SELECT * FROM FIRST_TABLE
EXCEPT ID NAME
SELECT * FROM SECOND_TABLE 1 SAMBA
INTERSECT: It will display the matching records from both the tables
INTERSECT INNERJOIN
It will compare the null value It will not compare the null value in
and display to the results set the tables.
IS NULL, ISNULL ()
ISNULL (): ISNULL () operator will replace the user value in place of
null.
Syntax SELECT
CASE
<CONDITION>
ELSE
<CONDITION>
END
Example SELECT *,
CASE
WHEN MATHS > 35 AND PHYSICS > 35 AND CHEMISTRY > 35 THEN 'PASS'
ELSE 'FAIL'
END as STATUS
FROM RANKING
RANKING FUNCTIONS
ROW_NUMBER ()
RANK ()
DENSE_RANK ()
For example table
STUID STUNAME MATHS PHYSICS CHEMISTRY TOTAL
1 A 75 46 93 214
2 B 82 92 37 211
3 C 93 38 27 158
4 D 28 67 91 186
5 E 63 89 28 180
6 F 79 83 92 254
7 G 89 92 86 267
8 H 36 76 74 186
RANK (): Rank will generate the values based on the given column in the
order by clause as same as Roll NO. But rank will skip the
intermediate values on the given column.
OR
WITH CTE
AS
(
SELECT ROW_NUMBER ()
OVER (PARTITION BY EMPID, EMPNAME, EMPSAL ORDER BY EMPSAL DESC) AS
ROLL_NO,* FROM EMPSALDETAILS
WITH CTE
AS
(
SELECT ROW_NUMBER () OVER (PARTITION BY EMPDEPT ORDER BY EMPSAL DESC) AS
ROLL_NO,* FROM EMPSALDETAILS
MIN_SAL EMPDEPT
35000 SE
38000 SSE
45000 TL
2) 6TH MAX SALARY FROM EMPSALDETAILS
WITH CTE
AS
(
SELECT ROW_NUMBER () OVER (ORDER BY EMPSAL DESC) AS ROLL_NO,* FROM
EMPSALDETAILS
)
WITH CTE
AS
(
SELECT ROW_NUMBER () OVER (ORDER BY EMPSAL ASC) AS ROLL_NO,* FROM
EMPSALDETAILS
)
WITH CTE
AS
(
SELECT ROW_NUMBER () OVER (PARTITION BY EMPDEPT ORDER BY EMPSAL DESC) AS
ROLL_NO,* FROM EMPSALDETAILS
)
Go to table
Select design
Select column below properties
Computed column specifications expand it.
Select the formula and provide the required formula in it.
VIEWS
o SIMPLE VIEW
o COMPLEX VIEW
o VIEW WITH SCHEMABINDING
o VIEW WITH ENCRYPTION
o INDEXED VIEW
It is a select statement to fetch the data from the required table for
viewing purpose.
Advantages of views
COMPLEX VIEW: If we are creating a view by using more than one table then
that type of views are called as COMPLEX VIEWs.
VIEW WITH SCHEMA BINDING: If we create a view with schema binding option
the structure cannot be modified for the source table.
Example CREATE VIEW V_EXAMPLE1 WITH SCHEMABINDING
AS
SELECT EMPID, EMPNAME, EMPSAL FROM DBO.EMPSALDETAILS
ALTER TABLE EMPSALDETAILS ALTER COLUMN EMPID VARCHAR (50) Fail this
command
Provide the keyword with schema binding after the view name.
Avoid the * in select query and provide the list of the columns which
we required.
Provide the schema DBO. Before mentioned in the table.
VIEW WITH ENCRYPTION: If create a view with encryption option then we can’t
see the code which is returns inside of the view.
Example CREATE VIEW V_EXAMPLE2 WITH ENCRYPTION
AS
SELECT * FROM EMPSALDETAILS
INDEXED VIEW: If we create a index on view then that type of views are
called as indexed views in this case view can store the
data same as tables with the help of index.
We have to create only unique cluster index only these
types’ views.
While creating index views we have to remind the following
cases.
View should be schemabinded
Mentioned the list of the columns instead of stocks.
Provide schema name also preceding the table name.
Create a unique clustered index for non duplicated column as following.
Constraints cannot be applicable for views.
View with schemabind index
CREATE VIEW V_index WITH SCHEMABINDING
AS
SELECT EMPID, EMPNAME, EMPSAL FROM DBO.EMPSALDETAILS
SUBQUERYS
Sub query is the query with in a query
First it will execute the inner query and get the output, and pass it
into the outer query.
Example select * from empsaldetails
where empid in (select empid from empsal)
Example SELECT
(SELECT TOP 1 EMPID FROM EMPSAL)AS EMPID, EMPNAME
FROM EMPSALDETAILS
LIKE OPERATOR
START WITH ‘R’
SELECT * FROM EMPSALDETAILS WHERE EMPNAME LIKE 'R%'
OR
SCALAR VARIABLE
TABLE VARIABLE
TEMPARORY TABLES
Temp tables will be use full to store the data physically in table
which are created under TEMPDB database.
These are the session tables and will be disappear automatically whenever the
session got closed.
We have following types of temp tables in SQL SERVER.
NORMAL TEMP TABLES: If we are creating the table with # symbol that type
of table are called as NORMAL TEMP TABLE.
These normal temp tables will be valid only up to the created window.
If we close the created window then automatically the table will be deleted
in the TEMPDB.
HOW TO CREATE NORMAL TEMP TABLE
CREATE TABLE #CUST
(
CUSTID INT,
CUSTNAME VARCHAR (50),
CUSTBAL INT
)
GLOBAL TEMP TABLE: If we are creating the table with ## symbol then that
type of tables are called as GLOBAL TEMP TABLE.
These tables also will be created under TEMPDB and these will valid in
multiple windows until the created window got closed.
Once we close the created window automatically global temp table will
be deleted from TEMPDB database.
CREATE TABLE ##CUST
(
CUSTID INT,
CUSTNAME VARCHAR (50),
CUSTBAL INT
)
ITERATIVES
IF: If condition will check the given condition and the condition is
true, then it will execute the block which we mentioned immediate to
that condition, otherwise it will fall into else case and execute the
statement provide in it.
WHILE: while condition will check the given condition. satisfy it will
go into the loop and execute the statement until the condition is falls.
DECLARE @I INT =1
DECLARE @J INT = 10
WHILE (@I <= @J)
BEGIN
IF (@I%2=0)
BEGIN
PRINT @I
END
SET @I = @I+1
END
<SQL STATEMENTS>
END
END
EXEC USP_EXAMPLE1
PROCEDURE WITH INPUT PARAMETERS: It we pass any value while executing the
procedure then that value will be passed to the SQL statements and get the
details based on that value as a result.
END
EXEC USP_EXAMPLE2 UP
END
END
EXEC [USP_EXAMPLE2] UP
1 puNE bNg UP
END
FUNCTIONS
1) SCALAR FUNCTION
2) TABLE VALUED FUNCTION
SELECT DBO.FN_EXAMPLE ()
If the function is returns the table of values then that type functions are
called as table valued functions.
PROCEDURES:
Procedure may or may not return the value
We can call function in procedure
It will not do record by record
It will not close with parenthesis () until we use the parenthesis
Procedure will execute with exec statement
FUNCTIONS
Function must return the value
We can’t call procedure in function
Function will perform record by record process
Every function should close parenthesis ().
Function will execute with select statement.
INDEXES Indexes is like as same as index in the book. It will
provide the reference to the select query for retrieve the data very fastly.
We have two types of indexes
1) Clustered index
2) Non clustered index
CLUSTERED INDEX:
Whenever we are creating primary key then automatically clustered index
will be generated on the specified column
We can create only one clustered index per a table
It will store the actual values in the index pages to get the data very
fast.
It will use B TREE to search the values in the pages
When compare to the heap table we will get data in a faster way while
creating the index.
We can create clustered index on multiple column also even we don’t
have primary key.
------WITH DUPLICATES----
It will store the address of the values in the B TREE and get the
actual values using the address.
It will use the B TREE to search the value like pages
When compare to the heap table we will get data in the faster way
to retrieve.
FILL FACTOR: Fill factor is used to specify the range of the base to
fill the data based on index, it will tell the percentage of page to be fill
to store.
The Microsoft recommended percentage is 70%.
INDEX DISADVANTAGES
It occupies more space in the database to store the data in the index
page.
Whenever we are doing update, insert, in index will give very low
performance to do the operation
Whenever we are inserting the intermediate value for the index it will
not automatically allocate the proper position in the index pages then
performance will not be high, while retrieving the data from the table
We can’t create indexes as TEXT, NTEXT, IMAGE datatypes.
TRIGGERS Triggers are used to rise and event, whenever user doing the
operation against the database for table.
We have following types of triggers DDL & DML
DDL TRIGGERS: DDL triggers are database triggers if we are performing any
kind of operations like CREATE, ALTER, DROP against the database.
AS
BEGIN
END
TABLE CREATION
AS
BEGIN
ROLLBACK
END
TO CRAETE TABLE
CREATE TABLE BBBB
(
ID INT
)
OUTPUT
YOU DONT HAVE PERMISSIONS TO DO DDL OPERATIONS
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
DML TRIGGERS: DML triggers are table level triggers it will restrict the
user to do the table level operations.
END
CURSORS cursors are used to do the row operations on table for each
and every record, it is private memory area, which will be stored the result
of SQL statements.
To create the cursors we have to follow the 5 steps.
1) DECLARE CURSORS
2) OPEN CURSORS
3) FETCH STATUS
4) CLOSE CURSORS
5) DE ALLOCATE CURSORS
DECLARE CURSOR: we can declare a cursor for select statement then it will
fetch the data from those tables and insert in to cursors.
OPEN CURSORS: It will open cursor to read the data record by record in to
the variables.
FOR OPEN
OPEN <CURSOR NAME>
<DECLARE SELECT STATEMENTS OF VARIABLES>
FETCH STATUS
@@FETCH STATUS
<INSERT STATEMENTS>
FETCH NEXT FROM <STATEMENTS>
CLOSE CURSOR
CLOSE <CURSOR NAME>
DE ALLOCATE CURSOR
DE ALLOCATE <CURSOR NAME>
Example
DECLARE ABC CURSOR
FOR SELECT * FROM EMPSAL
OPEN ABC
DECLARE @DEMPID INT,@DEMPNAME VARCHAR (50), @DEMPSAL INT
WHILE (@@FETCH_STATUS=0)
BEGIN
PRINT 'THE EMPLOYEE HAVING NUMBER' +
CAST (@DEMPID AS VARCHAR)+ 'IS HAVING NAME AS' + @DEMPNAME+'WITH HIS SALARY
AS' +
CAST (@DEMPSAL AS VARCHAR)
The end.