Nothing Special   »   [go: up one dir, main page]

14 - SQL 12 - NEW

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

II PUC Computer Science Unit C Chapter 14 SQL Commands

SQL Commands 7marks (2+5)

SQL (Structured Query Language)


 It is a language of database for storing, manipulating and retrieving data stored
in relational database.
 SQL is a standard language for relation database system.
 SQL is an ANSI (American National Standards Institute) standard.
 Oracle, Sybase, MS-SQL server use SQL as standard database language.

SQL allows users to


 Create and drop database and tables.
 Define the data in database and manipulate that data.
 To describe data.
 Access data in relational database.
 Create view, functions, and stored procedures.
 Set permissions on tables, views.

History
 1970-E.F. Codd of IBM known as father of relational database, described
relational model of database.
 1974- SQL developed.
 1978- IBM released a product System/R.
 1986- IBM first developed prototype of relational database. The first relational
database was released by relational software and later it became oracle.

SQL architecture

Diagram: SQL Architecture


Query language processor: The Query Processor is a Structured Query
Language (SQL) parser, optimizer, and query execution engine. The Query
Processor accepts and executes SQL commands according to a chosen plan and
interacts with the Enterprise Database Server storage engine to return the expected
results.
DBMS engine: A database engine (or storage engine) is the underlying software
component which involves file manager and transaction manager.

Dept. of Computer Science, SAIPUC, Shivamogga 1


II PUC Computer Science Unit C Chapter 14 SQL Commands

Physical database: This contains the actual data in the form of rows and columns.

Query dispatcher: The function of the dispatcher is to route the query request to either
CQE (Classic Query Engine) or SQE (SQL Query Engine), depending on the attributes of
the query. All queries are processed by the dispatcher. It cannot be bypassed.

Optimization engines: The optimization engine attempts to determine the most


efficient way to execute a given query by considering the possible query plans.

Classic Query Engine (CQE): The CQE processes queries originating from non-SQL
interfaces.

SQL Query Engine (SQE): SQE processes queries such as ODBC, JDBC.

DBMS software details:


MySQL:
 It is an open source SQL database, developed by Swedish company MySQL AB.
 MySQL is supported by many platforms like Windows, major distributions of
Linux, Mac OS x.
 MySQL has both free and paid version based on user requirement (commercial
and non commercial) and features.
 MySQL comes with a very fast, multi threaded, multi user and robust SQL
database server.
Features of MySQL:
 High performance.
 Scalability and flexibility.
 Robust transactional support.
 Web and data warehouse strengths.
 Strong data protection.
 Comprehensive application development.

MS SQL Server:
 MS SQL Server is a relational database management system developed by
Microsoft.
 Its primary languages are T-SQL and ANSI SQL.
Features of MS SQL Server:
 High performance.
 Database mirroring.
 Database snapshots.
 DDL triggers.
 XML integration.

Oracle:
 It is a very large and multi user relational database management system
developed by oracle corporation.
 Oracle supports all major operating systems for both clients and servers.
Features of oracle:
 Portability.
 Resource manager.

Dept. of Computer Science, SAIPUC, Shivamogga 2


II PUC Computer Science Unit C Chapter 14 SQL Commands

 Data warehousing.
 Table compression.
 Data mining.

Microsoft access:
 It is the most popular database management software developed by Microsoft.
 It is inexpensive and powerful database for small scale projects.
 MS access uses the JET database engine for its operations.
 MS access is available with the popular MS office package.
Features of MS access
 User can create tables, queries, forms and reports using macros.
 Data can be imported and exported.
 MS Access does not implement database triggers, stored procedures.
 It is based on JET database engine.

SQL commands
Command is a predefined word used to interact with relational databases.
SQL commands are classified into
a) Data Definition Language (DDL)
b) Data Manipulation Language (DML)
c) Data Control Language (DCL)
d) Data Query Language (DQL)

a) Data Definition Language (DDL)


 DDL defines the conceptual schema providing the link between the logical and
physical structure of the database.
 The logical structure of a database is a schema.
 A subschema is the way a specific application views the data from the database.

The functions of DDL


 Defines field’s data type, length, name, relationship.
 Describes schema and sub schema.
 Provides data security.
 Indicates keys of the records.
 Groups related records or fields.
 Provides logical and physical data independence.

DDL commands are as follows


Command Description
CREATE Creates a new table, a view of a table, or other object in database.
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in the database.

b) Data Manipulation Language (DML)


These commands provide data manipulation techniques like insertion, deletion,
update, modification.

Dept. of Computer Science, SAIPUC, Shivamogga 3


II PUC Computer Science Unit C Chapter 14 SQL Commands

The functions of DML


 DML facilitates use of relationship between the records.
 DML enables the user and application program to be independent of physical
data structure.
 These commands provide data manipulation techniques like insertion, deletion,
update, modification.

DML commands are as follows


Command Description
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records

c) Data Control Language (DCL)


Data Control Language (DCL) is used to control privilege in Database.

DCL commands are as follows


Command Description
GRANT Gives a privilege to user.
REVOKE Takes back privileges granted from user.

d) Data Query Language (DQL)


The SELECT statement is used to select or retrieve data from a database.
Command Description
SELECT Retrieves certain records from one or more tables.

Data types in SQL


 SQL data type is an attribute that specifies type of data of any object.
 Data types are used during table creation to indicate the type of data to be
stored.

SQL has following categories of data types

a) Exact numeric data types


Data type From To
int -2,147,483,648 2,147,483,647
numeric -10^38 +1 10^38 –1

b) Floating point numeric data types


Data type From To
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38

c) Date and time data types


Data type From To
datetime January 1, 1753 December 31, 9999
date Stores a date like march 26 2014
time stores a time of day like 12:30 P.M.

Dept. of Computer Science, SAIPUC, Shivamogga 4


II PUC Computer Science Unit C Chapter 14 SQL Commands

d) Character, string data types


Data type Description
char(n) Maximum 8,000 characters (Fixed length)
varchar(n) Maximum 8,000 characters (variable length)

Operators in SQL
An operator is a reserved word or a character used in an SQL statement to
perform operations, such as comparisons and arithmetic operations.

Types of operators
a) Arithmetic operators.
b) Comparison operators.
c) Logical operators.
d) Operators used to negate conditions.

Let a=10 and b=20

a) Arithmetic Operators:

Operator Description Example


+ Addition - Adds values on either side of the operator a + b will give 30
Subtraction - Subtracts right hand operand from left a - b will give -10
-
hand operand
Multiplication - Multiplies values on either side of the a * b will give 200
*
operator
Division - Divides left hand operand by right hand b / a will give 2
/
operand
Modulus - Divides left hand operand by right hand b % a will give 0
%
operand and returns remainder

b) Comparison Operators:

Operator Description Example


Checks if the values of two operands are equal or not, if yes then (a = b) is not
= condition becomes true. true.
Checks if the values of two operands are equal or not, if values are (a != b) is
!= not equal then condition becomes true. true.
Checks if the values of two operands are equal or not, if values are (a <> b) is
<> not equal then condition becomes true. true.
Checks if the value of left operand is greater than the value of right (a > b) is not
> operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (a < b) is
< operand, if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to the (a >= b) is
>= value of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than or equal to the value of (a <= b) is
<= right operand, if yes then condition becomes true. true.

Dept. of Computer Science, SAIPUC, Shivamogga 5


II PUC Computer Science Unit C Chapter 14 SQL Commands

Checks if the value of left operand is not less than the value of right (a !< b) is
!< operand, if yes then condition becomes true. false.
Checks if the value of left operand is not greater than the value of (a !> b) is
!> right operand, if yes then condition becomes true. true.

c) Logical Operators:

Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
The AND operator allows the existence of multiple conditions in an SQL statement's
AND
WHERE clause.
The ANY operator is used to compare a value to any applicable value in the list
ANY
according to the condition.
The BETWEEN operator is used to search for values that are within a set of values,
BETWEEN
given the minimum value and the maximum value.
The EXISTS operator is used to search for the presence of a row in a specified table
EXISTS
that meets certain criteria.
The IN operator is used to compare a value to a list of literal values that have been
IN
specified.
The LIKE operator is used to compare a value to similar values using wildcard
LIKE
operators.
The NOT operator reverses the meaning of the logical operator with which it is used.
NOT
Example: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
The OR operator is used to combine multiple conditions in an SQL statement's
OR
WHERE clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
The UNIQUE operator searches every row of a specified table for uniqueness (no
UNIQUE
duplicates).

SQL expressions
 SQL expressions are like formula and they are used in query language.
 An SQL expression is a combination of one or more values, operators, and SQL
functions that evaluate to a value.
Basic syntax: select column1, column2,……….. column n from
table_name where [condition | expression]

SQL has following expressions


a) Boolean expressions
b) Numeric expressions
c) Date expressions

a) Boolean expressions: These expressions fetch the data on the basis of matching single
value.
Syntax: select column 1, column 2, column n from table_name
where single_value_matching_expression;

Example: select * from employee where salary = 10000;

Dept. of Computer Science, SAIPUC, Shivamogga 6


II PUC Computer Science Unit C Chapter 14 SQL Commands

b) Numeric expressions: This expression is used to perform any mathematical operation in


any query.
Syntax: select numerical_expression as operation_name [from
table_name where condition];
Here numerical_expression is used for mathematical expression

Example 1: select (15+6) as addition


Output: addition
21

Example 2: select count (*) as ‘Records’ from student;


Output: Records
10

c) Date expression: Date expression returns current system date and time values.
Example: select current_timestamp;
This returns current date and time

SQL Constraints
 Constraints are the rules enforced on data columns or tables.
 These are used to limit the type of data that can go into a table.
 This ensures the accuracy and reliability of the data in the database.

Constraints could be
a) Column level
b) Table level
a) Column level constraints
 These are the constraints which are specified immediately after the column
definition.
 Column level constraints are applied only to the columns.
b) Table level constraints
 These are the constraints which are specified after all the columns are defined.
 Table level constraints are applied to the whole table.
Following are the commonly used constraints in SQL
a) Not NULL
b) Unique
c) Check
d) Primary key
e) Foreign key

a) NOT NULL Constraint: This constraint ensures all rows in the table contain a definite
value for the column which specified as “NOT NULL”. (This means NULL vales are not
allowed).

Syntax:
[CONSTRAINT constraint_name] NOT NULL

Dept. of Computer Science, SAIPUC, Shivamogga 7


II PUC Computer Science Unit C Chapter 14 SQL Commands

Example:
create table std
(
stdid int CONSTRAINT STD_ID_NN NOT NULL,
sname varchar2 (20),
total int
)

b) UNIQUE Constraint: This constraint ensures that a column or a group of columns in


each row have a distinct value.
Syntax (column level): [CONSTRAINT constraint_name] UNIQUE

Example 1 (column level):


create table std
(
stdid int CONSTRAINT STDID_UNQ UNIQUE,
sname varchar2 (20),
total int
)

Syntax (table level):


[CONSTRAINT constraint_name] UNIQUE (column_name);

Example 2 (table level):


create table std
(
stdid int,
sname varchar2 (20),
total int,
CONSTRAINT STDID_UNQ UNIQUE (stdid)
)

c) CHECK Constraint: The CHECK constraint is used to define a rule, condition to columns
which limits the value range that can be placed in columns.

Syntax: [CONSTRAINT constraint_name] CHECK (condition)

Example:
create table std
(
stdid int,
sname varchar2 (20),
total int check (total > 0)
)

d) PRIMARY KEY Constraint: The PRIMARY KEY constraint defines a column or combination
of columns which uniquely identifies each record in a database table.

Syntax: Primary key at column level


column_name data_type [CONSTRAINT constraint_name]
PRIMARY KEY

Dept. of Computer Science, SAIPUC, Shivamogga 8


II PUC Computer Science Unit C Chapter 14 SQL Commands

Example 1:
create table std
(
stdid int CONSTRAINT stdid_pk primary key,
sname varchar2 (20),
total int
)
Example 2:
create table std
(
stdid int primary key,
sname varchar2 (20),
)
Syntax: Primary key at table level
[CONSTRAINT constraint_name] primary key (column1,
column2….)
Example 1:
create table std
(
stdid int,
sname varchar2 (20),
total int,
primary key(stdid)
)
Example 2:
create table std
(
stdid int,
sname varchar2 (20),
total int,
CONSTRAINT std_id primary key(stdid, sname)
)
e) FOREIGN KEY Constraint: This constraint identifies any column referencing the primary
key in another table.
Syntax: Foreign key at column level
[CONSTRAINT constraint_name] foreign key REFERENCES
referenced_table_name (column_name)
Example:
create table std
(
stdid int primary key,
sname varchar2 (20),
total int
)

create table course


(
stdid int CONSTRAINT std_fk foreign key references
std(stdid),
cid int,
cname varchar2(20)
)

Dept. of Computer Science, SAIPUC, Shivamogga 9


II PUC Computer Science Unit C Chapter 14 SQL Commands

Syntax: Foreign key at table level


[CONSTRAINT constraint_name] foreign key (Column1,
column2,….) REFERENCES referenced_table_name (column_name)

Implementation of SQL commands


1) Data Definition Language commands
a) create command: This command is used to create tables.
Syntax:
create table table_name
(
column1 datatype,
column2 datatype,
column3 datatype,
.....
column N datatype,
primary key (one or more columns)
);

Example:
create table std
(
stdid int,
sname varchar(20),
total int
)

b) alter command: This command is used to change the structure of the table, like to
add new field, to change the data type of the field.

Syntax 1: To add a new column to a table is as follows: (Oracle 10g)


alter table table_name add (column_name datatype);

Example 1:
alter table ebill add (bill_amt float, due_date date);

Syntax 2: to change the data type of a column in a table. (Oracle 10g)


alter table table_name modify (column_name datatype);

Example 2:
alter table customer modify (caddress varchar2 (150));

C) drop command: This command is used to remove table definition and all data,
indexes, triggers, constraints and permission specification for that table.
Syntax: drop table table_name;

Example: drop table std;

2) Data Manipulation Language commands:


a) insert command: This command is used to add rows (tuples) to the table.

Dept. of Computer Science, SAIPUC, Shivamogga 10


II PUC Computer Science Unit C Chapter 14 SQL Commands

Syntax 1: To add values only to selected columns.


insert into table_name(column1,column2,column3,...column N)
values (value 1, value 2, value 3,...value N);

Example 1:
insert into customers (ID,NAME) values (1, 'Ramesh');

Syntax 2: To insert values for all columns.


insert into table_name
values (value 1, value 2, value 3 ,...value N );

Example 2:
insert into customers
values (7, 'ramesh', 24, 'Indore', 10000 );

Syntax 3: To insert values into one table using another table:


insert into first_table_name [(column1, column2, ... column N)]
select column 1, column 2, ... column N
from second_table_name [where condition];

Example 3:
insert into student1 (regnum, total) select regnum, total
from stdmaster where class=’1PUC’;

b) update command: The SQL UPDATE Query is used to modify the existing records in a
table.
Syntax: update table_name set column1 = value1, column2 =
value2...., column n = value n where condition;

Example: update customers set address = 'pune'


where id = 6;

c) delete command: This command is used to delete rows from a table based on
condition
Syntax: delete from table_name where condition;

Example: delete from std where avg <= 35;

3) Data Query Language commands:


a) select command:
 SQL SELECT statement is used to fetch the data from a database table which
returns data in the form of result table.
 The result tables obtained by select command are called as result sets.

Syntax1: To selects few columns from the table.


select column 1, column 2, column N from table_name
where condition;

Example1:
select id, name, salary from customers where salary >
20000;

Dept. of Computer Science, SAIPUC, Shivamogga 11


II PUC Computer Science Unit C Chapter 14 SQL Commands

Syntax2: To select all the records from the table


select * from table_name;
Example2: select * from std;

where clause:
 SQL where clause is used to specify a condition while fetching data from
database.
 It is also used with update, delete commands to specify a condition.
Syntax of where clause with select command:
select column 1, column 2, column N from table_name where
condition;

Example:
select id, name, salary from customers where salary > 20000;

AND operator: The AND operator allows the use of multiple conditions in an SQL
statement and statement is executed if all conditions are true.
Syntax: select column 1, column 2, column N from
table_name where condition1 and condition2... and
condition N;

Example: select id, name, salary from customers where


salary > 2000 and age < 25;

OR operator: The OR operator is used to combine multiple conditions in SQL statement


and statement is executed if any one condition is true.
Syntax: select column 1, column 2, column N from
table_name where condition 1 or condition 2 ....... or
condition N

Example: select id, name, salary from customers where


salary > 2000 or age < 25;

order by clause: The SQL ORDER BY clause is used to sort the data in ascending or
descending order, based on one or more columns.
Syntax:
select column-list
from table_name
[where condition ]
order by column1, column2, .. column n [asc | desc];
Example 1: select * from customers order by name, salary;
Example 2: To sort the result in descending order by NAME:
select * from customers order by name desc;

group by: The SQL GROUP BY clause is used in collaboration with the SELECT
statement to arrange identical data into groups.

Dept. of Computer Science, SAIPUC, Shivamogga 12


II PUC Computer Science Unit C Chapter 14 SQL Commands

Syntax:
select column1, column2
from table_name
where [ conditions ]
group by column1, column2
order by column1, column2

Example: select name, sum (salary) from customers group


by name;

Difference between order by and group by with example.


Order by Group by
The SQL ORDER BY clause is used to sort The SQL GROUP BY clause is used in
the data in ascending or descending order, collaboration with the SELECT statement to
based on one or more columns. arrange identical data into groups.
The ORDER BY keyword sorts the records No default value
in ascending order by default.
No need to follow conditions in where The GROUP BY clause must follow the
clause conditions in the WHERE clause
Can be used without group by The GROUP BY clause must precede the
ORDER BY clause if one is used.
Syntax: select column-list from Syntax: select column1, column2 from
table_name where condition order by table_name where [ conditions ] group by
column1, column2, .. column n [asc | column1, column2
desc]; order by column1, column2

Group functions in SQL : Group functions are built-in SQL functions that operate on
groups of rows and return one value for the entire group.
SQL group functions are
a) count( )
b) distinct( )
c) max( )
d) min( )
e) avg( )
f) sum( )

a) count ( ): This function returns the number of rows in the table that satisfies the
condition.

Example: 1) select count (*) from employee where dept = 'electronics';


2) select count (*) from employee;

b) distinct( ): This function is used to select the distinct rows.


Example: select distinct ename from employee;

c) max ( ): This function is used to get the maximum value from a column.
Example: select max (salary) from employee;

Dept. of Computer Science, SAIPUC, Shivamogga 13


II PUC Computer Science Unit C Chapter 14 SQL Commands

d) min ( ): This function is used to get the minimum value from a column.
Example: select min (salary) from employee;

e) avg ( ): This function is used to get the average value of a numeric column.
Example: select avg (salary) from employee;

f) sum ( ): This function is used to get the sum of a numeric column.


Example: select sum (salary) from employee;

Distinct keyword: It is used along with select statement to eliminate duplicate


(repeated) records to fetch unique records.

Syntax: select distinct column1, column2, ...from table_name where condition;

Example: select distinct ename from employee;

NULL keyword: NULL is the term used to represent a missing value. NULL values in table
appears to be blank.
Syntax with create command:
create table table_name
(
column_name data_type CONSTRAINT constraint_name NOT NULL,
column_name data_type
)
Example: select * from employee where phone is NULL;

Rename command: This command is used to give another name for a existing table.
Syntax: rename old_table_name to new_table_name
Example: rename employee to new_employee

Views
 In SQL, a view is a virtual table based on the result-set of SQL statement.
 Views can be created from a single table, multiple tables.
 To create a view a user must have appropriate system privilege.
Syntax: create view view_name as select column1, column2.....
from table_name where condition;

Example: createview customers_view as select name,


age from customers;

Commit command:
 The commit command is the transactional command used to save changes
invoked by a transaction to the database.
 The commit command saves all transactions to the database since the last
commit or rollback command.
Syntax: commit;
Example: commit;

Dept. of Computer Science, SAIPUC, Shivamogga 14


II PUC Computer Science Unit C Chapter 14 SQL Commands

Rollback Command:
 The rollback command is the transactional command used to undo transactions
that have not already been saved to the database.
 The rollback command can only be used to undo transactions since the last
commit or rollback command was issued.
Syntax: rollback;
Example: rollback;

DCL commands: DCL commands are used to enforce database security in a multiple
user database environment. Only database administrators can provide and remove
privileges.

a) Grant Command: SQL grant is a command used to provide access or privileges on


the database objects to the users.
Syntax:
grant privilege_name
on object_name
to {user_name |public |role_name}
[with grant option];

 privilege_name is the access right or privilege granted to the user.


 object_name is the name of an database object, like table.
 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: grant select on employee to user1;

b) REVOKE Command: 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}

Example: revoke select on employee from user1;

Privileges and Roles: Privileges define 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.

Dept. of Computer Science, SAIPUC, Shivamogga 15


II PUC Computer Science Unit C Chapter 14 SQL Commands

Few create system privileges are listed below:


System Privileges Description
CREATE object Allows users to create the specified object in their own schema.
CREATE ANY object Allows users to create the specified object in any schema.
The above rules also apply for ALTER and DROP system privileges.

Few of the object privileges are listed below:


Object Privileges Description
INSERT Allows users to insert rows into a table.
SELECT Allows users to select data from a database object.
UPDATE Allows user to update data in a table.
EXECUTE Allows user to execute a stored procedure or a function.

Roles: Roles are a collection of privileges or access rights. Some of the privileges
granted to the system roles are as given below:
System Role Privileges Granted to the Role
CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE
SEQUENCE, CREATE SESSION etc.
RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE
TRIGGER etc. The primary usage of the RESOURCE role is to restrict
access to database objects.
DBA ALL SYSTEM PRIVILEGES

Dual table in oracle


 The DUAL table is a special one-row, one-column dummy table present by
default in Oracle and other database installations.
 This is used to perform mathematical calculations without using a table.
Example: select 6*6 from dual;

SQL built-in functions


There are two types in SQL built-in functions
1) Single row functions (scalar functions)
2) Group function

1) Single row functions: Single-row functions return a single result row for every row of a
queried table or view.
There are four types of single row functions
a) Numeric functions
b) Character or text functions
c) Date functions
d) Conversion functions

Dept. of Computer Science, SAIPUC, Shivamogga 16


II PUC Computer Science Unit C Chapter 14 SQL Commands

a) Numeric function
Numeric functions accept numeric input and return numeric values.
Name Description Example Value
abs() Returns the absolute value of numeric expression. abs(-10) 10
ceil(x) Returns the smallest integer value that is not less than x ceil(1.6) 2

floor(x) Returns the largest integer value that is not greater than x floor(1.3) 1
round() Returns numeric expression rounded to an integer. Can round(23.764,2) 23.76
be used to round an expression to a number of decimal
points
trunc() Returns numeric exp1 truncated to exp2 decimal places. If trunc(5.79,1) 5.7
exp2 is 0, then the result will have no decimal point.

b) Character or text functions


Character functions works on characters and return character and numeric values.
Name Description Example Value
lower(string_value) string_value is converted to lowercase lower(‘ABC’) abc
upper(string_value) string_value is converted to uppercase upper(‘abc’) ABC
ltrim(string_value, trim_text is removed from the left of ltrim(‘good’,’g’) ood
trim_text) string_value
rtrim(string_value, trim_text is removed from the right of rtrim(‘good’,’d’) goo
trim_text) string_value
trim(trim_text FROM trim_text is removed from both side of trim(‘g’ from ood
string_value) string_value ‘good morning’) mornin
substr(string_value, m, n) Returns n number of characters from substr(‘abc’,2,1) b
string_value starting from m position
length(string_value) Number of characters in string_value is length(‘abc’) 3
returned
lpad(string_value, n, Returns the string_value left padded lpad(‘abc’,5,’*’) **abc
pad_value) with pad_value. The length of whole
string will be of n characters.
rpad(string_value, n, Returns the string_value right padded rpad(‘abc’,5,’*’) abc**
pad_value) with pad_value. The length of whole
string will be of n characters.
initcap(string_value) First letter in string_value is converted initcap(‘abcd’) Abcd
to uppercase.

Dept. of Computer Science, SAIPUC, Shivamogga 17


II PUC Computer Science Unit C Chapter 14 SQL Commands

c) Date functions: These functions works on date related values.


Name Description
add_months(date, n) Adds n months to date
months_between(x1,x2) Returns number of months between x1 and x2
next_day(x, week_day) returns the next date of the week_day on or after the date x
last_day(d) returns the date of the last day of the month that contains d.
Returns the date x rounded off to the nearest value specified by
round(x, date_format)
date_format
Returns the date less than or equal to the date x. date_format
trunc(x, date_format)
specifies year or month or day
Returns the date and time in zone2 if date x represents time ,date
new_time(x,zone1,zone2)
in zone1
SYSDATE Returns the systems current date and time

Name example Value


add_months(date, n) add_months(‘1-jan-2018’,2) 01-mar-18
months_between(‘1-mar-2000’, ‘1-jan-
months_between(x1,x2) 2
2000’)
next_day(x, week_day) next_day(‘28-jun-2016’,’thursday’) 30-jun-16
last_day(d) last_day(‘’28-jun-2016’) 30-jun-16
select round (to_date ('27-oct-16'),'year') New_year
round(x, date_format)
"new_year" from dual 01-JAN-17
select trunc(to_date('27-dec-92','dd- New Year
trunc(x, date_format) mon-yy'), 'year')
"new year" from dual; 01-JAN-92

select new_time('25-jan-16','gmt','pst') New Date


new_time(x,zone1,zone2)
"new date and time" from dual; 24-JAN-16
NOW
select to_char (sysdate, 'mm-dd-yyyy
SYSDATE 06-29-2017
hh24:mi:ss') "NOW" from dual;
17:23:43

Dept. of Computer Science, SAIPUC, Shivamogga 18


II PUC Computer Science Unit C Chapter 14 SQL Commands

d) Conversion functions
These functions used to convert one value in one form to another form.
Name Description
Converts a valid numeric and character values to a date
to_date(x, date format)
value.
nvl(x,y) If x is null then replace it with y.
decode(a,b,c,d,e,default_value) If a=b return c, if a=d return e else return default value.
Converts numeric and date values to a character, string
to_char(x,y)
value.

Name Example Value


to_date(x, date format) to_date(‘2003/07/09’,’yyyy/mm/dd’) 09-JUL-03
nvl(x,y) select nvl(e_mail, ‘NA’) from std NA
decode(a,b,c,d,e,default_val select sname, decode(sid, 1000, 'anil', 1001,
ue) 'akash', 'NOT FOUND') result FROM std;

Select to_char(SYSDATE,'Day,Month,YYYY') Friday


to_char(x,y)
from dual ,June ,2017

Dept. of Computer Science, SAIPUC, Shivamogga 19

You might also like