Sunday, March 13, 2011

how to write queries in sql server

SYNTEX FOR CREATE TABLE

 create table <tablename>(<col1><datatype>[width],<col2><datatype>[width],<col3><datatype>[width],.....
  <colN><datatype>[width] )
[] means optional
<> means any value you can give any name

e.g.   create table student (sno int,sname varchar(30))
to view the structure of the table you can use the following command

  sp_help <tablename>

SYNTEX FOR INSERT COMMAND

It is used for inserting data into created table 

insert into <tablename>[(col1,col2,col3....colN)] values(val1,val2,val3...valN)

e.g  insert into student  values(101,'Narendra')
 if i want to insert more  data than insert into student (sno,sname)  values(101,'Smith')
this is faster than above one so it is good practice always use column name.

While performing insert operation if we do not provide value for any column it takes NULL as a Default value

We can also explicitly insert Null value into desire column like
 insert into student (sno,sname) values(102,NULL)
 insert into student (sno,sname)values(103, 'NULL' ) (it will be wrong for inserting null value it will be traten as string)
NULL is a Keyword in sqlserver

SELECT COMMAND 

 If we want to retrieve the information that is present in table we use Select command

select <*|collist>  from <tablename>[<condition>] 


e.g. select * from student
Insted of * we can use column name for retrieve all the information from table and performance will also improve
              e.g.   select sno,sname from table 

COLUMN ALIASING:


 We can specify an alias name to any column of the table so that the alias name can be displayed in the output without changing the name of the table name.
An alias can be provide for column or table also
e.g. select sno Sno snumber from student
        select sno as snumber fron student

WHERE CONDITION IN SELECT

select * from student where sno=101

select * from student where sno=NULL (wrong)
When we want to perform operation based on NULL value we can not use Equal(=) operator.Because NULL value internally treated as unknown or indefrent value so not to NULL are equal
In our example the above statement will not retrieve the information because we are trying to compare NULL with NULL using equality operator
To overcome above drawback and retrieve  the information based on NULL values
use IS NULL

e.g. select * from student where sname is null

UPDATE COMMAND

update <tablename> set <col>=<value>[....n][<where condition>]

e.g. update student set sname="Vijay' where sno=101

DELETE COMMAND

It is used for deleting rows from table
delete from <tablename> [<where condition>]

e.g. delete  from student where sno=102

No comments:

Post a Comment