You are on page 1of 13

(1) Creating a Database: Create database <database name> Ex: Create database db1 (2) Getting the Details

of Database: sp_helpdb database name Ex: sp_helpdb db1 (3) Altering Database: (i)To Add Data File: Alter database <db name> add file(data file specification) Ex: Alter database db1 add file( name=db1_data1,file name=D:\db1_data1.mdf, Size=3,filegrowth=2,maxsize=500) (ii)To Add Log File: Alter database <db name> add log file(log file specification) Ex:Alter database db1 add log file( name=db1_log1,file name=D:\db1_log1.ldf, Size=1,filegrowth=1,maxsize=100) (iii)To Modify File: Alter database <db name> Modify file(name=<logical name>,size=<n>,file growth=<n>,maxsize=<n>) Ex:Alter database db1 Modify file(name=db1_data1,size=5,filegrowth=5,maxsize=unlimited) (iv)To Remove File: Alter database <db name> Remove file <logical name> Ex:Alter database db1 Remove file db1_data1 (v)To Modify Name: Alter database <db name> Modify name=<new name> Ex:Alter database db1 Modify name=database1 (4) Deleting Database: Drop database <db name> Ex: Drop database db1

(5) CONSTRAINTS: (i)Not Null: (Column level only) <col name> <data type> Not Null (ii)Default: (Column level only) <col name> <data type> [Constraint <constr name>] Default <default value> (iii)Unique: (a)Column Level: <col name> <data type> [constraint <constr name>] Unique [clustered/ non-clustered] default is: non-clustered (b)Table Level: [constraint <constr name>] Unique (<col1>,<col2>,.) [clustered/ non-clustered] default is: non-clustered (iv)Primary Key: (a)Column Level: <col name> <data type> [constraint <constr name>] Primary Key [clustered/ non-clustered] default is: clustered (b)Table Level: [constraint <constr name>] Primary Key (<col1>,<col2>,) [clustered/ non-clustered] default is: clustered (v)Check: (a)Column Level: <col name> <data type> [constraint constr-name] Check(<condition>) (b)Table Level: [constraint constr-name] Check(<condition>) (vi)Foreign Key: or Referential integrity constraint: (a)Column Level: <col name> <data type> [constraint <constr name>] References <table name> (<col name>) [on update no action/ cascade/ set null/ Set default] [on delete no action/ cascade/ set null/ set default] Default is: no action (b)Table Level: [constraint <constr name>] Foreign Key (<col1>,<col2>,) References <table name> (<col1>,<col2>,) [on update no action/ cascade/ set null/ set default] [on delete no action/ cascade/ set null/ set default] Default is: no action

(6) Creating Tables: Create table <table name> ( <col name> <data type> [constraints], <col name> <data type> [constraints], <col name> <data type> [constraints], <col name> <data type> [constraints],<col name> <data type> [constraints],[table level constraints] ) Ex: Create table student (sid int constraint sid_pk primary key,sname varchar(20) Not null,course varchar(30) constraint course_def default cpp) (7) Getting List of Tables: (a) Sys objects table: Select * from sysobjects where type=U (b) System view: Select * from information-schema.tables Select * from sys.tables (c) Getting List of Columns in a Table: Select * from information-schema.columns Where table_name = emp Select * from syscolumns Where id = object_id(emp) Select * from sys.columns Where object_id = object_id(student) (d) Getting List of Constraints on a Table: Sp_help constraint table name Ex: Sp_help constraint marks Sp_help marks

(or)

(or)

(or)

(8) DML( Data Manipulation Language ): (i) Inserting Rows: Insert [into] <table name> values (<val 1>,<val 2>,<val 3>,.)

(or)

Insert [into] <table name> (<col 1>, <col2>,) values (<val 1>,<val 2>,.) Ex: insert into student(sname,course) values(A,SQL) (ii) Updating Rows: Update <table name> set <col 1> = <val 1>, <col 2> = <val 2>,.. [where <condition>] Ex: update student set course = oracle where sid = 1004
3

(iii) Deleting Rows: Delete [from] <table name> [where <condition>] Ex: select * from marks Delete marks where sid = 1005 (iv) Truncate: Truncate table <table name> Ex: truncate table student1 (9) Identity: Identity (seed, increment) Identity Functions: (a) Ident_seed(table name): Returns the seed value of identity available on the given table. (b) Ident_incr(table name): Returns the increment value of identity available on the given table. (c) Ident_current(table name): Returns the current value of the identity.i.e; the last value generated by the identity. (d) @@ identity: Returns the identity value generated by the last insert statement. (10) Creating a table from another table: Select * into <new table name> from <old table name> Ex: select * into student2 from student (11) Inserting rows from one table to another: Insert into <table name> <select stmt> Ex: insert into student2 select * from student (12) Altering Table Structure: (a) Add: Alter table <table name> [with check/no check] Add [constraint <constr name>] <constraint> Ex: alter table student1 add constraint sid_pk primary key(sid) (b) To alter existing col data type: Alter table <table name> alter column <col name> <new data type> Ex: alter table student alter column sname char(20) null Note: To remove the not null constraint on a col,alter that col & specify the option Null at the end of the col declaration.

(c) Drop the column: Alter table <table name> drop column col-name [,n] Ex: alter table student drop column fname, address (d) Dropping Constraint: Alter table <table name> drop constraint <constr name> [,.n] Ex:alter table marks drop constraint fk_marks_student (e) Check/no check Constraint: This option is used to enable (or) disable the constraint. Ex: alter table marks1 nocheck constraint sid_fk1 (13) Renaming a Column in the Table: Sp_rename table name.col name ,new name Ex: sp_rename student.sid,student-id (14) Renaming a Table: Sp_rename old name,new name Ex: sp_rename student,stu (15) Enable & Disable the Identity: Set identity_insert <table name> on/off Ex: set identity_insert stu on (16) Deleting Table: Drop table <table name> Ex: drop table marks (17) Retrieving the Data: Select */<col list> from <table name> Ex: select * from emp (18) Where: (a) with select: Select statement where <exp 1> [,.n] Ex: select * from emp where deptno = 10 (b) with update: Update {table/view} set column 1 = value 1 [,n] [where <exp>] Ex(1): update emp set salary = salary+1000 (2):Update emp set deptno = 15 where deptno = 10 (c) with delete: Delete [from] {table/view} [where <exp>] Ex: delete from emp where deptno is null
5

(19) Order by Clause: Select statement [where <exp>] order by <col list> [Ascen/Descen] Default is: Ascending Ex: select * from emp where deptno = 10 order by empno descen (20) Distinct: The key word distinct is used to eliminate duplicate values in the output of a select Stmt. A rule to use distinct is it can be used only once in the select stmt,that also Immideatly after the key word select. Ex: select distinct deptno from emp (21) Isnull: Isnull (<col name>,<value>) Ex: select ename,sal,comm,sal+isnull(comm,0), (sal+isnull(comm,0))*12 from emp (22) Group by: Select statement [where <exp>] group by <cols list> Ex: select job, sum(sal) from emp group by job (23) Having Clause: Select statement [where <exp>] [group by <cols list>] Having <exp> Ex: select deptno, count(*), avg(sal) from emp group by deptno Having count(*) > 2 (24) Joins: (a) ANSI: Select */ <cols list> from <table 1> inner/outer/cross join <table 2> [,n] [On <join condition>] i.e; join condition table 1.column = table 2.column [,.n] (b) Non-ANSI (or) SQL Server Syntax: Select */ <cols list> from <table 1>,<table 2> [,.n] where <join conditions> i.e; join condition table 1.column = table 2.column [,n] (25) Self Join: Select */ <cols list> from table alias name, table absence, table to [,n] Where <exp> (26) Sub Queries: Select statement where <exp> (select statement where <exp>) . Ex: select * from emp where deptno = (select deptno from emp where ename like raj) (27) Set Operators: (a) Union: Select stmt 1 Union Select stmt 2 Union Select stmt 3

Ex: select distinct job from emp where deptno = 10 Union select distinct job from emp where deptno = 20 (b) Union All: Select stmt 1 Union All Select stmt 2 Union All Select stmt 3 . Ex: select empno from emp Union All Select deptno from dept (c) Intersect: Select stmt1 Intersect Select stmt2.. Ex: select distinct job from emp where deptno = 10 Intersect select distinct job from emp where deptno = 20 (d) Except: Select stmt1 Except Select stmt 2.. Ex: select distinct job from emp where deptno = 10 Except select distinct job from emp where deptno = 20 (28) Indexes: (a) Creating Indexes: Create [unique] [clustered/ non-clustered] index <idx name> on <table name> (<col name> [Ascen/Descen],<col name> [Ascen/Descen],.) [include <cols list>] Default is: non-clustered Ex: create index dnoidx on emp(deptno) (b) Deleting Index: Drop index <idx name> on <table name> (,n) Ex: drop index dnoidx on emp (c) Getting List of Indexes: Sp_help index table name Ex: sp_help index emp (29) Views: (a) Creating a View: Create view <view name> [(<cols list>)] [with encryption] as <select stmt> [With check option] Ex: create view emp20 as select * from emp where deptno = 20 (b) Altering a View: Alter view <view name> [(<cols list>)] [with encryption] as <select stmt> [with check option] Ex: alter view emp20 as select * from emp where deptno = 20 With check option Insert into emp20 values(1002,A,CLERK,7782,09/23/1982) Select * from emp select * from emp20
7

(c) Getting the list of Views: Select * from information_schema.views Select * from sys.views (d) Getting the definition of a view: Sp_helptext View name Ex: sp_helptext empdept (e) Deleting a View: Drop view <view name> [,n] Ex: drop view name1 [,.n] (f) Changing cols in the view: (i) Schemabinding: Create view <view name> [(<cols list>)] [with encryption, schemabinding] as <select stmt> [with check option] (30) Cursors: (a) Declaring a Cursor: Declare <cursor name> Cursor [local/global] [forward-only/scroll] [static/dynamic/keyset] for <select stmt> (b) Opening a Cursor: Open <Cursor name> (c) Fetching data or records from the Cursor: Fetch {first/last/next/prior/Absolute <n>, Relative <n>} from <Cursor name> Into <Var list> (d) Closing the Cursor: Close <Cursor name> (e) Deallocating the Cursor: Deallocate <Cursor name> (31) Stored Sub Programs: (a) Stored Procedures: (i) Creating or Altering a Procedure: {Create/Alter} Procedure <prco name> [@param1 data type [= default value] [output][,n]] [{with recompile/with encryption}] As Begin --------------End

(ii) Executing a Procedure: (exec/execute) <proc name> [@param1 [output] [,.n]] Execute <proc name> <arg 1>,<arg 2>,. (iii) Getting List of Procedures: Select * from sys.procedures Select * from sysobjects where type = P (iv) Getting the Source code: Sp_helptext Procedure name (v) Deleting a Procedure: Drop procedure procedure name

(or)

pProcedure

(b) Functions: (i) User defined Functions: Create/Alter Function <Function name> ([@param1 datatype, @param2 datatype]) Returns <return type> [with encryption] as Begin <stmts> return <value> end (ii) Calling a Function: Select <function name> ([arguments]) Ex: select dbo.sum(10,20,30,40,50) (iii) Getting the List of Functios: (A) Scalar Functions: Select * from sysobjects where type = Fn (B) Inline Table Valued Functions: Select * from sysobjects where type = IF (C) Multi Stmt Table Valued Functions: Select * from sysobjects where type = TF (iv) Dropping (or) Deleting the Function: Drop Function <function name> (c) Triggers: (i) Creating a Trigger: Create trigger <trigger name> on <table/view name> [with encryption] For/after/instead of [insert] [,update] [,delete] as Begin <stmts> End
9

(ii) Getting the List of Triggers: Sp_helptrigger table name (or) Select * from sys.triggers Where parent_id = object_id(table name) (iii) Enable & Disable the Triggers: Alter table <table name> Disable/Enable trigger <trigger name> (iv) Deleting (or) Dropping the Triggers: Drop trigger <trigger name> (32) Syntax to Create Duplicate table from an Existing table: Select {*/ columns list} into <New table name> from <Existing table name> Ex: select * into Dept_ins from Dept (33) Syntax to Copy only the Structure from an Existing table: Select {*/ columns list} into <New table name> from <Existing table name> Where <False condition> Ex: select * into Dept_ins2 from Dept where 0 = 2 (34) Exception Handling: Begin try <stmts> End try Begin Catch <stmts> End Catch (a) Sys.messages: Sp_addmessage <msg id>,<severity>,<msg text> (b) Delete error messages: Sp_dropmessage <msg id> (c) Raising exceptions manually: Raiserror(msg id/msg text,severity,state[, arguments]) (35) Security: (a) Logins:( windows Authentication) Create login [<server name>\<user name>] from windows (b) Creating SQL Server Authentication Login: Create login <login name> with password = password, Default_database = <db name>, check_expiration = on/off, Check_policy = on/off
10

(c) creating users: Sp_grantdbaccess login name, user name (d) Granting Database Level Permissions: Grant <permission1>, <permission2>,. To <user1>, <user2>,.. [with grant option] (e) Granting Object Level Permissions: Grant <permission1>, <permission2>, on <object name> To <user1>, <user2>,.. [with grant option] (f) Getting List of Permissions Current user: Select * from fn_my_permissions (<Database/Object name>, Database/Object) (g) Revoke Database Level Permissions: Revoke <permission1>, <permission2>, .. From <user1>, <user2>, [cascade] (h) Revoke Object Level Permissions: Revoke <permission1>, <permission2>,.. on <object name> From <user1>, <user2>,.. [cascade] (i) Roles: (A) Creating a role: Sp_addrole Role name (B) Granting permissions to a role: Ex: grant select on emp to myrole (C) Adding members to a role: Sp_addrolemember role name, user name (D) Deny permissions to a role: Deny <permission1>, <permission2>,. On <object name> To <user1>, <user2>, (E) Removing members from a role: Sp_droprolemember role name, user name (F) Deleting a role: Sp_droprole role name (G) Getting list of roles: Sp_helprole (or) Sp_helprole role name
11

(H) Getting list of role members: Sp_helprolemember role name (36) Case Statement: Case When condition1 Then result1 When condition2 Then result2 -----------------------------------[else result n] End (37) Grouping: SQL Server provides the function grouping to determine whether (or) not value for a Column is generated by Rollup (or) Cube as null. If the values for a column is generated By Rollup (or) Cube as null then it returns 1 & otherwise returns 0 (zero). Grouping (<col name>) (38) Computeby: A draw-back for group by is, it can display the data only from those columns that are in Group by. When you want to display data from every column in table but apply the Aggregate function by deviding rows into groups based on values of only a particular Column then use Computeby. Rule: A rule to use Computeby is every column in Computeby must be in Order by. (39) Over(partition by): This is same as Computeby & can calculate Aggregates by deviding the rows into groups while displaying data from any columns. It displays the result of Aggregates with every row but not at the end of every group unlike the Computeby. (40) Top n: This clause is used to retrieve top n rows from the result of a select statement. You can use the key word percent with top n to retrieve top n percent of rows instead of top n rows. Top n percent Ex: select top 3 * from emp order by sal desc Ex: select top 20 percent * from emp order by sal We can use the option with ties with top n clause to retrieve every row from the table that has same value as the last row retrieved by the top n clause within the column used in Order by. Ex: select top3 with ties * from emp Order by sal desc.

12

13

You might also like