Anda di halaman 1dari 12

SQL

-Structured query language is query language for storing modifying and retrieving data from
database.

 Data definition language


 Data Manipulation Language
 Data control Language

DDL

 create
 Alter
 Drop

DML

 Select
 Insert
 Update
 Delete

DCL

 Grant
 Revoke

Create

Create database dbname

Eg:- Create database db1;

Create table table_name (col_name datatype);

Eg:- Create table tab1 (name varchar(20),id int, age int, dob date);

Create table from existing table

The new table will be filled with data from existing table have the same column definition

Either all column or sekective column can be selected

Create table newtable as select * from old table

Eg:- create table tab2 as select name,id from tab1 where id<5;

Drop

Drop an existing databse and table


Drop Database dbname;

Eg:- drop Database Db1;

Drop table tablename;

Eg:- Drop table tab1;

Truncate is used to delete data inside table not entire table definition.

Truncate table table_name

Truncate table tab1;

Alter

Used to add, modify and delete columns in table

Also to alter the index and constriants.

Alter table table_name add/modify/drop column_name data_type;

Eg:- Alter table tab1 add address varchar(100);

Alter table tab1 modify column address var;

Alter table tab1 drop column age;

In oracle before 10g /Mysql

Alter table tab1 modify column address var;

In Mssql

Alter table tab1 alter column address var;

In oracle 10g

Alter table tab1 modify address var;

Insert

Insert data into table

Insert into table_name values ( val1,..);

Insert into table_name (col1,col2..) values (val1,val2);

Eg:- insert into tab1 values(arthi,01,26);

Insert into tab1 (name, age) values (bala ,23);


Table can be populate by using data from another table where as target and source table column
datatype should be same.

Insert into tablename select * from tablename where condition;

Select into

Copies data from one table into new table

Select * into newtable from oldtable where condition;

Eg:-

Select name ,age into tab3 from tab1 where age<30;

Delete

Delete records from table

Delete from tablename;

Eg:- delete from tab1 where id =05;

Update

To modify existing records in a table;

Update tablename set columnname= value where condition;

Eg:-Update tab1 set age =45 where id=7;

Select

Select database

Use dbname

Eg:- Use mydb;

To select/fetch data from database

Select * from tablename;

 Distinct

To select unique records

Select distinct * from tablename;

Eg:- select distinct name from customers;


 Where – to filter the records

Select * from tablename where condition

Eg:- select name,ge from tab1 where id<10;

Operators to use in where clause are =, <, >, <=, >=, BETWEEN, LIKE, IN

To combine conditions AND, OR, NOT are used

Select * from customers where id <10 AND age >18;

 Orderby

To sort the result in ascending or descending order

Select * from tablename orderby colname asc|desc

Eg:- Select * from tab1 orderby name desc;

By default ascending order;

 Top /limit/rownum to fetch top n number of records from table

Select top number|percentage from tablename;

Eg:- select top 5 * from tab1;

Select top 60 percent from tab1;

 Limit (mysql)

Select * from tab1 where limit 10;

 Rownum (oracle)

Select * from tab1 where rownum<=10;

Max/Min

To return maximum or minimum value of selected column.

Select max(colname) from tablename;

Eg: -

Select max(age) as maxage from tab1;

Count -return count number of records matches the conditions

Select count(id) from tab1 where age<30;

Avg -Return the average of specified numeric column

Eg:- Select avg(marks) from customer;


Sum -returns the total of specified numeric column;

Eg:- select sum(marks) from customer;

Like used in where clause to search pattern

%->searches zero ,one or more character

_-> single character

Wildcards % ,_ , [],!/^

%a-ends with a

[a-c]%- starts with a to c

%[dgh] ends with d/g/h

[!jkl]% not starts with j/k/l

_r%a_i any char followed by r followed by any chars ends with a followed by any char ends with i.

IN / not in

Used to specify multiple values in for where condition

Select * from tab1 where name IN (‘arthi’,’bala’, ‘chitra’);

Slect * from tab1 where name IN (select name from tab2);

Between /not between

Used to specify values in range in where condition

Select * from tab1 where age BETWEEN 18 and 26;

Select * from tab1 where dob between # 01/01/1994# and #01/01/2005# ;

Aliases

Used to give temporary name for table or column

Is exist only for duration of query

Select name as fname from tab1;

Select t.name s.age from tab1 as t, tab2 as s;

NULL Values to represent missing value

IS NULL or IS NO TNULL functions used to check whether null or not.

Eg:- select * from tb1 where name IS NOT NULL;


In expression if one of value sis null then result will be null for instead of null alternate value sis
returned

For that ISNULL() ,IFNULL(),NVL(), coalesce is used

Mysql

Select name, unitprice * (unitsinstock +IFNULL( unitsorder ,0)) from tab2;

Select name, unitprice * (unitsinstock +ISNULL( unitsorder ,0)) from tab2;

Select name, unitprice * (unitsinstock +coalesce( unitsorder ,0)) from tab2;

Select name, unitprice * (unitsinstock +NVL unitsorder ,0)) from tab2;

Constraints

Rules enforced on data of table to limit type of data ensures accuracy and reliability of data in
database. Either column or table level.

 Notnull – column cannot have null value

Create table customer (name varchar, id int NOT NULL, address varchar(100));

 Primary – uniquely identify each row in database

create

o Create table customer ( name varchar, id int PRIMARY KEY);


o Create table customer (name varchar, id int , primay key (id)); (mysql)
o Create table customer (name varchar, id int, constraint pk_customer primary key (id,name));

Alter constraint

o Alter table customers add Primary key(ID);


o Alter table customer add constraint UCCustomer primary key(id, name);

Drop

o Alter table customer drop constraint UCCustomer ;


o Alter table customer drop primary key ; (mysql)

 Unique – ensures all values in table are different.

create

o Create table customer ( name varchar, id int UNIQUE);


o Create table customer ( name varchar, id int ,UNIQUE (id) );
o Create table customer ( name varchar, id int , constraint u_customer UNIQUE (id,name));
Alter constraint

o Alter table customers add unique(ID);


o Alter table customer add constraints UCCustomer unique(id, name);

Drop

o Alter table customer drop constraints UCCustomer ;


o Alter table customer drop index UCCustomer; (mysql)

 Foreign- uniquely identify tha record in any table

Foreign key links two table

Create table order (order_id int primary key , person_id int foreign key references
person(person_id),

Create table order (order_id int, person_id int, primary key (order_id) foreign key (person _id)
references person (person-id);

Create table order (order_id int, person_id int , constraint con2 foreign key (person_id) references
person (person_id);

Alter

Alter table order add foreign key(pid) references person(person_id);

Alter table order add constraint ufkey foreign key(pid) references person (person_id);

Alter table order drop foreign key con2;

Alter table order drop constraint con2;

 Default- provide default value for column when none is specified.

Create table order (name varchar,id int , address varchar default “Chennai”);

Alter
Alter table order alter column address set default ‘chennai’; (sql server)
Alter table order alter address set default ‘chennai’; (mysql)
Alter table order modify address default ‘chennai’;(oracle)
Drop
Alter table order alter column address drop default;
Alter table order alter address drop default; (mysql);

 Check- all values in columns satisfies certain condition

create table person (id int, name varchar, age int check(age>=18);

Create table person (id int, name varchar, age int, constraint chk_age check (age<=18));
Create table person (id int, name varchar, age int, check(age>=18));

Alter

Alter table person add check (age>=18);

Alter table person add constraint chk_age check(age>=18);

Drop

Alter table person drop check chk_age;

Alter table person drop constraint chk_age;

 Index- create and retrieve data from database quickly

Create index inx_name on persons (firstname , lastname);

Create unique index inx_name on persons(firstname,lastname);

Drop

Drop index person.inx_name; (sql server)

Drop index inx_name on person;(Ms access)

Drop index inx_name; (oracle)

Alter table person drop index inx_name; (my sql);

AutoIncrement

To increase value automatically when new record is inserted.

Create table tab1 (name varchar, id int auto_increment=10 ); mysql

Alter table tab1 auto_increment=10;

Create table tab1 (name varchar, id int identity (1,1); sql server

Create table tab1 (name varchar, id int autoincrement (10,5);

Sequence is used for oracle

Create sequence seq_name

Minvalue 1

start with 1

increment by 1

cache 10;
Group by

To arrangr the identical data into group

Follows the where clause precedes the orderby clause.

Used with aggregate functions.


. as a rule, when using GROUP BY and aggregate functions, any items in the SELECT list not used as an
argument to an aggregate function must be included in the GROUP BY clause.

Eg:- Select sum(sales),department where group by department

Having

Having clus is used along with groupby used to restrict dta send to groupby clause.

Where is filters the data before grouping whereas having filters after grouping.

Eg:-

Select name ,id ,age, department from person group by department have age>50;

Join

Join is used to combine rows from two or more tables based on related columns between them.

Inner join

Left join

Right join

Full join

Cross join
Inner join or equi join or natural join

Selects records hat have matching vaues in both table

Select person .name ,person. Address, order .orderno from person inner join order on
person.id=order.id order by person.id.
When to useinner join

Use an inner join when you want to match values from both tables.

Why to use Inner Joins:

Use inner joins to obtain information from two separate tables and combine that information in one result set.

When you use inner joins, consider the following facts and guidelines:

1. Inner joins are the SQL Server default. You can abbreviate the INNER JOIN clause to JOIN.

2. Specify the columns that you want to display in your result set by including the qualified column names in the
select list.

3. Include a WHERE clause to restrict the rows that are returned in the result set.

4. Do not use a null value as a join condition because null values do not evaluate equally with one another.

5. SQL Server does not guarantee an order in the result set unless one is specified with an ORDER BY clause.
[Source: Microsoft SQL Server 7.0 data warehousing training]

Outer join l(eft and right join)

Left
Returns all records from left table and matched records from right table .

Why to use outer joins

Use left or right outer joins when you require a complete list of data that is
stored in one of the joined tables in addition to the information that matches the join condition.

When to use outer joins

Use an outer join when you want to find unmatched rows. (because either you want to find missing values from
one of the tables, like in this case, or you may want to include all values from your tables even if they are
missing values in the other table).

Self join

Is used to join the table to itself

For eg employee table with field name id and emp’s manager id

To dispay emp and their manager name where as namager is not in that table

We use self join

Select E1.name as employee E2.name as manager from emp e1 emp e2 where E1.mgr_id==E2.id;

Why use self join

While self-joins rarely are used on a normalized database, you can use them to reduce
the number of queries that you execute when you compare values of different columns
of the same table.

When you use self-joins, consider the following guidelines:

You must specify table aliases to reference two copies of the table. Remember that table
aliases are different from column aliases. Table aliases are designated as the table name
followed by the alias.

When you create self-joins, each row matches itself and pairs are repeated, resulting in
duplicate rows. Use a WHERE clause to eliminate these duplicate rows [Microsoft SQL
Server 7.0 data warehousing training

Cross join or cartesian join

Every row of one table is matched with every row of another table.

Eg:- select * from dept,emp;

Select * from emp join on dept;


UNION

Is used to combine the resultset of two or more select statements.

Each Select statement must have same no of columns with same datatype in same order

Union give u distinct value

To select all values union all is used.

EG:-

Select city from persons

Union

Selct city from order;

Views

Is virtual table represent data from 2 or more tables

Query is stored in data dictionary.

Table referred here is called as base tables.

Create eg:-

Create view view_name as slect * from table_nmae;

Create or replace view view_name as select * from table_name where condition;

Drop view view_name;

SUBQUERY

Subquery should be enclosed within parameters

Subquery should select only one column

In operator is mostly used with subquery

Between query should not be used in subquery

Eg:-

Select product name ,price from productdetails where product_id in (select id from orderdetails );

Anda mungkin juga menyukai