14 - SQL 12 - NEW
14 - SQL 12 - NEW
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
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.
Classic Query Engine (CQE): The CQE processes queries originating from non-SQL
interfaces.
SQL Query Engine (SQE): SQE processes queries such as ODBC, JDBC.
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.
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)
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.
a) Arithmetic Operators:
b) Comparison Operators:
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]
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;
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
Example:
create table std
(
stdid int CONSTRAINT STD_ID_NN NOT NULL,
sname varchar2 (20),
total int
)
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.
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.
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
)
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.
Example 1:
alter table ebill add (bill_amt float, due_date date);
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 1:
insert into customers (ID,NAME) values (1, 'Ramesh');
Example 2:
insert into customers
values (7, 'ramesh', 24, 'Indore', 10000 );
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;
c) delete command: This command is used to delete rows from a table based on
condition
Syntax: delete from table_name where condition;
Example1:
select id, name, salary from customers where salary >
20000;
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;
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.
Syntax:
select column1, column2
from table_name
where [ conditions ]
group by column1, column2
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.
c) max ( ): This function is used to get the maximum value from a column.
Example: select max (salary) from employee;
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;
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;
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;
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.
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}
Privileges and Roles: Privileges define the access rights provided to a user on a
database object.
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. 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
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
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.
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.