0% found this document useful (0 votes)
39 views

Bca320 Dbms SQL Unit-3

The document provides an introduction to SQL, covering topics such as the history of SQL, an overview of SQL and its types, data definition in SQL, SQL data types, SQL operators, SQL expressions, constraints, query structure, query types, additional operations like set, comparison, null, aggregate functions, nested and correlated subqueries, complex queries, views, database modification, transactions, joins, and authorization commands. It discusses the evolution of SQL standards over time and provides detailed explanations of core SQL components and functionality.

Uploaded by

Chaithra.y
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Bca320 Dbms SQL Unit-3

The document provides an introduction to SQL, covering topics such as the history of SQL, an overview of SQL and its types, data definition in SQL, SQL data types, SQL operators, SQL expressions, constraints, query structure, query types, additional operations like set, comparison, null, aggregate functions, nested and correlated subqueries, complex queries, views, database modification, transactions, joins, and authorization commands. It discusses the evolution of SQL standards over time and provides detailed explanations of core SQL components and functionality.

Uploaded by

Chaithra.y
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

INTRODUCTION TO SQL

Topics Covered:
• History of SQL.

• Overview of SQL & Types.

• Data Definition in SQL.

• SQL Data Types.

• SQL Operators.

• SQL Expressions.

• SQL Constraints.

• Basic SQL Query Structure.

• SQL Query Types.

• Additional Basic Operations : Set , Comparison, Null , Aggregate , Etc….

• Nested Sub queries.

• Correlated Nested Queries.

• Complex Queries.

• VIEWS.

• Modification of Database.

• Transaction Commands.

• JOIN Expressions.

• Authorization Commands.
History of SQL:
• Early 1970’s ---- IBM , which is called as IBM Sequel XRM language.

• Late 1970’s -Inherited ISO Standards.

• Early 1986 they introduced, SQL-86 & SQL 89( ANSI/ISO ).

• Late 1986, SQL-1992.

• Then, They Introduced SQL-1999std ( Core SQL) ( Y2K Relations).

- Vendor oriented, Feasible, Compatible Packages.

• SQL-2003, SQL-2005 latest Standard(My Sql).


Overview :
• SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database.

• SQL is the standard language for Relational Database System. All the Relational Database Management
Systems (RDBMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as
their standard database language.
• Why SQL?
SQL is widely popular because it offers the following advantages −
1. Allows users to access data in the relational database management systems.
2. Allows users to describe the data.
3. Allows users to define the data in a database and manipulate that data.
4. Allows to embed within other languages using SQL modules, libraries & pre-compilers.
5. Allows users to create and drop databases and tables.
6. Allows users to create view, stored procedure, functions in a database.
7. Allows users to set permissions on tables, procedures and views.
SQL Process/Architecture:

NOTE :
A classic query
engine handles
all the non-SQL
queries, but a
SQL query
engine won't
handle logical
files.
SQL Types:
• The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into the
following groups based on their nature , like:
1. DDL-Data Definition Language: CREATE, ALTER, DROP, RENAME, TRUNCATE, COMMENT.

2.DML- Data Manipulation Language: SELECT, INSERT, UPDATE, DELETE, MERGE, CALL, LOCK

TABLE, EXPLAIN PLAN.

3. DCL- Data Control Language: GRANT , REVOKE.

4. SDL- Storage Definition Language.

5. VDL- View Definition Language.

6.TCL- Transaction Control Language: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION.


Data Definition in SQL :
Functions Performed are :

• Gives the SCHEMA for each relation.

• Gives the DOMAIN of values associated with each ATTRIBUTE.

• Gives INTREGRITY CONTRIANTS.

• Gives the set of indices which is to be maintained for each ATTRIBUTE.

• Gives the security and authorization information for each RELATION.

• Gives physical storage structure of each relation on the disk.


SQL DATA /DOMAIN TYPE’s:
SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data
type in SQL. You can use these data types while creating your tables. You can choose a data type for a table column based on your
requirement.
( Built-in and User Defined Data Types).

1. Numeric :
- Integer/Int. - Small Int. - Floating Int ( Float/Real , Double Precision) - Bit( 0 or 1)
2. Character String :
- Fixed Length ( Char).
- Variable Length ( VarChar) ) Characters will be varied).
- Literal String. ( Which are placed Between Single Quotation Marks ).
- Concatenation String : ‘abc’ || ‘xyz’
3. Bit String :
- Fixed ( Bit(n)).
- Variable ( Bit Varying(n)).
SQL Data Types Continued …..
4. BOOLEAN : TRUE, FALSE, UNKNOWN (NULL).

5. DATE : YYYY-MM-DD ------- ( 10 Positions).

6. TIME : HH:MM:SS -----------( 8 Positions).

7. Timestamp : Combination of DATE + TIME .

Consists of fields + minimum of 6 Positions for decimal fractions(Seconds).

8. INTERVAL : Combination of DATE + TIME + TimeStamp.

Consists of two types: 1. Year/Month Interval 2. Day/Time Interval

9. Large Objects Data Types :

- Character Data ( DOB).

- Binary Data for Image’s (BLOB)


SQL Operators :
• An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform

operation(s), such as comparisons and arithmetic operations. 

NOTE: These Operators are used to specify conditions in an SQL statement and to serve as conjunctions
for multiple conditions in a statement.

• Arithmetic operators.

• Comparison operators.

• Logical operators.

• Operators used to negate conditions.


SQL Operators Continued……
1. Arithmetic Operators: Assume 'variable a' holds 10 and 'variable b' holds 20 :
Operator Description Example

+ Adds values on either side of the operator.


(Addition)
a + b will give 30

- Subtracts right hand operand from left hand


(Subtraction) operand. a - b will give -10

* Multiplies values on either side of the operator.


(Multiplication)
a * b will give 200

/ Divides left hand operand by right hand operand.


(Division)
b / a will give 2

% Divides left hand operand by right hand operand


(Modulus) and returns remainder. b % a will give 0
2. Comparison Operators:Assume 'variable a' holds 10 and 'variable b' holds 20
Operator Description Example

Checks if the values of two operands are equal or not, if yes then condition
= becomes true. (a = b) is not true.
Checks if the values of two operands are equal or not, if values are not equal
!= then condition becomes true. (a != b) is true.

Checks if the values of two operands are equal or not, if values are not equal
<> then condition becomes true. (a <> b) is true.

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

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

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

Checks if the value of left operand is less than or equal to the value of right
<= operand, if yes then condition becomes true. (a <= b) is true.

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

Checks if the value of left operand is not greater than the value of right
!> operand, if yes then condition becomes true. (a !> b) is true.
3.Logical Operators:
No. Operator & Description
ALL The ALL operator is used to compare a value to all values in another value set.
1

AND The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
2

ANY The ANY operator is used to compare a value to any applicable value in the list as per the condition.
3

BETWEEN The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
4

EXISTS The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain criterion.
5

6 IN The IN operator is used to compare a value to a list of literal values that have been specified.

7 LIKE The LIKE operator is used to compare a value to similar values using wildcard operators.

NOT The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. 
This is a negate operator.
8

OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
9

IS NULL The NULL operator is used to compare a value with a NULL value.
10

11 UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
SQL Expressions:
EXPRESSION is a combination of one or more values, operators and SQL functions that evaluate to a value.

NOTE: These SQL EXPRESSIONs are like formulae and they are written in query language .

There are different types of SQL expressions, which are mentioned below −

• Boolean : SQL Boolean Expressions fetch the data based on matching a single value.

Example : SELECT column FROM table_name WHERE SINGLE_VALUE_MATCHING_EXPRESSION;

• Numeric : These expressions are used to perform any mathematical operation in any query.

Example: SELECT NUMERICAL_EXPRESSION as OPERATION_NAME FROM table_name;

• Date : Date Expressions return current system date and time values.

Example : SELECT CURRENT_TIMESTAMP; -- 2018-01-20 10:32:37


SQL Constraints:
• CONSTRAINTS are the rules enforced on data columns on a table.
• 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.

• NOTE: Constraints can either be column level or table level. Column level constraints are applied only to one column whereas,
table level constraints are applied to the entire table.

• Following are some of the most commonly used constraints available in SQL −
• NOT NULL Constraint − Ensures that a column cannot have a NULL value.

• DEFAULT Constraint − Provides a default value for a column when none is specified.

• UNIQUE Constraint − Ensures that all the values in a column are different.

• PRIMARY Key − Uniquely identifies each row/record in a database table.

• FOREIGN Key − Uniquely identifies a row/record in any another database table.

• CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions.

• INDEX − Used to create and retrieve data from the database very quickly.
Data Integrity Constraints:

• The following categories of data integrity exist with each RDBMS −


• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by restricting
the type, the format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by other
records.
• User-Defined Integrity − Enforces some specific business rules that do not
fall into entity, domain or referential integrity.
• NULL Value - A NULL value in a table is a value in a field that appears to be
blank, which means a field with a NULL value is a field with no
value.
NOTE : It is very important to understand that a NULL value is different than a zero value or a field
that contains spaces. A field with a NULL value is the one that has been left blank during a record
creation.
Basic SQL Query Structure:
- SQL Consists of Basic THREE Clauses, they are
SELECT ……
FROM ……
WHERE ………
Syntax :
SELECT A1,A2,A3,….….,An

Attributes
FROM r1,r2,……...,rn

Relations
WHERE P ---------- Predicate/Condition.

Example : SELECT branch-name From loan;


Basic SELECT Clause Types:
1. SELECT Distinct branch-name from loan; ( Used to eliminate duplicates )
2. SELECT loan-no, branch-name, amount * 100 from loan; ( ALL attributes )
3. SELECT * from Table name;
4. SELECT loan-no
from loan
Where branch-name = ‘xyz’; ( Here I have used Where Clause)
5. SELECT loan-no
from loan
Where branch-name = ‘xyz’ and amount > 10000; ( Here I have used Boolean
operator between two conditions)
( AND , OR , NOT )
6. SELECT loan-no
from loan
Where branch-name = ‘xyz’ and amount > 10000; ( Here we have also

used Comparison
<,>,<=,>=,=,#) Operator along with
Boolean operator's)
7. SELECT loan-no
from loan
Where amount BETWEEN 9000 and 10000; ( Here I have used Between key word )
{OR}
SELECT loan-no
from loan
Where amount <= 9000 and amount >= 10000;
8. SELECT cust-name, borrower, loan-no as loan-id, amount
from borrower, loan (Used to RENAME )
where borrower.loan-no = loan.loan-no ; ( & we can also write query using as,)
SELECT Cust-name, T.loan-no, S.amount
from borrower as T.laon-no as S
where T.loan-no = S.loan-no ;
9. String Operations : LIKE --- Keyword, % ----- Symbhol.
Variations :
‘xyz%’ – ( Matches any beginning with ‘xyz’ )
‘%xyz’ – ( Matches any string containing ‘xyz’ as a sub string )
‘%xyz%’ – ( Both )
“ || “ – ( Concatenation to join two strings )
“viceversa” – ( Used to convert Uppercase to Lowercase and ViceVersa )
10. Ordered By Clause:
SELECT distinct customer-name
from borrower, loan
where borrower.loan-no = loan.loan-no and branch-name = ‘xyz’
Ordered by customer-name;

( Ascending, Descending, Alphabetical)

{OR}

SELECT * from loan


Order by amount Desc, loan-no Asc;
11. SET Operation : ( UNION , INTERSECTION , EXCEPT ) ( Used based on Relational
Algebra Operations )
Examples :

i. (SELECT customer-name From depositor) UNION (SELECT customer-name From borrower);

ii. (SELECT customer-name From depositor) UNION ALL (SELECT customer-name From borrower);

iii. (SELECT customer-name From depositor) INTERSECTION (SELECT customer-name From borrower);

iv. (SELECT customer-name From depositor) INTERSECTION ALL (SELECT customer-name From borrower);

v. (SELECT customer-name From depositor) EXCEPT (SELECT customer-name From borrower);

vi. (SELECT customer-name From depositor) EXCEPT ALL (SELECT customer-name From borrower);
12. Aggregate Functions : MIN, MAX , AVG , SUM , COUNT
Examples :
- SELECT Avg(balance)
from account
Where branch-name = ‘xyz’;
13. Group By Clause:
SELECT branch-name, Avg(balance)
from account
group by branch-name ;

14. Having Clause:


SELECT branch-name, Avg(balance)
from account
group by branch-name
having avg(balance) > 12000 ;
15. NULL Values : It indicates the absence of information about the value of an attribute. Null Signifies
an unknown value or that a value does not exist.
Example :
SELECT loan-no
From loan
Where amount is NULL ;
NOTE : the result of any arithmetic expression involving NULL is a NULL.
--------------------------------------------------------------------------------------------------------------
CREATE TABLE CUSTOMERS
( ID INT NOT NULL,NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
NOTE : Here, NOT NULL signifies that column should always accept an explicit value of the given data
type. There are two columns where we did not use NOT NULL, which means these columns could be
NULL.
Nested Sub Queries:
• A Sub query or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE

clause.

• A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

• Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <,

>, >=, <=, IN, BETWEEN, etc.

• Syntax :
SELECT column_name [, column_name ]
Main Query FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
Sub Query FROM table1 [, table2 ]
[WHERE])
There are a few rules that subqueries must follow −
• Subqueries must be enclosed within parentheses.

• A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for
the subquery to compare its selected columns.

• An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The
GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.

• Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

• The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.

• A subquery cannot be immediately enclosed in a set function.

• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within
the subquery.
Set Membership Function's:
• Giving membership to access tuples in a table/relation is known as set membership.
• To perform this function , we use TWO keywords : IN and NOT IN

(SQL Connectives)
Example : SELECT distinct customer-name
From borrower
Where customer-name IN/NOT IN ( SELECT customer-name from Depositor);
[ OR ]
SELECT S.name
From Sailors S
Where S.sid NOT IN (SELECT R.sid
From Reserves R
Where R.bid IN (SELECT B.bid
From Boats B
Where B.color = ‘red’));
Set Comparison Function's:{ Correlated Nested Queries}
• The ANY/SOME and ALL operators are used with a WHERE or HAVING clause.
• The ANY/SOME operator returns true if any of the subquery values meet the condition.
• The ALL operator returns true if all of the subquery values meet the condition
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
( <ANY/SOME, >ANY/SOME,………. & <ALL, >ALL………. ) can be used in optional Cases.
Examples:
SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = “xyz’);
[OR]
SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2);
Test for EMPTY Relations:{ Correlated Nested Queries}

• We use TWO Keywords here, EXISTS and NOT EXISTS along with WHERE clause.

• For EXISTS : Each selected row be such that the subquery following EXISTS
does return something, i.e., the subquery doesnot return a NULL result.
( Argument subquery is not empty)

• For NOT EXISTS : Each selected row be such that the subquery following
NOT EXISTS does not return anything, i.e., the subquery returns a NULL
result. ( Argument subquery is empty )
Examples:
• SELECT Fname, Lname
From player
WHERE EXISTS ( SELECT *
From bating
WHERE playerID = PID
AND matchID = ‘1111’) ;
• SELECT PID As PlayerID
From batting b1
WHERE NOT EXISTS ( SELECT *
From Batting b2
WHERE b1.PID = b2.PID
AND Nruns < 31 ) ;
Test for the Absence of Duplicate Tuples : { Correlated Nested Queries }
• Here we Use TWO Keywords : UNIQUE & NOT UNIQUE

SQL Constructs
• UNIQUE : Argument sub query contains NO TUPLES.
• NOT UNIQUE : Argument sub query contains TUPLES.

Examples :
SELECT FirstName, LastName
FROM CUSTOMER
WHERE UNIQUE (SELECT CustomerID
FROM SALES
WHERE SALES.CustomerID = CUSTOMER.CustomerID);

NOTE : For NOT UNIQUE, We use SELECT DISTINCT at the first query.
Complex Queries:
• The WITH Clause: The SQL WITH clause allows you to give a sub-query block a name (a process also
called sub-query refactoring), which can be referenced in several places within the main SQL query.
• The clause is used for defining a temporary relation such that the output of this temporary relation is available and
is used by the query that is associated with the WITH clause.
• Queries that have an associated WITH clause can also be written using nested sub-queries but doing so add more
complexity to read/debug the SQL query.
• WITH clause is not supported by all database system.
• The name assigned to the sub-query is treated as though it was an inline view or table
• The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
• Example: WITH temporaryTable (averageValue) as
(SELECT avg(Attr1)
FROM Table),
SELECT Attr1
FROM Table
WHERE Table.Attr1 > temporaryTable.averageValue;
NOTE: In complex queries, we are unable to see the data storage and attributes all. Hence to overcome this
drawback , they introduced VIEWS.
VIEWS:
• Views in SQL are kind of virtual tables.

• A view also has rows and columns as they are in a real table in the database. We can create a view by selecting
fields from one or more tables present in the database.

• A View can either have all the rows of a table or specific rows based on certain condition.

• A view is nothing more than a SQL statement that is stored in the database with an associated name and is
actually a composition of a table in the form of a predefined SQL query.

• Views, which are a type of virtual tables allow users to do the following −

- Structure data in a way that users or classes of users find natural or intuitive.

- Restrict access to the data in such a way that a user can see and (sometimes) modify exactly

what they need and no more.

- Summarize data from various tables which can be used to generate reports.
Creating VIEWS:
• Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another view.
• To create a view, a user must have the appropriate system privilege according to the specific implementation.
• The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Example:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
• You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL
SELECT query.
WITH CHECK option in VIEWS:

• The WITH CHECK OPTION is a CREATE VIEW statement option.

• The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the
view definition.

• If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.

• The following code block has an example of creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION:
Syntax: CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;

NOTE: The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column,
because the view is defined by data that does not have a NULL value in the AGE column.
How to UPDATE a VIEW:
• A view can be updated under certain conditions which are given below −
• The SELECT clause may not contain the keyword DISTINCT.
• The SELECT clause may not contain summary functions.
• The SELECT clause may not contain set functions.
• The SELECT clause may not contain set operators.
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain subqueries.
• The query may not contain GROUP BY or HAVING.
• Calculated columns may not be updated.
• All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function.
• So, if a view satisfies all the above-mentioned rules then you can update that view.
• The following code block has an example to update the age of Ramesh:
UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
Modification of the Database:
1. CREATE DATABASE Command:
The SQL CREATE DATABASE statement is used to create a new SQL database.
Syntax:
CREATE DATABASE DatabaseName;
NOTE: Always the database name should be unique within the RDBMS.

2. CREATE Command:
The SQL CREATE TABLE statement is used to create a new table.
Here, Creating a basic table involves naming the table and defining its columns and each column's data type.
Syntax: The basic syntax of the CREATE TABLE statement is as follows −

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
• Example: CREATE TABLE CUSTOMERS

( ID INT NOT NULL,


NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

You can verify if your table has been created successfully by looking at the message displayed by the SQL server,
otherwise you can use the DESC command as follows −
3. INSERT Command :
• The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
• Syntax:

There are two basic syntaxes of the INSERT INTO statement which are shown below.

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)

VALUES (value1, value2, value3,...valueN);

Here, column1, column2, column3,...columnN are the names of the columns in the table into which you want to insert the
data.

You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table.
But make sure the order of the values is in the same order as the columns in the table.
The SQL INSERT INTO syntax will be as follows −

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);


Example:
• The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
{OR}
You can create a record in the CUSTOMERS table by using the second syntax as shown below.
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in the CUSTOMERS table as shown below.
SELECT * FROM CUSTOMERS;
4.UPDATE Command :
• The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE
query to update the selected rows, otherwise all the rows would be affected.

• Syntax: The basic syntax of the UPDATE query with a WHERE clause is as follows −

UPDATE table_name

SET column1 = value1, column2 = value2...., columnN = valueN

WHERE [condition];

• You can combine N number of conditions using the AND or the OR operators.

• Example:The following query will update the ADDRESS for a customer whose ID number is

6 in the table.

UPDATE CUSTOMERS

SET ADDRESS = 'Pune'

WHERE ID = 6;
6. ALTER Command:
• The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table.
• You should also use the ALTER TABLE command to add and drop various constraints on an existing table.
• Syntax: The basic syntax of an ALTER TABLE command to add a New Column in an existing
table is as follows.
ALTER TABLE table_name ADD column_name datatype;
• The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
• The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as
follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
• The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as
follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
• The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
7. DELETE Command :
• The SQL DELETE Query is used to delete the existing records from a table.
• You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be
deleted.

• Syntax: the basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
• You can combine N number of conditions using AND or OR operators.
• Example:
DELETE FROM CUSTOMERS
WHERE ID = 6;

NOTE: If you want to DELETE all the records from the CUSTOMERS table, you do not need to use
the WHERE clause and the DELETE query would be as follows −
DELETE FROM CUSTOMERS;
Now, the CUSTOMERS table would not have any record.
8. DROP Command:
• The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.

Syntax: The basic syntax of DROP DATABASE statement is as follows −

DROP DATABASE DatabaseName;

NOTE: Always the database name should be unique within the RDBMS.

NOTE : Be careful before using this operation because by deleting an existing database
would result in loss of complete information stored in the database.

9. RENAME/Alias Command:

• You can rename a table or a column temporarily by giving another name known as Alias.

• The use of table aliases is to rename a table in a specific SQL statement.

• The renaming is a temporary change and the actual table name does not change in the database. The column aliases are
used to rename a table's columns for the purpose of a particular SQL query.
Syntax :
• The basic syntax of a table alias is as follows.
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
• The basic syntax of a column alias is as follows.
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Example:
SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O Table Alias
WHERE C.ID = O.CUSTOMER_ID;
-------------------------------------------------------------------------------------------------
SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS Column Alias
WHERE SALARY IS NOT NULL;
Transaction Commands:
- A transaction is a unit of work that is performed against a database.
- Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a
user or automatically by some sort of a database program.

- NOTE: Practically, you will club many SQL queries into a group and you will execute all of them together as a part
of a transaction.
• Properties of Transactions: Transactions have the following four standard properties, usually referred to
by the acronym ACID.
1. Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the
transaction is aborted at the point of failure and all the previous operations are rolled back to their former
state.
2. Consistency − ensures that the database properly changes states upon a successfully committed transaction.
3. Isolation − enables transactions to operate independently of and transparent to each other.
4. Durability − ensures that the result or effect of a committed transaction persists in case of a
system failure.
Transaction Control Commands:
The following commands are used to control transactions.
10. COMMIT − to save the changes. The COMMIT command saves all the transactions to the database
since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;
Example: SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;
11. ROLLBACK − to roll back the changes. This command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
Example: SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
12. SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.
SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point
without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.

SAVEPOINT SAVEPOINT_NAME;

This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.

The syntax for rolling back to a SAVEPOINT is as shown below.

ROLLBACK TO SAVEPOINT_NAME;
13. SET TRANSACTION − Places a name on a transaction.

• The SET TRANSACTION command can be used to initiate a database transaction. This command is used to
specify characteristics for the transaction that follows. For example, you can specify a transaction to be read
only or read write.

• The syntax for a SET TRANSACTION command is as follows.

SET TRANSACTION [ READ WRITE | READ ONLY ];


JOIN Expressions:
• The SQL JOINS clause is used to combine records from two or more tables in a database. A JOIN is a means. for

combining fields from two tables by using values common to each

Now, let us join these two tables in our SELECT statement as shown below.

SQL> SELECT ID, NAME, AGE, AMOUNT

FROM CUSTOMERS, ORDERS

WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables,

such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most

common operator is the equal to symbol.


• There are different types of JOINS available in SQL −

• INNER JOIN − returns rows when there is a match in both tables.

• LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table.

• RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table.

• FULL JOIN − returns rows when there is a match in one of the tables.

• SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.

• CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more
joined tables.
Authorization Commands: 14. GRANT Command
• When the SQL standard authorization mode is enabled, object owners can use the GRANT
and REVOKE SQL statements to set the user privileges for specific database objects or for
specific SQL actions. They can also use roles to administer privileges.
• The GRANT statement is used to grant specific privileges to users or to roles, or to grant
roles to users or to roles. The REVOKE statement is used to revoke privileges and role
grants. The grant and revoke privileges are:
• DELETE,EXECUTE,INSERT,SELECT,REFERENCES,TRIGGER,UPDATE

• The Syntax for the GRANT command is:


GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
****THANK YOU****

You might also like