Lecture 5 - Advanced SQL
Lecture 5 - Advanced SQL
Constraints
• Constraints are the rules enforced on the data columns of 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.
• Constraints could be either on a column level or a table level. The
column level constraints are applied only to one column, whereas the
table level constraints are applied to the whole table.
Commonly used Constraints available in SQL
• NOT NULL Constraint – Ensures that a column cannot have a null value
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)
);
Commonly used Constraints available in
SQL
• If CUSTOMERS table has already been created, then to add a NOT
NULL constraint to the SALARY column in Oracle and MySQL, you
would write a query like the one that is shown in the following code
block.
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;
Commonly used Constraints available in SQL
• DEFAULT Constraint - Provides a default value for a column when none is
specified.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
);
Commonly used Constraints available in SQL
• If the CUSTOMERS table has already been created, then to add a
DEFAULT constraint to the SALARY column, you would write a query
like the one which is shown in the code block below.
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;
NOTE − If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) should have already been declared to not contain NULL
values (when the table was first created)
Delete Primary Key
Here, the WHERE clause could be any given expression based on your
requirement.
Cartesian Join
• The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets
of records from two or more joined tables.
SELECT ColumnName_1,
ColumnName_2,
ColumnName_N
FROM [Table_1]
CROSS JOIN [Table_2]
or
SELECT ColumnName_1,
ColumnName_2,
ColumnName_N
FROM [Table_1],[Table_2]
Union Operator
The SQL UNION clause/operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows.
To use this UNION clause, each SELECT statement must have
• The same number of columns selected
• The same number of column expressions
• The same data type and
• Have them in the same order
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
Union All Operator
• The UNION ALL operator is used to combine the results of two SELECT
statements including duplicate rows.
• The same rules that apply to the UNION clause will apply to the UNION
ALL operator.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Intersect Operator
• The SQL INTERSECT clause/operator is used to combine two SELECT
statements, but returns rows only from the first SELECT statement that are
identical to a row in the second SELECT statement. This means INTERSECT
returns only common rows returned by the two SELECT statements.
• Just as with the UNION operator, the same rules apply when using the
INTERSECT operator. MySQL does not support the INTERSECT operator.
Although indexes are intended to enhance a database's performance, there are times when they should be
avoided. The following guidelines indicate when the use of an index should be reconsidered.
Indexes should not be used on small tables.
Tables that have frequent, large batch updates or insert operations.
Indexes should not be used on columns that contain a high number of NULL values.
Columns that are frequently manipulated should not be indexed.
Index
•Example - For example, the following SQL syntax creates a new table called CUSTOMERS and adds five
columns in it.
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));
•Now, you can create an index on a single or multiple columns using the syntax given below.
CREATE INDEX index_name
ON table_name ( column1, column2.....);
•To create an INDEX on the AGE column, to optimize the search on customers for a specific age, you can use
the follow SQL syntax which is given below −
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
Index
•DROP an INDEX Constraint - To drop an INDEX constraint, use the following SQL syntax.
Remember - The INDEX is used to create and retrieve data from the database very quickly. An Index can be
created by using a single or group of columns in a table. When the index is created, it is assigned a ROWID for
each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while creating an index. A
Selection of fields depends on what you are using in your SQL queries.
Truncate
•The SQL TRUNCATE TABLE command is used to delete all the records from an existing table by reinitializing
the table's structure. This command instructs the database to deallocate the space for all records in a table and
change this table's structure by resetting the table size. This is the reason why it is deemed to be a Data Definition
Language (DDL) operation rather than Data Manipulation Language (DML), even though all the table data is
removed.
•Logically, the TRUNCATE TABLE statement performs similarly to the DELETE TABLE statement but without
the WHERE clause. However, TRUNCATE is much faster than DELETE and does not allow roll back once
committed.
•You can also use DROP TABLE command to delete a table but it will remove the complete table structure from
the database and you would need to re-create this table once again if you wish you store some data again.
The basic syntax of a TRUNCATE TABLE command is as follows.
There is a need to make a manual COMMIT after When you use the TRUNCATE command, the
making changes to the DELETE command, for the modifications made to the table are committed
modifications to be committed. automatically.
It deletes rows one at a time and applies some criteria It removes all of the information in one go
to each deletion.
The CREATE PROCEDURE statement is used to create the procedure. After creating the
procedure, we can define any input parameters that the procedure may require. These
parameters are preceded by the '@' symbol and followed by their respective data types.
The AS keyword is used to begin the procedure definition. The SQL statements
that make up the procedure are placed between the BEGIN and END keywords.
Stored Procedure - Example
Customer Table CREATE PROCEDURE GetCustomerInfo
@CutomerAge INT
AS
BEGIN
SELECT * FROM CUSTOMERS
WHERE AGE = @CutomerAge
END
• 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.
• 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.
• Consistency − ensures that the database properly changes states upon a
successfully committed transaction.
• Isolation − enables transactions to operate independently of and transparent to
each other.
ROLLBACK;
The SAVEPOINT Command
A 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;
The SAVEPOINT Command - Example
SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
SQL> ROLLBACK TO SP2;
Savepoint created.
Rollback complete.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
Sequences
Initial_Value − This specifies the starting value from where the sequence should start.
Increment_Value − This specifies the value by which the sequence will increment by itself. This can be valued positively or
negatively.
Cache - Specify how many values of the sequence the database preallocates and keeps in memory for faster access. The
maximum value allowed for CACHE must be less than the value determined by the following formula: (CEIL (MAXVALUE -
MINVALUE)) / ABS (INCREMENT)
Nocache -Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit both CACHE and
NOCACHE, the database caches 20 sequence numbers by default.
Cycle − When the sequence reaches its Maximum_Value, it starts again from the beginning.