SQL-DDL DML TCL
SQL-DDL DML TCL
COMMANDS
History
text Variable width character 2GB of text data 4 bytes + number of chars
string
The first way specifies both the column names and the values to be
inserted:
If you are adding values for all the columns of the table, you do not need
to specify the column names in the SQL query. However, make sure the
order of the values is in the same order as the columns in the table. The
INSERT INTO syntax would be as follows:
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
FirstName varchar(255),
Age int
);
SQL PRIMARY KEY Constraint
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:
To create a PRIMARY KEY constraint on the "ID" column when the table is already created,
use the following SQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables. OrderID OrderNu PersonI
PersonID LastName FirstName Age mber D
The FOREIGN KEY constraint also prevents invalid data from being inserted into
1 the foreignHansen
key column,Ola 30 to be one of1 the values
because it has 77895 3 in the
contained
2 table it points
Svendson
to. Tove 23 2 44678 3
3 Pettersen Kari 20 3 22456 2
4 24562 1
SQL FOREIGN KEY Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
DROP a CHECK Constraint
Syntax:
SELECT column1, column2, ...
FROM table_name;
To select all the fields available in the table, use the following
syntax:
SELECT * FROM table_name;
SQL SELECT DISTINCT Statement
Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
SQL SELECT
Find the names of all instructors in the Art department who have
taught some course and the course_id
select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID and instructor. dept_name
= ‘Art’
instructor teaches
SQL Where clause
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Operators in The WHERE Clause
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
SQL AND, OR and
NOT Operators
The WHERE clause can be combined with AND, OR, and
NOT operators.
The AND and OR operators are used to filter records based
on more than one condition:
The AND operator displays a record if all the
conditions separated by
AND are TRUE.
The OR operator displays a record if any of the
conditions separated by
OR is TRUE.
The NOT operator displays a record if the condition(s) is
NOT TRUE.
SQL AND, OR and
NOT Operators
AND Syntax
SELECT column1, column2, ... SELECT * FROM Customers
FROM table_name WHERE Country='Germany' AND C
WHERE condition1 AND condition2ity='Berlin';
AND condition3 ...;
OR Syntax
SELECT * FROM Customers
SELECT column1, column2, ...
FROM table_name WHERE City='Berlin' OR City='Münche
n'; OR condition3 ...;
WHERE condition1 OR condition2
NOT Syntax
SELECT column1, column2, ... SELECT * FROM Customers
FROM table_name WHERE NOT Country='Germany'
WHERE NOT condition; ;
SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by default. To
SELECT * FROM Customers
sort the records in descending order, use the DESC keyword.
ORDER BY Country;
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
SQL MIN() and MAX() Functions
COUNT() Syntax
SELECT COUNT(column_name) SUM() Syntax
FROM table_name
WHERE condition; SELECT SUM(column_na
me)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SQL COUNT(), AVG() and
SUM() Functions
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Other functions • String conversion
Concatenation (||) upper(s)
lower(s)
Extracting substrings • Remove the space at
Length of the sring the end of the string
SQL LIKE Operator
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or Finds any values that have "or" in
%' any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in
the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a"
and are at least 2 characters in
length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a"
and are at least 3 characters in
length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a"
and ends with "o"
SQL LIKE Operator
LIKE Operator Description
WHERE CustomerName LIKE ‘___' Matches any string of exactly three
characters
WHERE CustomerName LIKE ‘___%' Matches any string of atleastthree
characters
SQL LIKE Operator
Find the names of all instructors whose name
includes the substring “dar”.
select name
from instructor
where name like '%dar%'
Match the string “100%”
like ‘100 \%' escape '\'
in that above we use backslash (\) as the escape
character.
SQL IN Operator
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
SQL statement selects all customers that are from the same
countries as the suppliers:
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
The are two types of SQL JOINS - EQUI JOIN and NON EQUI JOIN
The SQL EQUI JOIN is a simple SQL join uses the equal sign(=) as the comparison operator for the
condition. It has two types - SQL Outer join and SQL Inner join.
The SQL NON EQUI JOIN is a join uses comparison operator other than the equal sign like >, <,
.
SQL EQUI JOIN
.
SQL EQUI JOIN
.
SQL EQUI JOIN
The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table
(table2). The result is NULL from the right side, if there is no
match.
Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SQL RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right
table (table2), and the matched records from the left table
(table1). The result is NULL from the left side, when there is no
match.
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
SQL FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all records when there is
a match in left (table1) or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-
sets!
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SQL NON EQUI JOIN
SELECT *
FROM foods
NATURAL JOIN
company;
SELECT column_1, column_2...column_n
FROM table_1
NATURAL JOIN table_2;
ANY Syntax:
SQL ANY and ALL Operators
ANY Syntax:
SELECT column_
name(s)
FROM table_na
me
WHERE column_
name
operator ANY
(SELECT column FROM Products
SELECT ProductName
WHERE ProductID = ANY (SELECT ProductID
_name outp
FROM OrderDetails WHERE Quantity = 10);
FROM table_na ut
me WHERE
condition);
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
ANY means that the condition will be true if the operation is true for any of the values in the range.
ANY means that the condition will be true if the operation is true for any of the values in the range.
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
SQL ANY and ALL Operators
SELECT column_
name(s)
FROM table_na
me
WHERE column_
name
operator ALL
(SELECT column
_name
FROM
SELECTtable_na
ProductName FROM Products
me WHERE cond = ALL (SELECT ProductID
WHERE ProductID
ition);
FROM OrderDetails WHERE Quantity = 10);
outp
ut
SQL Views
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.
Syntax:
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.
To Display all the tables of current user
Cursors
Explicit Cursor
These types of cursors are created by the user using the SELECT query.
An explicit cursor holds multiple records but processes a single row at a
time. It uses the pointer, which moves to another row after reading one row.
It is basically used for gaining extra control over the temporary workstation.
With explicit cursors, developers can fetch data from a query, go through
each row, and work on it individually. They offer more control and are perfect
for complex tasks or when you need to process data row by row.
Advantages of Using Cursors
in Database Management
They are a key tool for developers and database admins. They help you get and change
data efficiently, boosting database performance in certain cases.
Cursors also make data manipulation easier. You can update or delete rows based on
certain rules. This is crucial for changing data in a targeted way, like updating records or
removing old data.
Also, cursors help with complex data tasks. You can go through data sets, do math, or apply
rules to each row. This makes it easier to handle complex data changes that regular SQL
queries can’t handle.
How Cursor works?
Declaring a Cursor
The first step is declaring a cursor. You define its name, the SQL statement it will
run, and any parameters needed. This stage sets up the cursor’s role and its scope.
Opening a Cursor
After declaring, you must open the cursor. Opening it allocates memory and runs
the SQL statement. It gets ready to fetch data from the result set.
OPEN <cursorName>;
How Cursor works?
Fetching Data with a Cursor
With the cursor open, you can start fetching data. The data fetching process gets rows from the
result set one by one. You can move through the result set using FETCH NEXT, FETCH PRIOR,
With the cursor open, you can start fetching data. The data fetching process gets rows from
the result set one by one. You can move through the result set using FETCH NEXT, FETCH
Closing a Cursor
When you’re done fetching data, close the cursor. Closing it frees up memory and ends the
CLOSE <cursorName>;
cursor’s lifecycle. Not closing it can cause resource leaks and harm database performance.
To SQL CREATE INDEX Statement
DEALLOCATE cursor_name
Example : Implicit Cursor
BEGIN
FOR emp_rec IN SELECT * FROM emp LOOP
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.ename);
END LOOP;
END;
Example: Using an Explicit Cursor
BEGIN
-- Open the cursor
OPEN emp_cursor;
DECLARE
total_rows number;
BEGIN
UPDATE Emp
SET Salary = Salary + 1500;
total_rows := SQL%ROWCOUNT;
3. Lock Timeout
• This happens when the cursor tries to obtain a lock on a row or table,
but the lock is already held by another transaction for an extended
time.
• Solution: Use appropriate isolation levels, manage transactions
efficiently, and minimize locking duration to prevent timeouts.
Advantages of Using
Cursors
1. Row-by-Row Processing: Cursors allow data to be processed
row-by-row, which is particularly useful for tasks requiring detailed
and individualized operations, such as complex calculations or
transformations.
2. Iterative Data Handling: With cursors, we can iterate over a
result set multiple times, making it ideal for scenarios where
repeated operations are necessary on the same data.
3. Working with Complex Relationships: Cursors make it easier
to handle multiple tables with complex relationships, such as
hierarchical data structures or recursive queries.
4. Conditional Operations: Cursors are effective for performing
operations like updates, deletions, or inserts based on specific
conditions.
5. Processing Non-Straightforward Relationships: When the
relationships between tables are not straightforward or set-based
operations are impractical, cursors provide a flexible alternative.
Limitations of Cursors
While cursors are helpful in certain scenarios, they come with notable
limitations, and alternatives should be explored whenever possible:
1. Performance Overhead: Cursors process one row at a time,
which can be significantly slower compared to set-based operations
that handle all rows at once.
2. Resource Consumption: Cursors impose locks on tables or
subsets of data, consuming server memory and increasing the risk of
resource contention.
3. Increased Complexity: Managing cursors requires explicit
declarations, opening, fetching, closing, and deallocating, which adds
to the complexity of the SQL code.
4. Impact of Large Datasets: The performance of cursors decreases
with the size of the dataset, as larger rows and columns require more
resources and time to process.
Syntax:
CREATE INDEX Statement
Uniqdexes
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, column2);
Implicit Indexes
Implicit indexes are indexes that are automatically created by the
database server when an object is created. Indexes are
automatically created for primary key constraints and unique
constraints.
When should indexes be created –
SQL INDEX
to full table scans. Indexes provide a faster alternative by allowing quick access to relevant rows.
Join Optimization: Indexes on columns used for joining tables (such as foreign keys) improve
4. However, it is essential to be mindful of the storage cost and performance tradeoffs associated
with indexes. Over-indexing can lead to unnecessary overhead, while under-indexing may slow
Commit Command
COMMIT command is used to permanently save any
transaction into the database.
Syntax:
COMMIT;
TCL Commands
ROLLBACK command
- restores the database to last commited state. It is also used with
savepoint command to jump to a savepoint in an ongoing
transaction.
Syntax
ROLLBACK TO savepoint_name;
Savepoint Command:
command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
Syntax
SAVEPOINT savepoint_name;
TCL Commands
id name
1 Abhi
2 Adam
4 Alex
COMMIT;
SAVEPOINT A;
SAVEPOINT B;
SAVEPOINT C;
TCL Commands
d name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
TCL Commands
ROLLBACK TO A;
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit