0% found this document useful (0 votes)
59 views

SQL

SQL is a database language used to communicate with database systems like SQL Server, MySQL, and Oracle to perform operations like inserting, updating, deleting, and retrieving data. It consists of statements divided into four main types: DDL for data definition, DML for data manipulation, DCL for data control, and TCL for transactions. SQL provides tools like joins, views, functions, and constraints to manage relational databases.

Uploaded by

ramu
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

SQL

SQL is a database language used to communicate with database systems like SQL Server, MySQL, and Oracle to perform operations like inserting, updating, deleting, and retrieving data. It consists of statements divided into four main types: DDL for data definition, DML for data manipulation, DCL for data control, and TCL for transactions. SQL provides tools like joins, views, functions, and constraints to manage relational databases.

Uploaded by

ramu
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

SQL[Structured Query Language]

===
---> it is a DataBase Language, which is used to communicate with Database
Systems
(SQL server,MS-ACCESS,ORACLE,MySQL,DB2,SYBASE) for the follwing purpose

*) Inserting Data
*) Deleting the Data
*) Updating the Data
*) Retrieving the Data
--> it is not a case-sensitive Language

--> Query = QUEstion+ReplY

DATABASE --> collection of Tables, where Table is called "Relation"


TABLE --> Collection of Records, where records are called "ROWS or "TUPLES"
RECORD --> Collection of Fields or Attributes

--> SQL statements are Divided into 4 TYPES

*) DDL (Data Definition Language) statements


1. create
2. alter
3. drop
4. Truncate
*) DML(Data Manipulation Language) statements
1. Insert
2. Update
3. Delete
4. Select
*) DCL (Data Control Language) statements
1. Grant
2. Revoke
*) TCL (Transction Control Language) statements
1. Commit
2. RollBack

SQL TOPICS
==========
*) SQL statements
*) SQL OPerators
*) SQL set Operators
*) SQL joins
*) SQL stored Procedures
*) SQL Triggers
*) T-SQL (Transact SQL)
*) SQL Cursors
*) SQL Views
*) SQL Constraints
*) SQL Functions
*) SQL RULES

SQL STATEMENTS
==============
1. DDL statements
============

*) create
=====
--> it is used to create the Database,Table,views, triggers, stored
Procedures and so on

i) syntax : creating the Database


----------------------------------

create database <database_name>

Ex : create database EmployeeDB

---> When Executing this Query, the two files are Created

*) ".MDB" file ---> holds the Datas or records


*) ".LDF" file --> holds the Transaction Information

syntax : selecting the Database


--------------------------------

use DataBase_Name

Ex : use EmployeeDB

ii) syntax : creating the Table


----------------------

create table <table_name>(col1 datatype,col2 datatype,....)

SQL DataType
==========
int --> specifies the integer values to Store in a Column
datetime --> specifies the Datetime value to Store in a Column
varchar ---> specifies the Variable Length characters to Store in a
Column
char ---> specifies the Fixed length of character String to
store in a Column
money ---> specifies the Float values to store in a Column
varbinary --> specifies the Binary values to store in a Column

Ex: create table emp(eid int,ename varchar(20),sal int)

syntax : viewing the Structure of a Table


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

Exec sp_help <table_name>

Ex : EXEC[UTE] sp_help emp

2) alter
====
--> used to change or modify the structure of Existing table

*) we can add new columns


*) we can modify the datatype of Existing column including its size
*) we can also a delete a column of a Existing Table

i) syntax : Adding a New Column


----------------------------

alter table <table_name> add new_column_name datatype

Ex : alter table emp add dept varchar(5)

ii) syntax : Deleting a Column


-----------------------

alter table <table_name> drop column <column_name>

Ex: alter table emp drop column dept

iii) syntax : modify or change the Existing column datatype

-------------------------------------------------------------------------

alter table <table_name> alter column <existing_col_name> new_datatype

alter table emp alter column ename varchar(40)

3. drop
===
---> used to remove the table from the DB system

syntax : drop table table_name


=====

Ex : drop table emp

4. truncate
======
--> used to remove all the rows from the table.

syntax : truncate table <tablename>

Ex : truncate table emp

DML statements
===========

1. select
====
--> it is used to retrieve all rows or specific rows from the Table

i) Syntax : Retrieving the All rows


-----------------------------

select * from <table_name>

Ex : select * from emp


ii) syntax : Retrieving the Specific rows
---------------------------------

select * from <table_name> where <condition>


Ex : select * from emp where address='hosur'

iii) syntax : retrieving all rows with specific columns

select col1,col2,...,col-n from <table_name>

Ex : select ename,salary from emp

iv) syntax : Retrieving the TOP N records


------------------------------------

select top n * from tablename

Ex : select top 15 * from emp

2. Insert
====
--> used to insert or add new records to table

i) syntax : inserting the values in all columns


----------------------------------------

insert into <table_name> values(val1,val2,val3,....);

Ex : insert into emp values(1001,'ssss','CS')

ii) syntax : inserting the values in specific colms


--------------------------------------------

insert into <table_name>(col1,col2,..) values(val1,val2,..)

Ex : insert into emp(eid,ename) values(1001,'www')

3) delete
====
--> used to delete all rows or specific rows from the table

i) syntax : to delete all rows


---------------------
delete from <table_name>

Ex : delete from emp

ii) syntax : to delete only specific rows


---------------------------------
delete from <table_name> where <condition>

Ex : delete from emp where eid=1001 -> deletes the specific row

Ex : delete from emp where address='hosur' --> deletes the group of


rows
4) update
---> used to update the specific row or group of rows or all rows from
the Table

i) syntax : to update all records

update table_name set col1=val1,col2=val2,...

Ex : update emp set bonus=1000

ii) syntax : to update only specific records

update <table_name> set col1=val1,col2=val2,.. where <cond>

Ex : update emp set bonus=2000 where deptid=3

SQL operators
===========

*) <, >,<=,>=,<>,=
*) AND
*) OR
*) IN
*) NOT IN
*) BETWEEN
*) LIKE

Ex : AND
===

select * from emp where salary>=5000 AND salary<=10000

Ex : OR

select * from emp where city='hosur' OR city='bangalore'

Ex : BETWEEN

select * from emp where salary BETWEEN 6000 AND 10000

Ex : IN

select * from emp where city in('hosur','krishnagiri')

Ex : NOT IN

select * from emp where city not in('hosur','krishnagiri')


Ex : LIKE

WILDCARD SYMBOLS
================

% ----> matches the 0 or more characters


_(underscore) ---> matches the Single character

[ ] --> matches the character listed within the brackets

[ start-end ] --> matches the characters within the given range

Ex : %
=====

select * from emp where ename LIKE 'N%'


select * from emp where city not in('hosur','krishnagiri')
select * from emp where ename like 'v%'
select * from emp where ename like '_i%'
select * from emp where ename like '[svk]%'
select * from emp where ename like '[a-m]%'

SQL set OPERATORS


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

--> used to combine the rows of two or more tables..


--> each table must have the same no of columns and similar datatype

*) UNION
--> used to combine the rows from two or more tables without
including the duplicates records..

syntax
=====
select * from T1 UNION select * from T2

*) UNION ALL

--> similar to UNION but includes the Duplicate records in the


ResultSet.

syntax
---------
select * from T1 UNION ALL select * from T2

*) INTERSECT

--> returns the records that appears in both sets

syntax
--------
select * from T1 INTERSECT select * from T2
*) EXCEPT [MINUS-ORACLE]

---> returns only the records that appears in first set but not in
the Second set..

syntax
--------
select * from T1 EXCEPT select * from T2

Ex :
===
select * from emp UNION select * from emp1
select * from emp UNION ALL select * from emp1
select * from emp INTERSECT select * from emp1
select * from emp1 EXCEPT select * from emp

SQL Constraints
=============

Data Integrity
---------------
--> it ensures the correctness of the Data stored in the Database
Tables

Constraints
--------------
--> constraints are set of rules, which are applied to table columns

Types of Constraints
================

*) primary key constraint


*) Unique Constraint
*) foreign key constraint
*) not null constraint
*) default constraint
*) check Constraint

i) primary key constraints


-----------------------
---> it doesnt allows the duplicate values to enter in a columns which has
primary key

syntax
=====

create table <tablename>


(
col1 datatype constraint <constraint_name> constraint_type,
col2 datatype,
------
)

Ex :
==
create table student
(
sid int constraint sid_key primary key,
sname varchar(20)
)

ii) unique constraints


------------------------
--> similar to primary key constraints but it allows the NULL values

Ex :
create table student1
(
sid int constraint sid_key1 unique,
sname varchar(20)
)

iii) Default Constraint


-------------------------
---> it is used to insert default value in a column when the user not
given the value to insert

syntax
======
create table tablename
(
col1 datatype,
col2 datatype default value,
-----
)

Ex :
==
create table emp2
(
eid int,
ename varchar(20),
deptid int,
doj datetime default getdate(),
salary int default 6000
)

insert into emp2(eid,ename,deptid) values(1001,'sri',100)


insert into emp2 values(1002,'eeee',101,'12-jul-2008',10000)

iv) Not Null Constraint


---------------------------

-> The Enforcement of NOT NULL constraint on a Table Column, makes the user
must enter the value in a Column which has NOT NULL constraint..
syntax
=====
create table <tablename>
(
col1 datatype not null,
col2 datatype,
----
)

Ex : create table student(sid int,sname varchar(10) not null)

v) check Constraint
-----------------------
--> it allows only a specific range values to Enter in a Column

syntax
=====

create table <tablename>


(
col1 datatype constraint constraint_name check (columnname
in('val1','val2')),
col2 datatype,
----
)

Ex:
==
create table emp
(
eid int,
ename varchar(20),
gender varchar(10) constraint gen_check check (gender
in('Male','female')),
age int constraint age_check check(age between 20 and 40)
)

Enabling/Disabling the Constraint Checking


-------------------------------------------

i) Disabling the Constraint Checking

syntax
=====
alter table tablename nocheck constraint [ALL|Constraint_name]

Ex : alter table emp nocheck constraint gen_check

ii) Enabling the Constraint


----------------------

syntax
=====
alter table tablename check constraint [ALL|Constraint_name]

Ex : alter table emp check constraint gen_check


vi) Foreign key constraints
======================
--> it is used to create a relationship b/w tables
--> all values in the Foreign key must match the Values in the Primary key
--> Foreign key references the Primary key

Ex :
===
create table student_personal
(
sid int constraint p_id primary key,
sname varchar(10),
address varchar(20),
gender varchar(10)
)

create table student_marks


(
sid int constraint f_id foreign key references student_personal(sid),
Tamil int,
English int,
Maths int,
Science int,
SScience int,
Total int,
Result varchar(5)
)

T-SQL(Transaction SQL) @a--> local,@@-->global varibles


=================
--> we can add a programming features to SQL to perform the tasks as mush as
Easy to make the Transaction..

T-SQL Variable Declaration


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

syntax : declaring the Variable


=====
declare @varname

Ex : declare @a int
declare @name varchar(20)

syntax: assigning the values to a Variable


======

set @varname=value
(or)
select @varname=value from <tablename> where <condition>

Ex :
===
set @a=100

or
select @a=100

select @name=ename from emp where eid=1001

syntax : printing the Variable Values


=====
print 'user string' --> displaying the String values
print convert(varchar,variable) --> displaying the Integer Values
print 'user string' + convert(varchar,variable)

Ex :
==

print 'The value of a is : '+convert(varchar,@a)

declare @a int
declare @salary int
declare @ename varchar(20)
set @a=1
select @salary=salary,@ename=ename from emp where eid=1001
print 'The value of a is : '+convert(varchar,@a)
print 'EName : '+@ename
print 'ESalary : '+cast(@salary as varchar)

Ex : if...else statement
==
declare @a int,@b int
set @a=10
set @b=20
if @a>@b
print 'a is greatest'
else
print 'b is greatest'

begin....end block
===============

it is used to include set of T-SQL statements

syntax
=====

begin
//stmt1
//stmt2
-----
end

Ex :
==
declare @a int,@i int
set @a=10
set @i=1
while @i<=@a
begin
print 'i = '+convert(varchar,@i)
print 'i * a = '+convert(varchar,(@i*@a))
set @i=@i+1
end

Stored Procedures
==============
--> it is a procedure, which is used to execute the set of statements as a
Single Transaction
--> it is createad and stored in server

syntax
===

create procedure <procedure_name> [par1,par2,...]


as
begin
//sql statements
end

syntax : Executing the Stored procedure


===

EXEC[UTE] procedurename [par1,par2,..]

syntax : droping the Procedure


=====

drop procedure <procedure_name>

create table student (sid int,sname varchar(20),M1 int,M2 int,M3 int,tot int,aveg
int,result varchar(10))

create procedure stuinsert @sid int,@sname varchar(20),@m1 int,@m2 int,@m3 int


as
begin
declare @tot int,@avg int
declare @r varchar(10)
set @tot=@m1+@m2+@m3
set @avg=@tot/3
if @m1>=35 and @m2>=35 and @m3>=35
set @r='PASS'
else
set @r='FAIL'
insert into student values(@sid,@sname,@m1,@m2,@m3,@tot,@avg,@r)
print 'Record Inserted'
end

exec stuinsert 1003,'arun',78,87,95

select * from student


select * from student order by tot DESC

SQL Functions
============

---> scalar functions or single row functions

*) Numeric Functions
*) string functions
*) Date functions
*) conversion functions(convert,cast)
*) System functions

---> aggregate functions or group functions

*) min()
*) max()
*) count()
*) sum()
*) avg()

select * from emp


select sum(salary) as TOTAL_SALARY from emp
select avg(salary) as AVG_SALARY from emp
select min(salary) as MIN_SALARY from emp
select max(salary) as MAX_SALARY from emp
select count(*) as NO_OF_Employees from emp

select city, sum(salary) as TOTAL_SALARY from emp group by city

i) Numeric Functions
===============
select sqrt(64),abs(-
50),sin(45),cos(45),tan(45),power(2,3),floor(23.67),ceiling(34.78),round(123.54676,
2),pi(),log(100),exp(5),rand()

ii) Date Functions


------------------
select getdate(),dateadd(yyyy,2,'12-jul-2012'),datediff(dd,'12-jul-
2012','20-jan-2014'),day('12-jul-2014'),month('12-jul-2013'),year('13-jul-2014')

iii) String Functions


----------------------

select char(97),ascii('a'),left('Navin kumar',6),right('Navin


Kumar',5),len('Navin Kumar'),ltrim(' sri'),rtrim('sse
'),replicate('Navin',3),upper('sachin'),lower('VIRU'),replace('sachinRT','RT','Rame
sh'),substring('Navin Kumar',1,5)

System functions
=============
--> used to query general information about the DB system

select
host_id(),host_name(),suser_id(),suser_name(),object_id('emp'),object_name(20730584
21)

DCL statements
=============

*) grant --> giving permission to another user to access its DB Objects

syntax
======

grant [previleges] on <table_name> to <User_name>

Ex : grant ALL on emp to user2

Ex : grant INSERT on emp to user2

*) revoke --> withdrawing the permission from the Granted users

syntax
======

revoke [previleges] on <table_name> from <user_name>

Ex : revoke ALL on emp from user2


Ex : revoke INSERT on emp from user2

TCL statements
============

---> commit

--> used to make a transaction permanent to the Database


--> once the transaction is commited, we cant rollback the transaction

syntax : commit

---> rollback

--> used to undo the transaction

syntax
======
rollback

Cursors
=======
1) declaring the Cursor
==============

syntax :

----

declare cursor_name cursor [forward|scroll]


for select statement

Ex:
===

declare mycursor cursor scroll


for select * from emp

2) opening the Cursor


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

syntax :
=======
open cursor_name

Ex : open mycursor

3) Fetching the Information from the Cursor


================================
syntax
======

fetch [next|prior|first|last|absolute n|relative n] from cursor_name into


var1,var2,..

4) closing the Cursor


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

syntax:
======
close cursor_name

Ex; close mycursor


==

5) Deallocate the Cursor


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

syntax
======
deallocate cursor_name
Ex:
==
deallocate mycursor
declare mycursor cursor scroll
for select * from emp

open mycursor

declare @eid int,@deptid int,@sal int


declare @name varchar(20),@city varchar(20)
fetch absolute 1 from mycursor into @eid,@name,@sal,@deptid,@city
print 'Eid : '+convert(varchar,@eid)
print 'Ename : '+@name
print 'Esalary : '+convert(varchar,@sal)
print 'Deptid : '+convert(varchar,@deptid)
print 'City : '+@city

declare @eid int,@deptid int,@sal int


declare @name varchar(20),@city varchar(20)
fetch next from mycursor into @eid,@name,@sal,@deptid,@city
while (@@fetch_status=0)
begin
print 'Eid : '+convert(varchar,@eid)+'-Ename : '+@name+
'-Esalary : '+convert(varchar,@sal)+'-Deptid : '+convert(varchar,@deptid)+'-
City : '+@city
fetch next from mycursor into @eid,@name,@sal,@deptid,@city
end

SQL VIews
===========

--> A view is a virtual table, which holds the Output of the Query..

--> holds the records as up-to-date

syntax
======
create view view_name
as
select Query

Ex : create view myview as select * from emp

droping the Views


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

syntax : drop view view_name

Ex: drop view myview


sql Joins
=========

--> joins are used to combine rows from two or more tables based on the
Condition..

types of joins
===========

*) inner join
*) outer join
--> left join
--> right join
--> full join
*) cross join

INNER JOIN:
===========
Returns all rows when there is at least one match in
BOTH tables
LEFT JOIN:
========
Return all rows from the left table, and the matched
rows from the right table
RIGHT JOIN:
=========
Return all rows from the right table, and the matched rows
from the left table
FULL JOIN:
===========
Return all rows when there is a match in ONE of the tables

*) inner join
========
syntax :
-------

select * from T1,T2 where T1.C1=T2.C1

or
select * from T1 inner join T2 on T.c1=T2.c1

*) outer join
==========
--> similar to inner join but it also includes the unmatched values in the
Resultset

syntax
select * from T1 [LEFT|RIGHT|FULL] OUTER JOIN T2 ON T1.C1=T2.C1

*) cross Join
==========
---> it gives the cortesian product of two tables

syntax
======

select * from T1 cross join T2

SQL Rules
======

-->a rule specifies the acceptable values that can be inserted into that column.

syntax
======
create rule rule_name as <conditional_Expression>

Ex:
===
create rule myrule as @salary>=3000

binding the rule to Table column


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

syntax
======

execute sp_bindrule rulename,'obj.colname'

Ex:
---

execute sp_bindrule myrule,'emp_salary.salary'

unbinding the rule


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

syntax:
=======
execute sp_unbindrule 'obj.colname'

Ex:
===
execute sp_unbindrule 'emp_salary.salary'
Sql Identity property
===============

--> it is applied to the table column when creating the table,so we dont need to
enter the values in the column with idenity property..

syntax
======

create table <table_name>


(

col1 datatype identity(seed,incr),


col2 datatype,
----
)

Ex:
==

create table emp


(
eid int identity(1001,2),
ename varchar(20)
)

@@idenity
=========
--> it is a Global variable, which is used to find the most recently generated
identity value

Ex:
==
select @@identity

select ident_seed('emp')
select ident_incr('emp')

Triggers
======
syntax:
======

create trigger <trigger_name> on <table_name>


[FOR|AFTER|INSTEAD OF] [INSERT|UPDATE|DELETE]
as
begin
//statements
end

You might also like