SQL Commands
SQL Commands
-----------------------
Syntax:
Create Table <table-name> (<column-name> <data type> (<width>) , … );
Example:-
Creating a table named Employee with fields Employee No, Employee Name, Designation,
Department , Salary and date of Birth.
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='Employee'
OR
sp_columns 'Employee'
Insert (DML):-
Syntax:
Note : if values are inserted into all coulmns in the correct order then there is no need to specify
the column names
Insert into <table-name> values(<value1>,...);
Example:
Select (DQL): -
Syntax:-
Example :
Alter command is used to modify the structure of an existing table which may or may not have
data , the alter command has certain limitations.
Syntax;-.
Example
Modifying a Column:
Alter table employee Alter Column empname varchar(25);
Drop (DDL)-
Drop command is used to remove a table from the database.
Syntax:-
Drop table <table-name>;
Example
Virtual Columns: -
Virutal columns defines values which are generated by the system when an sql command is
executed, these values can be selected like any other columns for any table.
example to display the system date in MsSQL.
select GetDate();
select CONVERT(varchar,CURRENT_TIMESTAMP , 106) ;
to display the name and age of all employees in the employee table
select EmpName,Designation,Department , salary, salary*0.1 as HRA, salary*0.25 as DA from
Employee;
Column aliasing - Each column selected from a select query can have a temperory display
name which is known as
column alias , above example 'DA' and 'HRA' are aliased column.
Example:
To select the employee name , department, designation and salary , 10% of salary as HRA ,
25% of salary as DA and sum of HRA,DA and Salary as
netpay from the employee table.
selecting a details of employees from the table in a text mode, ie wishing a merry christmas.:-
Select 'Hello ' +EmpName+' , wish you a merry chirstmas and happy new year' from Employee;
Example-2
Select EmpName + ' is working as ' + Designation + ' in the ' +Department+ ', Department and
his Salary is '+
LTRIM(STR(Salary)) As 'Details ... ' from Employee;
Where Clause :-
Where clause is used to filter a query fetched by any DML /DQL command of SQL.
example :-
To display the Employee Name, Designation and Depratment ,Salary of all Employees with
salary equal or above 5000.
select EmpName, Designation,Department from Employee where Salary >=5000;
To display the Employee Name, Designation and Depratment ,Salary of all Employees born
before 1980.
select EmpName, Designation,Department ,Salary ,DOB from Employee where DOB <
'1-Jan-1980';
To display the Employee Name, Designation and Depratment ,Salary of all Managers born
before 1980.
select EmpName, Designation,Department ,Salary ,DOB from Employee where DOB <
'1-Jan-1980' and Designation='Clerk';
To display the Employee Name, Designation ,Depratment and Salary of all Officers and Clerks.
select EmpName, Designation,Department ,Salary ,DOB from Employee where
Designation='Officer' or Designation='Clerk';
To display the Employee Name, Designation and Depratment ,Salary of all Employee with
salary between 5000 and 8000.
select EmpName, Designation,Department ,Salary ,DOB from Employee where salary>=5000
and salary <=8000;
To display the Employee Name, Designation and Depratment ,Salary of all Employee execpt
clerks and officers.
select EmpName, Designation,Department ,Salary ,DOB from Employee where
Designation<>'Officer' and Designation<>'Clerk';
IN clause:
To Display the details of employees working in Sales,HR and Accounts Department
NOT IN clause
To Display the details of employees not working in Sales,HR and Accounts Department
Like clause:
Like clause is used to search text data using widcard characters (pattern searching in oracle)
NOT Like
Display the details of all employees with empname ending with 'r'
select * from Employee where EmpName like '%r'
Display the details of all employees with "ni" anywhere in the name.
select * from Employee where EmpName like '%ni%'
Display the details of all employees with exactly 3 letters in their name or less than 3.
select * from Employee where EmpName like '___'
IS operator
Syntax:
Update <table-name> set <column-name>=<value>, <column-name>=<value> [where
<criteria-statement>]
example:-
Note :
Update command without a where clause update the details for the entire table.
Delete (DML)
Delete command is used to remove a column from the table, Delete statment without a where
clause removes all rows of a table.
Syn :
Example
Delete the details of Anila
Truncate
Truncate removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such,
Truncate is faster and doesn't use as much undo space as a DELETE.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
Syntax :
Select */<column-name>,.. into <table-name> from <table-name>
Examples
Syntax :
insert into <target-table> select * from <source-table> [where <criteria>];
example -
create table worker(wrk_id number(5),wrk_name varchar(30));
insert into worker (wrk_id,wrk_name) select empno,empname from employee;
IDENTITY COLUMN
Creates an identity column in a table. This property is used with the CREATE TABLE and
ALTER TABLE Transact-SQL statements.
IDENTITY property for an automatically incrementing identification number.
Syntax
IDENTITY [ ( seed , increment ) ]
example
Functions :-
SQL supports two types of functions that is normal functions and aggergate
functions.
Normal functions are similar the built-in functions in other langauges and packages, these
functions
are catogrised into 1)Numeric 2)String and 3) Date functions
Aggergate functions are applied to multiple rows for a table /query examples are
sum(), avg(),count(),min(),max() etc. these functions fetches only one row from a table.
Example
Numeric functions :-
Ceiling() - return the smallest integer value that is not smaller than X.
select ceiling(34.566789) ;
round() -
select round(34.89,0); rounds to integer
select round(56.7891,2);
exp()
SELECT EXP(4) "e to the 4th power" FROM DUAL;
select sin(90);
select cos(90);
select tan(90);
select cot(90);
select radians(90);
select degrees(3);
select asin(-1);
select acos(-1);
select atan(-1);
sign() -returns the sign of the number 1 for +ve numbers , -1 for negative numbers
SELECT SIGN(-100)
rand() -returns a random number for 0.1 to 1,Repetitive calls of RAND() with the same seed
value return the same results.
select rand();
Charcter functions:
Char() -return the charcter equivalent of the ASCII value (1-256) passed as parameter to the
function
SELECT char(67);
NChar() -return the charcter equivalent of the ASCII and supplymentry characters value
(1-65535) passed as parameter to the function
SELECT nchar(1167);
CharIndex(n,m) -returns the first occurence of the character N within the string M.
Select CHARINDEX('llo','Hello')
PatIndex(n,m) -returns the first occurence of the pattern N within the string M.
Select CHARINDEX('%llo%','Hello')
Str(n,m) -Coverts the given expression N to a string data type with width M (optional)
select STR(345,3)
convert all employee names ,department and designation to uppercase in employee table.
update employee set empname=upper(empname), designation=upper(designation),
department =upper(department);
convert all employee names ,department and designation to lower case in employee table.
update employee set empname=lower(empname), designation=lower(designation), department
=lower(department);
to remove both leading and trailing white space from a character value.
select * from employee where ltrim(rtrim(empname))='Sunil Kumar';
Substr() -Returns the sub string of the first parameter string ,starting postion as value defined
and second parameter and the no of characters as value of third parameter
example
select substr('HariNarayanadas',5,6);
Replace() -repalace the output string with the pattern provided as the 3rd parameter as pattern
provided as the 2nd parameter in the string.
syn
select Replace (<string-value>, <pattern-value1>,<pattern-value2>) from <schema>
replaces pattern-value1 with pattern-value2 in the string value.
example
select Replace ('Mangalore City','City','Central') from dual;
Date Functions:-
DateName(interval,d1) -returns the date name in words for date "d1" as per the "interval" .
DatePart(interval,d1) -returns the date part for date "d1" as per the "interval" .
Aggregate Functions:-
Aggregate functions are used to extract the aggergate values from a group of data in a table,
SQL supports
the following aggergate.
Note:-
Only sngle column can be selected , aggergate functions will fetch only a single row from a
table.
example:-
To find the sum of the salary of all employees in the employee table.
select sum(salary) as "total salary" from employee;
select sum(salary) as "total salary" , avg(salary) as "average salary" from employee;
Group By -
Group by clausing is used to display the aggergated columns grouped for a specific
column-value.
example:-
To find the department wise count of employees from the employee table.
select department, count(*) as "Total Employees" from employee group by department
To find the designation wise count of employees from the employee table.
select designation, count(*) as "Total Employees" from employee group by designation
Multiple grouping
To find the departmentwise and designation wise count of employees from the employee table.
select department, designation, count(*) as "Total Employees" from employee group by
department, designation
Order by -
Order by clause is used to sort the query with respect to any column, the column must be
selected in the
select query ,if order by used in conjuction with group by clause order by must follow group by.
examples
select * from employee order by empname;
Display the employee details sorted on department then by deisgnation (within each
deepartment)
select * from employee order by department,designation;
DESC
used in conjuction with order by clause, to sort in the descending order , system will sort
columns on
ascending order by default.
example
select * from employee order by empname desc;
Having clause:-
Having clause is used by queries using aggergate functions , i.e if you want to compare
an aggergate function you must use having instead of where clause
example
to display departmentwise total salary for total salary above 10000.
select department, sum(salary) from employee group by department having sum(salary)
>10000
Sub Queries :-
example
To get the details of all employees with salary lower than that of wilson's , wilson's salary is
unknown.
To display the details of employee drawing the highest and lowest salaries.
To display the department and total salary where total salary is highest.
DISTINCT keyword
DISTINCT keyword is used to identify the unique rows from a query , i.e supress the duplicate
values.
example-
display all departments from the employee table
INTERSECT,UNION keywords
examples
Displays the details all employees working in the departments mentioned in the query, but
will supress duplicate data.
Displays the name & salary of all employees with total salary and summary of salary
as last row.
Note : Intersect,UNION and minus will sort the consolidated queries with respect to the first
column.
so the summary may not display in the last row unless you give the salary as first column.
SQL JOINS
=========
SQL Joins are queries which fetches relational data from two or more independent sql tables
using one or more common common key fields, in oracle the joins are
classied into three namely
1.equi-joins /inner-joins
2. outer joins
left outer joins
right outer joins
full other joins
3. self-joins
equi joins:-
Display the data if the data is exists in both tables , it is also known as simple inner joins.
create a table personal which stores an extension of the data of the employees
such as spouse, qualification and bank account number
select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee inner join personal on employee.empno=personal.empno;
Outer Joins
Displays all the data of the first table but only the matching data of the second table
example:
select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee left outer join personal on
employee.empno=personal.empno;
Works excatly opposite of left outer joins i.e Displays all the data of the second table but only
the matching data of the first table
select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee right join personal on employee.empno=personal.empno;
Full outer joins is a unioin of both left and right outer joins , i.e Displays all the data of both
tables.
select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee full join personal on employee.empno=personal.empno;
4. Self -Joins
self joins are used to join the single table to itself in some cases like
INDEXES :-
An index is database object assoicated with a table or a cluster, that helps to increase the data
access speed . By creating an index on one or more columns of a table, you can fetch the data
from randomly distributed rows.Indexes are one of many means of reducing disk I/O .If a table
has no indexes, then the database must perform a full table scan to find a value. A index stores
the column value with a pointer to the location of the correspoding row in the physical storage ,
which a select query is executed with the respective column in the where clause the system
looks the index table identifies the row pointer for the physical location and fetech the row
details . the function is similar to a normal index page given at the begining of any big reference
book which helps a reader to move to the required topic by identifying the page number from the
index page.
Syntax :
example:-
Deleting an Index
Syn:
Drop index <index-name>
Example:
Drop index emp1_index;
Unique Indexes - Unique index on a table allows only unique values to be entered for each row
of the table for the mentioned column.
example
create UNIQUE INDEX emp_idx on employee(empno);
once a unique index is created you cannot duplicate the key colum value in the table ,unique
index cannot be created if duplicate values for the keycolumns,already exists in the table.
Clusters:-
-----------
A cluster is a database object that contains data from one or more tables, all of which have one
or more columns in common.
Oracle Database stores together all the rows from all the tables that share the same cluster key.
Creating a cluster
Syntax:
Create Cluster <clustername> (<column-name>(<data-type>) [sort])
example:
Create Cluster inventory (itemcode number(5));
Indexing a cluster:
Create Index idx_iventory on CLUSTER inventory;
Data Constraints:-
=============
The constraint are rules that restrict the values for one or more columns in a table. The Oracle
Server uses constraints to prevent invalid data entry into tables.
Note : the first 4 constraints are also know as entity constraints (column-level) and the 5th one is
known as
referencial constraint
The primary key is a single field or combination of fields that uniquely defines a record. The not
null constraint is part of the primary key. A table can have only one primary key.
example:-
Note : now for the above table duplicates or blank values for the column empno will not be
allowed. A primary key can be added for the column of any existing table provided the existing
data in the table does not have a
duplicate values for empno.
Check constraint: The check constraint allows you to specify a condition on each row in a table.
The not null constraint means the column contains no null values. The columns without the NOT
NULL constraint can contain null values by default.
Unique Constraint:
The unique constrain means no row value repeat again. The unique constraint is a part of the
primary key.
Note : combination of unique and not null constraints produces the same affect of a primary
key, but system
internally creates index for a primary key which will not happen in case of an UNIQUE NOT
NULL constraint
and primary key can be applied only for one column of the table.
example:
All the above defined cnstraints are column level constraints, a table level constraint is defined
for setting
the integrity rules on the data linking one or more columns of the tables.
Composite Key :
Compostie Key is same as primary key but involves two or more columns of the table as follows
In the above case system allows duplicate values for empname as well as dept , but not for the
combination.
i.e one employee cannot exists in multiple department.
The foreign key constraint and references constraint is a same. A foreign key constraint means
that values in one table must also appear in another table. The referenced table is called the
parent table while the table with the foreign key is called the child table. The column refered in
the parent table by the foreign key column must be primary key of the parent table.
example:
create table product_purchase
(
pur_no number(5),
pur_date date,
pur_qty number(5),
pur_rate number(7,2)
prod_no number(5) Constraint fk_prodno references product_master(prod_no);
);
Note: only table name need to be mentioned in the reference clause if column names in both
tables
are identical
Note:- now you cannot delete both customer and product tables from the database unless you
delete
the purchase table, similary you cannot delete the table rows from customer or product if the
respective
prod_no or cust_no is used in the purchase table.
On Delete Cascade:
Usally system will not allow to delete a row from the master table if the primary key column
value is
used in the child table, you must remove on the dependent rows from the child table before
removing
the row from the master table. in case if you set ON DELETE CASCADE rule for the foreign key
constraint
and if any row from parent table is deleted all dependent rows the the child table will be
automatically deleted
Note :-
Naming a constraint is not mandatory in oracle, if name is not specified system will generate
an internal
name for the constraint which can be identified by running the query
VIEWS
======
A view is a predefined, named query stored in the database. Once created, views can be
queried in much the same way that tables can be queried.
Views contain rows and columns like tables do. Views are also known as virtual tables.
Syntax:
Create or replace [FORCE] view <view-name> As <query-statement> [WITH READ ONLY
][With Check Option]
Restrictions:-
Updateable Views:-
1. An updatable view is one you can use to insert, update, or delete base table rows.
2. A DISTINCT operator, An aggregate function, A collection expression in a SELECT list, A
subquery in a SELECT list, A subquery designated WITH READ ONLY
3. for a join view to be updatable, then all of the following conditions must be true:
a.The DML statement must affect only one table underlying the join.
b.For an INSERT/Update statement, the view must not be created WITH CHECK
OPTION, and all columns into which values are inserted must come from a primary key table.
Examples
note:-
The above created view is updatable , you can update any row in the view as follows
Create or replace view empv2 as select * from employee where department='Production' WITH
READ ONLY;
it will allow an insert or update in the table only if the new row matches the criteria given on view
creation.
Create or replace view empv3 as select * from employee where department='production' WITH
CHECK OPTION;
For the above view you can insert /update the details of employees for production department in
the employee table;
FORCE View
Normal views can be created only for existing tables, FORCE VIEW allows users to create view
on a table even if the table is
non existant but the query can be performed using the view only after the table creation.
Note:
Dropping the table or a parent view from the database will not delete the views dependent on
those tables/parent views.
Deleting a view
Note :
the Employee Name and Salary can be updated or inserted in the view , HRA,DA and Gross
are read-only.
Delete command applied on a view without a where clause will delete the table data. In such
case to avoid such deletions
create the view WITH CHECK OPTION. but check options will allow to insert new rows into the
view.
Commit - Updates all the modified transactions to the physical storage system. If autocommit
feature is set for the application commits automatically
rollback - Cancels all the recent chages made the the logical data structure , a rollback can be
performed before a commit.
savepoint -multiple savepoints can be set by the developer within a single session for a
collection of statements executed. rollback to
a save point will undo all actions performed by the user in the database for 1 hour.
example:-
uncheck the autocommit option in the editor and try to insert a few rows as follows
select * from employee; (all the above rows will be availble in the table)
rollback;
select * from employee; (all the above rows will not be availble in the table,insert action is
cancelled)
SAVEPOINT:-
insert into employee values(103,'Padma','clerk','accounts',4000,'1-jan-1972','1-mar-1998');
savepoint s1;
insert into employee values(104,'Rakesh','officer','sales',4500,'1-jan-1967','1-mar-1996');
insert into employee values(105,'Deepak','manager','production',4000,'1-jan-1972','1-mar-1998');
savepoint s2;
insert into employee values(106,'Anotony','Faculty','CS',4500,'1-jan-1967','1-mar-1996');
insert into employee values(107,'Thanzeer','Faculty','CS',4000,'1-jan-1972','1-mar-1998');
savepoint s3;
insert into employee values(108,'Sudessh','Faculty','CS',4500,'1-jan-1967','1-mar-1996');
rollback to s3;
select * from employee (only the last row insertion is cancelled, i.e transaction till savpoint s3)
rollback to s1;
select * from employee (till the first row insertion is cancelled, i.e transaction till savpoint s1)
DCL commands are used to enforce database security in a multiple user database environment.
Two types of DCL commands are GRANT and REVOKE.
Only Database Administrator's or owner's of the database object can provide/remove privileges
on a database object.
GRANT - is a command used to provide access or privileges on the database objects to the
users.
Syntax
privilege_name is the access right or privilege granted to the user. Some of the access rights
are ALL, EXECUTE, and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
PUBLIC is used to grant access rights to all users. ROLES are a set of privileges grouped
together.
WITH GRANT OPTION - allows a user to grant access rights to other users.
Example:
WITH GRANT OPTION - if this option is suffixed with the command then the user receving the
permission can GRANT SELECT privilege on employee table to another user, Later, if you
REVOKE the SELECT privilege on employee from receving user, still other user will have
SELECT privilege on employee table.
REVOKE -The REVOKE command removes user access rights or privileges to the database
objects.
Syntax
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}
This command will REVOKE a SELECT privilege on employee table from sudhir and will not be
able to SELECT data from that table anymore.
However,
1) if the user has received SELECT privileges on that table from more than one users, he/she
can SELECT from that table until everyone who granted the permission revokes it.
2) You cannot REVOKE privileges if they were not initially granted by you.
Privileges: Privileges defines the access rights provided to a user on a database object. There
are two types of privileges.
1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or
DELETE data from database objects to which the privileges apply.
Roles:
Roles are a collection of privileges or access rights. When there are many users in a database it
becomes difficult to grant or revoke privileges to users.
Therefore, if you define roles, you can grant or revoke privileges to users, thereby automatically
granting or revoking privileges. You can either create Roles or use the system roles pre-defined
by oracle.
Some of the privileges granted to the system roles are as given below:
Creating Roles:
Syntax :
Example: To create a role called "developer" with password as "pwd",the code will be as
follows
It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a
privilege directly to every user.
If a role is identified by a password, then, when you GRANT or REVOKE privileges to the role,
you definitely have to identify it with the password.
For example: To grant CREATE TABLE privilege to a user by creating a testing role:
Second, grant a SELECT,INSERT,UPDATE privilege to the ROLE testing. You can add more
privileges to the ROLE.
To Delete a Role:
Syntax
DROP ROLE role_name;
example
The above will have to wait to be performed till sudhir executes a commit/rollback on his
session.
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects and used while granting access
to an object from another schema and to avoid users worry about knowing which schema owns
the object.
Syntax
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];
1) PUBLIC means that the synonym is a public synonym and is accessible to all users.
2) User must first have the appropriate privileges to the object to use the synonym.
Example:
CREATE PUBLIC SYNONYM worker FOR employee;
Removing a synomym:
example
DROP PUBLIC SYNONYM emp_table;
Note : FORCE option will force Oracle to drop the synonym even if it has dependencies
Snapshots:
Oracle uses snapshots, sometimes referred to as materialized views, to meet the requirements
of delivering data to non-master sites in a replicated environment and caching
"expensive" queries from a data warehouse.
Snapshot types:
Primary Key -
Primary key snapshots are considered the normal (default) type of snapshot. Primary key
snapshots are updateable if the snapshot has been created with "FOR UPDATE" was specified
when defining the snapshot. Changes are propagated according to the row changes as
identified by the primary key value of the row (vs. the ROWID). The SQL command for creating
an updateable, primary key snapshot might look like:
Partitioned Tables:-
Now a days enterprises run databases of hundred of Gigabytes in size. From Oracle Ver. 8.0
Oracle has provided the feature of
table partitioning i.e. you can partition a table according to some criteria .
For example you have a SALES table containing millions of records, but all the records belong
to four years only i.e. 1991, 1992, 1993
and 1994. And most of the time you are concerned about only one year i.e. you give queries
like the following
Now whenever you give queries like this Oracle will search the whole table. If you partition this
table according to year, then the performance is improve since oracle will scan only a
single partition instead of whole table.
Range Partitioning:-
Hash partitioning:-
Hash partitioning provides a method of evenly distributing data across a specified number of
partitions. Rows are mapped into partitions based on a hash value of the partitioning key
CREATE TABLE products (partno NUMBER, description VARCHAR2 (60))
PARTITION BY HASH (partno)
PARTITIONS 4
STORE IN (tab1, tab2, tab3, tab4);
List Partitioning:-
Use list partitioning when you require explicit control over how rows map to partitions. You can
specify a list of discrete values for the partitioning column in the description for each partition.
Create table customers (custcode number(5), Name varchar(20), Addr varchar2(10,2), City
varchar2(20), Bal number(10,2))
Partition by list (city),
Partition north_India values (‘DELHI’,’CHANDIGARH’),
Partition east_India values (‘KOLKOTA’,’PATNA’),
Partition south_India values (‘HYDERABAD’,’BANGALORE’, ’CHENNAI’),
Partition west India values (‘BOMBAY’,’GOA’);