SQL_PPT1
SQL_PPT1
Prepared By:M.P.Karnik 1
SQL-Structured Query Language
• SQL (Structured Query Language):-
It is a computer language aimed to store,
manipulate data stored in relational databases.
Some of the basic functions of SQL are
inputting, modifying, and dropping data from
databases.
Prepared By:M.P.Karnik 2
Data types in SQL
Data type Description
CHARACTER(n) Character string, fixed length n.
CHARACTER VARYING(n)
Variable length character string,
or
maximum length n.
VARCHAR(n)
Fixed length binary string, maximum
BINARY(n)
length n.
BINARY VARYING(n) or Variable length binary string, maximum
VARBINARY(n) length n.
INTEGER(p) Integer numerical, precision p.
SMALLINT Integer numerical precision 5.
NTEGER Integer numerical, precision 10.
BIGINT Integer numerical, precision 19.
DECIMAL(p, s) Exact numerical, precision p, scale s.
Prepared By:M.P.Karnik 3
FLOAT(p) Approximate numerical,mantissa precision p.
Prepared By:M.P.Karnik 4
Data Type Abbreviations
Abbreviation Character
CHAR(n) CHARACTER(n)
CHAR CHARACTER
CHAR VARYING(n) CHARACTER VARYING(n)
VARCHAR(n) CHARACTER VARYING(n)
VARBINARY(n) BINARY VARYING(n)
INT(p) INTEGER(p)
INT INTEGER
DEC(p, s) DECIMAL(p, s)
DEC DECIMAL
NUM(p, s) NUMERIC(p, s)
NUM NUMERIC
Prepared By:M.P.Karnik 5
Operators in SQL
SQL support 3 types of operators
✔ Arithmetic Operator:
Used for basic calculations like +,-,* & /. It can
be used in the expression.
Prepared By:M.P.Karnik 6
SQL Operators
Prepared By:M.P.Karnik 8
Operators in SQL
✔ Logical Operator:
Used to evaluate the expression depending on
combination of conditions.
Logical operators are,
Prepared By:M.P.Karnik 9
The ALL operator is used to compare a value to all
ALL
values in another value set.
Prepared By:M.P.Karnik 10
The NOT operator reverses the meaning of the
logical operator with which it is used. Eg: NOT
NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a
negate operator.
The OR operator is used to combine multiple
OR
conditions in an SQL statement's WHERE clause.
The NULL operator is used to compare a value with
IS NULL
a NULL value.
The UNIQUE operator searches every row of a
UNIQUE
specified table for uniqueness (no duplicates).
Prepared By:M.P.Karnik 11
SQL Comparison Keywords
• There are other comparison keywords available in sql
which are used to enhance the search capabilities of a
sql query.
Prepared By:M.P.Karnik 13
• The previous select statement searches for all
the rows where the first letter of the column
first_name is ‘A' and rest of the letters in the
name can be any character.
Prepared By:M.P.Karnik 15
SQL set operators
• SQL set operators combine results from two
or more SELECT statements.
• SQL set operators combine rows from
different queries with strong preconditions -
all involved SELECTS must.
• They retrieve the same number of columns
and the data types of corresponding
columns.
Prepared By:M.P.Karnik 16
• According to SQL Standard there are
following Set operator types:
UNION [DISTINCT];
UNION ALL;
EXCEPT [DISTINCT];
EXCEPT ALL;
INTERSECT [DISTINCT];
INTERSECT ALL.
Prepared By:M.P.Karnik 17
Union and UNION ALL
• In SQL the UNION clause combines the results of
two SQL queries into a single table of all matching
rows. The two queries must result in the same
number of columns and compatible data types in
order to unite. Any duplicate records are
automatically removed unless UNION ALL is used.
• A simple example would be a database having
tables sales2005 and sales2006 that have identical
structures but are separated because of
performance considerations. A UNION query could
combine results from both tables.
• UNION does not guarantee the order of rows. Rows
from the second operand may appear before, after,
or mixed with rows from the first operand. In
situations where a specific order is desired, ORDER
Prepared By:M.P.Karnik 18
person amount person amount
A 1000 A 2000
B 2000 B 2000
C 5000 D 35000
Sales2006
Sales2005
person amount
A 1000
B 2000
C 5000
A 2000
D 35000
person amount
A 1000
A 2000
B 2000
B 2000
C 5000
D 35000
Prepared By:M.P.Karnik 20
INTERSECT operator
Prepared By:M.P.Karnik 21
Minus operator
• The following statement combines results with the
MINUS operator, which returns only unique rows
returned by the first query but not by the second:
Prepared By:M.P.Karnik 22
EXCEPT operator
• The SQL EXCEPT operator takes the distinct
rows of one query and returns the rows that
do not appear in a second result set.
• The EXCEPT ALL operator does not remove
duplicates.
• For purposes of row elimination and
duplicate removal, the EXCEPT operator
does not distinguish between NULLs.
Prepared By:M.P.Karnik 23
The query returns all rows where the Quantity is
between 1 and 100, apart from rows where the
quantity is between 50 and 75.
Prepared By:M.P.Karnik 24
Statement
• DML
DML is abbreviation of Data Manipulation Language. It
is used to retrieve, store, modify, delete, insert and
update data in database.
Examples: SELECT, UPDATE, INSERT statements
• DDL
DDL is abbreviation of Data Definition Language. It is
used to create and modify the structure of database
objects in database.
Examples: CREATE, ALTER, DROP statements
• DCL
DCL is abbreviation of Data Control Language. It is used
to create roles, permissions. It is also used to control
access to database by securing it.
Examples: GRANT, REVOKE statements
• TCL
TCL is abbreviation of Transactional Control Language.
It is used to manage different transactions occurring
within a database. Prepared By:M.P.Karnik 25
What are the difference between DDL, DML and
DCL commands
Prepared By:M.P.Karnik 26
✔ DML:-Data Manipulation Language
(DML) statements are used for managing
data within schema objects. Some
examples:
• SELECT - retrieve data from the database
• INSERT - insert data into a table
• UPDATE - updates existing data within a
table
• DELETE - deletes all records from a table,
the space for the records remain
• MERGE - UPSERTPrepared
operation
By:M.P.Karnik (insert or 27
✔ DCL:-Data Control Language (DCL)
statements.
GRANT - gives user's access privileges to
database
REVOKE - withdraw access privileges given with
the GRANT command.
Prepared By:M.P.Karnik 29
SELECT
• The most commonly used SQL command is SELECT
statement. The SQL SELECT statement is used to
retrieve data from a table in the database. A query
may retrieve information from specified columns or
from all of the columns in the table. To create a
simple SQL SELECT Statement, you must specify the
column(s) name and the table name. The whole
query is called SQL SELECT Statement.
Prepared By:M.P.Karnik 40
SQL Delete-DML Statement
• The DELETE Statement is used to delete rows from
a table.
• Syntax :
DELETE FROM table_name [WHERE condition];
Prepared By:M.P.Karnik 42
Difference between DELETE and TRUNCATE
Statements
Prepared By:M.P.Karnik 45
SQL ALTER TABLE-DDL Statement
Prepared By:M.P.Karnik 46
Continue….
• Syntax :
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
Prepared By:M.P.Karnik 52
Example
REVOKE SELECT ON employee FROM user1;
• This command will REVOKE a SELECT
privilege on employee table from user1.
• When you REVOKE SELECT privilege on a
table from a user, the user will not be able to
SELECT data from that table anymore.
• However, 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.
• You cannot REVOKE privileges if they were
not initially granted by you.
Prepared By:M.P.Karnik 53
Privileges and Roles
• 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.
Prepared By:M.P.Karnik 54
CREATE system privileges
Prepared By:M.P.Karnik 55
Object privileges
Object Privileges Description
allows users to insert rows
INSERT
into a table.
allows users to select data
SELECT
from a database object.
allows user to update data in a
UPDATE
table.
allows user to execute a
EXECUTE stored procedure or a
function.
Prepared By:M.P.Karnik 56
• Roles:
1) 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.
2) 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.
Prepared By:M.P.Karnik 57
Some of the privileges granted
Prepared By:M.P.Karnik 58
Creating Roles
• Syntax :
CREATE ROLE role_name
[IDENTIFIED BY password];
Prepared By:M.P.Karnik 59
• 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.
• We can GRANT or REVOKE privilege to a role as
below:
• For example: To grant CREATE TABLE privilege
to a user by creating a testing role:
• First, create a testing Role
CREATE ROLE testing
• Second, grant a CREATE TABLE privilege to the
ROLE testing. You can add more privileges to the
ROLE. Prepared By:M.P.Karnik 60
Continue….
Commit:
Used to end the transaction & also make its
effect permanent to the database.
Prepared By:M.P.Karnik 62
Rollback-TCL Statement
Rollback:
Used to undo work done in current
transaction.
Prepared By:M.P.Karnik 63
Save Point-TCL Statement
Savepoint:
Like marker which marks the lengthy
transactions
It is used with rollback to cancel effect till
particular savepoint
Syntax: savepoint savepointname;
Prepared By:M.P.Karnik 64
Database Objects
Object Description
Table Basic unit of storage; composed of rows and
columns
View Logically represents subsets of data from one
or more tables
Sequen Generates primary key value
ce
Index Improves the performance of some queries
Synony Alternative name for an object
m
Prepared By:M.P.Karnik 65
SQL Views
• A VIEW is a virtual table, through which a
selective portion of the data from one or more
tables can be seen.
• Views do not contain data of their own. They
are used to restrict access to the database or
to hide data complexity.
• A view is stored as a SELECT statement in the
database. DML operations on a view like
INSERT, UPDATE, DELETE affects the data in
the original table upon which the view is
based.
Prepared By:M.P.Karnik 68
• SQL Dropping a View
• You can delete a view with the DROP
VIEW command.
• Syntax:
DROP VIEW view_name
Prepared By:M.P.Karnik 69
Syntax for MySQL
• The following SQL statement defines the "ID"
column to be an auto-increment primary key field
in the “Employee" table:
Prepared By:M.P.Karnik 73
Example
Prepared By:M.P.Karnik 75
• Single-Column Indexes:
• A single-column index is one that is created based on only
one table column.
CREATE INDEX index_name ON table_name
(column_name);
• Unique Indexes:
• Unique indexes are used not only for performance, but
also for data integrity. A unique index does not allow any
duplicate values to be inserted into the table.
CREATE UNIQUE INDEX index_name ON table_name
(column_name);
• Composite Indexes:
• A composite index is an index on two or more columns of
a table.
CREATE INDEX index_name ON table_name (column1, 76
Prepared By:M.P.Karnik
• Explicit Indexes:
They are created using the "create index.. "
syntax.
1) Even though sql indexes are created to access
the rows in the table quickly, they slow down
DML operations like INSERT, UPDATE, DELETE
on the table, because the indexes and tables both
are updated along when a DML operation is
performed. So use indexes only on columns
which are used to search the table frequently.
Prepared By:M.P.Karnik 80
Synonyms
• We can simplify access to objects by creating a
synonym(another name for an object).
• Syntax:
CREATE [PUBLIC] SYNONYM synonym
FOR object;
Where,
PUBLIC: creates synonym accessible to all users
SYNONYM: It is the synonym to be created
object: identifies the object for which the synonym is
created.
Prepared By:M.P.Karnik 82
Removing Synonym
• To drop a synonym use the DROP
SYNONYM statement. Only the
database administrator can drop a
public synonym.
Prepared By:M.P.Karnik 83
• Suppose the schemas hr and sh both
contain tables named customers.
Prepared By:M.P.Karnik 84
Group Functions
• SQL GROUP Functions
• Group functions are built-in SQL functions that operate on
groups of rows and return one value for the entire group.
These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT
Prepared By:M.P.Karnik 90
Query
• If you want to know the total
amount of salary spent on
each department, the query
would be:
Prepared By:M.P.Karnik 91
Example
• SELECT Department_id, SUM (salary)
FROM employee
GROUP BY Department_id;
Deparment_i SUM(salary)
d
90 40000
60 50000
70 30000
10 80000
Prepared By:M.P.Karnik 92
• The group by clause should contain all
the columns in the select list except
those used along with the group
functions.
Prepared By:M.P.Karnik 93
Having Clause
• Having clause is used to filter data based on the
group functions. This is similar to WHERE condition
but is used with group functions.
• Group functions cannot be used in WHERE Clause
but can be used in HAVING clause.
Prepared By:M.P.Karnik 96
Query
• If you want to select the
department that has total
salary paid for its employees
more than 35000.
Prepared By:M.P.Karnik 97
Example1
• SELECT Department_id, SUM (salary)
FROM employee
GROUP BY Department_id
HAVING SUM (salary) > 35000
Deparment_i SUM(salary)
d
90 40000
60 50000
10 80000
Prepared By:M.P.Karnik 98
Query
• Display the department id and
average salaries for those
departments whose maximum
salary is greater than 35000
Prepared By:M.P.Karnik 99
Example 2
• SELECT Department_id, AVG (salary)
FROM employee
GROUP BY Department_id
HAVING MAX(salary) > 35000
• Syntax
• SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN]
[ASC|DESC]];
Job_id Payroll
ST_Clerk 40000
Manager 50000