Database Lo3
Database Lo3
SQL is the standard language for Relational Database System and all Relational Database
Management Systems (RDBMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres
and SQL Server use SQL as their standard database language.
SQL is widely popular because it can execute queries against a database, retrieve data , insert
records, update records, delete records from a database, create new databases, create new tables
in a database, create stored procedures in a database, create views in a database and set
permissions on tables, procedures, and views.
SQL sub-languages
SQL Commands
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP, etc.
SQL commands are grouped into below major categories (sublanguages) depending on
their functionality:
1
2. Data Manipulation Language commands:
DML commands work on records in a table. These are basic operations we perform on data such
as inserting new records, deleting unnecessary records, and updating existing records.
Command description
SELECT Is used to retrieve records from one or more tables in your SQL
database.
NOTE: TCL Commands (COMMIT, ROLLBACK, SAVEPOINT) are used for only DML
Commands (INSERT, UPDATE, DELETE) while DDL, DCL commands are Auto-committed.
2
SQL Operators
Introduction
An operator is a reserved word or a character that is used to query our database in a SQL
expression. To query a database using operators, we use a WHERE clause.
Operators are necessary to define a condition in SQL, as they act as a connector between two or
more conditions. The operator manipulates the data and gives the result based on the operator’s
functionality.
Examples:
3
Comparison operators
A comparison (or relational) operator is a mathematical symbol which is used to compare two
values.
Comparison operators are used in conditions that compares one expression with another. The
result of a comparison can be TRUE, FALSE, or UNKNOWN (an operator that has one or two
NULL expressions returns UNKNOWN).
Example: For your better understanding, I will consider the following table
CUSTOMER to perform various operations.
4
Example1. [Use equal to] (=):
SELECT * FROM CUSTOMER WHERE CSALARY=2000;
OUTPUT:
OUTPUT:
Assignment operators
The assignment operator (=) in SQL Server is used to assign the values to a variable. The
equal sign (=) is the only Transact-SQL assignment operator.
In the following example, we create @MyCounter variable and then the assignment operator
sets @MyCounter variable to a value i.e. 1.
5
Logical operators
The logical operators are used to perform operations such as ALL, ANY, NOT, BETWEEN
etc.
Logical operators separate two or more conditions in the WHERE clause of an SQL statement.
1. ALL OPERATOR
It is used to compare a value with every value in a list or returned by a query.
Must be preceded by =, !=, >, < ,<=, or >= evaluates.
ALL operators in the MySQL query are used to extract all tuples or records of the select
statement.
ALL keyword is also used to make a comparison of a value with each and every data in another
set of output from a subquery.
The ALL operator outputs true if and only if the complete subqueries will satisfy the
condition. ALL operator is headed by a comparison operator and will output true if all of
the values of the subquery will fulfill the condition.
ALL is always used in combination with select, where, having clause of the MySQL.
ALL is used to select all records or rows of a select query. It compares the value of every
value in a list or results from a query.
For example, ALL means either greater than every value, means greater than the
maximum value, less than every value or equal to ever value. Suppose ALL >(1, 2, 3)
means greater than 3, ALL < (1,2,3) means less than 1.
6
Syntax of ALL operators
select All column_name1, column_name2 from table name where condition
EXAMPLE 1:
mysql> select CID, CLAST_NAME, CSALARY FROM CUSTOMER where CSALARY<
ALL(select CSALARY FROM CUSTOMER WHERE CSALARY>2000);
EXAMPLE 2:
select CID, CLAST_NAME, CSALARY FROM CUSTOMER where CSALARY<=ALL(select
CSALARY FROM CUSTOMER WHERE CSALARY>2000);
7
THE OUTPUT WILL BE:
2. ANY OPERATOR
EXAMPLE 1:
SELECT * FROM CUSTOMER WHERE CAGE>ANY (SELECT CAGE FROM CUSTOMER WHERE CAGE> 22);
THE OUTPUT WILL BE:
EXAMPLE 2:
Consider two tables customer and orders:
CUSTOMER:
ORDERS:
8
Syntax:
SELECT num_value FROM table1 WHERE experession ANY (SELECT num_val FROM table2);
mysql>SELECT * FROM CUSTOMER WHERE CID> ANY(SELECT CID FROM ORDERS WHERE
CID>2);
3. IN, NOT IN
These operators in SQL are used with SELECT, UPDATE and DELETE statements/queries to
select, update and delete only particular records in a table those meet the condition given in
WHERE clause and conditions given in IN, NOT IN operators.
I.e. it filters records from a table as per the condition. Syntax for SQL IN & NOT IN operators
are given below.
Where,
column_name: Any one of the column names in the table.
Operator: Any one of the following (>, <, =, >=, <=, NOT, LIKE etc)
Value: User defined value.
The following SQL statement selects all customers that are located in "Germany", "France" or
"UK":
Examples:
(1) SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');
(2) select * from customer where cage IN (18,22,25);
9
4. The SQL BETWEEN, NOT BETWEEN Operators
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax:
SELECT column_name(s)
FROM table_nameWHERE column_name BETWEEN value1 AND value2;
Examples:
The following SQL statement selects all products with a price between 10 and 20:
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Syntax:
SELECT column_name(s) FROM table_nameWHERE column_name NOT
BETWEEN value1 AND value2;
Please consider the following table with few records as given below.
Table name (for example): student
Column names in this table: Student_ID, Student_name, City and Age
10
EXAMPLE2:
HOW TO USE NOT BETWEEN…AND IN WHERE CLAUSE IN SELECT QUERIES
SQL query:
SELECT Student_ID, Student_name, City, Age from student WHERE Age NOT
BETWEEN 19 AND 25;
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.
AND Syntax
SELECT column1, column2, ...FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...FROM table_name WHERE NOT condition;
EXAMPLES:
11
The following SQL statement selects all fields from "Customers" where country is "Germany" OR
"Spain":
Note: You can also combine the AND, OR and NOT operators.
Examples:
1. The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city must be "Berlin" OR "München" (use parenthesis to form complex expressions):
2. The following SQL statement selects all fields from "Customers" where country is NOT
"Germany" and NOT "USA":
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
6. LIKE operator
The SQL LIKE operator is used to find matches between a character string and a
specified pattern.
12
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?)
instead of the underscore (_).
Syntax:
13
The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in any
position:
SELECT * FROM Customers WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:
SELECT * FROM Customers WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts with "a"
and are at least 3 characters in length:
The following SQL statement selects all customers with a ContactName that starts with "a" and ends
with "o":
SELECT * FROM Customers WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does NOT start
with "a":
SELECT * FROM Customers WHERE CustomerName NOT LIKE 'a%';
EXISTS Syntax
SELECT column_name(s) FROM table_name WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example1:
SELECT cid,cage from customer where exists (select csalary from
customer where csalary=2000);
Output:
14
Example2:
SELECT cid,cage from customer where exists (select csalary from customer
where csalary>200000);
Output:
8. Some operator
It evaluates the condition between the outer and inner tables and evaluates to true if the final
result returns any one row. If not, then it evaluates to false.
The SOME and ANY comparison conditions are similar to each other and are completely
interchangeable.
SOME must match at least one row in the subquery and must be preceded by comparison
operators.
Syntax:
SELECT column_name(s) FROM table_name WHERE expression comparison_operator
SOME (subquery);
EXAMPLE:
SELECT * FROM CUSTOMER WHERE CAGE>SOME(SELECT CAGE FROM CUSTOMER
WHERE CAGE> 22);
Output:
9. UNIQUE operator
The SQL UNIQUE Operator is used to check whether the sub-query has any duplicate values in
the result. It returns true if the sub-query has no duplicate values, else returns false.
Syntax:
The syntax for using UNIQUE operator is given below:
SELECT [Link] FROM table1 WHERE UNIQUE (SELECT [Link] FROM table2
WHERE [Link] = [Link]);
15
Example:
Consider a database containing tables called Employee and Contact_Info with the following
records:
To find all the employees whose contact information is updated in the Contact_Info table, the
below mentioned SQL code can be used.
16
Membership operators
Membership operators are operators used to validate the membership of a value.
It tests for membership in a sequence, such as strings, lists, or tuples.
Set-membership tests: IN, NOT IN.
Identity operators
An identity column of a table is a column whose value increases automatically.
The value in an identity column is created by the server. A user generally cannot insert a value into an
identity column.
Syntax:
IDENTITY [(seed, increm ent)]
Arguments:
1. Seed: Starting value of a column. The default value is 1.
2. Increment: It specifies the incremental value that is added to the identity column value of the
previous row. The default value is 1.
In general, the operators’ precedence follows the same rules as in the high school math. The
order of the precedence is indicated in the following table.
17
Multiplication and division take priority over addition and subtraction.
Operators of the same priority are evaluated from left to right.
Parentheses are used to force prioritized evaluation and to clarify
statements.
CREATE command
Application of " Create database and Create table" commands
a) Create database
i) To create a new database, the SQL query used is CREATE DATABASE
The Syntax is:
Create database database-name;
Creating a database does not select it for use; you must do that explicitly. To make menagerie the
current database, use one of these statement:
OR
b) Create table
Creating the database is the easy part, but at this point it is empty if no table created,
as SHOW TABLES tells us:
After creating a database and entering in database, there is a need now to create a table.
Creating a table involves naming the table and defining its columns and each column’s data type.
The SQL CREATE TABLE statement is used to create a new table.
18
The basic syntax of CREATE TABLE statement is as follows:
Create table table_name (column1 datatype, column2 datatype, column3
datatype, .....column datatype);
Then in brackets comes the list defining each column in the table and what sort of data type it is.
The following SQL query creates a “Customers” table with 6 columns, and thereafter, when the
table was successfully created, the message “Query OK, o rows affected (0.48 sec)” is displayed.
See below.
The user can verify if the table has been created successfully by looking at the message displayed
by the SQL server, otherwise he/she can use DESC command as follows:
Now, “Customers” table is created and available in database. It can be used to store required
information related to “Customers”. Notice that DESC is the same as DESCRIBE.
Create Table Using another Table: A copy of an existing table can be created using a
combination of the CREATE TABLE statement and the SELECT statement. The new table has
the same column definitions. All columns or specific columns can be selected.
When you create a new table using existing table, new table would be populated using existing
values in the old table. The basic syntax for creating a table from another table is as follows:
Example: To create a table called SALARY having the same attributes like table “Customers”,
write Create table salary like “Customers”;
19
Description of 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.
Constraints can be either column level or table level. Column level constraints are applied only
to one column whereas table level constraints are applied to the entire table.
Constraints are:
20
You should also use the ALTER TABLE command to add and drop various constraints on an
existing table.
21
Execution of SQL constraints:
Note: In the example above at the right, there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
The following commands are used when the table is already created.
ADD
MySQL / SQL Server / Oracle On MySQL / SQL Server / Oracle On
single column multiple columns
ALTER TABLE Persons
ALTER TABLE Persons ADD CONSTRAINT PK_Person
ADD PRIMARY KEY (ID); PRIMARY KEY (ID, LastName);
Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have
been declared to not contain NULL values (when the table was first created).
22
[Link] a PRIMARY KEY Constraint
DROP
MYSQL SQL Server / Oracle
ALTER TABLE Persons ALTER TABLE Persons DROP
DROP PRIMARY KEY; CONSTRAINT PK_Person;
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Persons Table
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
OrderID OrderNumbe PersonID
r
1 77895 3
2 44678 3
3 22456 2
4 24562 1
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.
23
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
In MySQL:
CREATE TABLE Orders (OrderID int NOT NULL,OrderNumber int NOT NULL,PersonID int,
PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
MySQL:
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;
24
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
Primary key will not accept NULL values whereas Unique key can accept NULL values. A
table can have only one primary key whereas there can be multiple unique key on a table.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table
is created:
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following
SQL syntax:
MySQL / SQL Server / Oracle
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, CONSTRAINT UC_Person UNIQUE (ID,LastName));
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:
25
MySQL:
ALTER TABLE Persons DROP INDEX UC_Person;
This enforces a field to always contain a value, which means that you cannot insert a new record,
or update a record without adding a value to this field.
Syntax:
Here is the syntax to remove the constraint NOT NULL for a column in MySQL
Example :
Here is an example to remove the constraint NOT NULL for the column “Name” of the
“Employee” table:
To make sure you don’t miss anything, you can use the statement SHOW CREATE TABLE to
display the full definition of the column:
26
E. Add/drop default constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:
SQL Server:
ALTER TABLE Persons ADD CONSTRAINT df_City DEFAULT 'Sandnes' FOR City;
Oracle:
ALTER TABLE Persons MODIFY City DEFAULT 'Sandnes';
MySQL:
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 column it will allow only certain values for this column.
27
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.
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table
is created. The CHECK constraint ensures that the age of a person must be 18, or older:
MySQL:
CREATE TABLE Persons (ID int NOT NULL,LastName varchar(255) NOT NULL,FirstName
varchar(255),Age int CHECK (Age>=18));
NOTE: To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
CREATE TABLE Persons (ID int NOT NULL,LastName varchar(255) NOT NULL,FirstName
varchar(255),Age int,City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes'));
To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
NOTE: To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
28
F3. DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL
MySQL:
ALTER TABLE Persons DROP CHECK CHK_PersonAge;
ALTER Table
ALTER TABLE Statement
The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.
Example
ALTER TABLE Customers ADD Email varchar(255);
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers DROP COLUMN Email;
29
ALTER TABLE - MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
DROP
This command deletes the information of the table or the database, and it removes the entire
structure/schema of the table or the entire database.
By Using the DROP statement, the objects are permanently deleted or lost from a database, and
they cannot be rolled back.
Whenever an object is deleted, its description is deleted from the catalog, and any packages that
reference the object are invalidated.
Database
Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!
Tip: Once a database is dropped, you can check it in the list of databases with the following SQL
command:
SHOW DATABASES;
Table
30
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!
Example
DROP TABLE Shippers;
TRUNCATE Table
The TRUNCATE statement in MySQL removes the complete data without removing its
structure. It is a part of DDL or data definition language command. Generally, we use this
command when we want to delete an entire data from a table without removing the table
structure.
The TRUNCATE command works the same as a DELETE command without using a WHERE
clause that deletes complete rows from a table. However, the TRUNCATE command is more
efficient as compared to the DELETE command because it removes and recreates the table
instead of deleting single records one at a time.
The following points must be considered while using the TRUNCATE command:
We cannot use the WHERE clause with this command so that filtering of records is not
possible.
We cannot rollback the deleted data after executing this command because the log is
not maintained while performing this operation.
We cannot use the truncate statement when a table is referenced by a foreign key or
participates in an indexed view.
The TRUNCATE command doesn't fire DELETE triggers associated with the table that
is being truncated because it does not operate on individual rows.
Syntax
The following syntax explains the TRUNCATE command to remove data from the table:
Example:
mysql> TRUNCATE TABLE customer;
31
MODIFY
Database
SQL ALTER DATABASE is an essential statement to modify the properties of an existing
database in a Relational Database Management System (RDBMS). This statement is helpful if
you want to rename a database, change its composition, or modify file properties.
Table
The modify command is used when we have to modify a column in the existing
table, like adding a new one, modifying the datatype for a column, and dropping an
existing column.
By using this command, we have to apply some changes to the result set field.
Example
ALTER TABLE csharpcorner_mvps ADD COLUMN MVPKitStatus INT;
Note: Use the “DESCRIBE” command to check the result from the ALTER TABLE ADD
statement
Example.
ALTER TABLE csharpcorner_mvps
ADD COLUMN Country VARCHAR(50),
ADD COLUMN Description VARCHAR(250);
Note. Use the “DESCRIBE” command to check the result from the ALTER
TABLE ADD statement.
32
a) Modify a single column in a table
Syntax
ALTER TABLE employees
MODIFY employee_name VARCHAR(100);
Example.
ALTER TABLE csharpcorner_mvps
MODIFY MVPKitStatus VARCHAR(100);
Note.
Use the “DESCRIBE” command to check the result from the ALTER TABLE
MODIFY statement.
Example.
ALTER TABLE csharpcorner_mvps
MODIFY MVPAddress VARCHAR(250) NOT NULL,
MODIFY MVPKitStatus VARCHAR(100) NOT NULL,
MODIFY Description VARCHAR(221);
SQL
Copy
Note.
Use the “DESCRIBE” command to check the result from the ALTER TABLE
MODIFY statement.
3) DROP a Column
ALTER TABLE DROP COLUMN statement is used to drop the column(s) in a
table.
Syntax
ALTER TABLE employees DROP COLUMN date_of_birth;
Example.
ALTER TABLE csharpcorner_mvps DROP COLUMN Country;
Note. Use the “DESCRIBE” command to check the result from the ALTER
TABLE DROP statement.
33
4) Change Column name
To rename a column in a table, use the following statement.
Syntax
ALTER TABLE employees CHANGE COLUMN emp_name employee_name
VARCHAR(100);
Example.
ALTER TABLE STUDENT CHANGE COLUMN SEX GENDER CHAR;
Note. Use the “DESCRIBE” command to check the result from the ALTER
TABLE CHANGE statement.
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
34
Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
2. 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.
Here, the INSERT INTO syntax would be as follows:
The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):
Example
INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger',
'Norway');
UPDATE
UPDATE Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE
clause, all records in the table will be updated!
The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
35
Example
UPDATE Customers SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the PostalCode to 00000 for all records where country
is "Mexico":
Example
UPDATE Customers SET PostalCode = 00000 WHERE Country = 'Mexico';
DELETE
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
36
Example
DELETE FROM Customers;
CALL
Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog.
These procedures contain IN and OUT parameters, or both. They may return result sets in case
you use SELECT statements; they can return multiple result-sets.
Syntax in MYSQL
DELIMITER
CREATE PROCEDURE ProcedureName()
BEGIN
SQL STATEMENT
END
DELIMITER
EXAMPLE
37
The call statement of MySQL is used to invoke/call a stored procedure.
Syntax
Where procedure_name is the name of an existing procedure you need to call and param1 and
param2... are the list of parameters accepted by the procedure (if it accepts any).
The CALL statement invokes a stored procedure that was defined previously with CREATE
PROCEDURE . Stored procedures that take no arguments can be invoked without parentheses.
Suppose we have created a table named Emp in the database using the CREATE statement and
inserted three records in it as shown below −
CREATE TABLE Emp (
Name VARCHAR(255),
Salary INT,
Location VARCHAR(255));
Assume we have created a stored procedure InsertData which accepts the name, salary and
location values and inserts them as a record into the above create (Emp) table.
DELIMITER //
Create procedure InsertData (
IN name VARCHAR(30),
IN sal INT,
IN loc VARCHAR(45))
BEGIN
INSERT INTO Emp(Name, Salary, Location) VALUES (name, sal, loc);
END //
DELIMITER ;
Verification
Once you call the procedure by passing the required values you can verify the contents of the
Emp table as shown below −
38
SELECT * FROM EMP;
While calling a stored procedure that doesn't accepts any arguments, we can omit the parenthesis
as shown below:
Assume we have created another procedure with name getData that retries the contents of the
table EMP
Since this procedure doesn't accept arguments you can call this procedure by omitting the
parameters as shown below
Output
Following is the output of the above query
LOCK
In the above syntax, we have specified the table name on which we want to acquire a lock after
the LOCK TABLES keywords. We can specify the lock type, either READ or WRITE.
We can also lock more than one table in MySQL by using a list of comma-separated table's
names with lock types. See the below syntax:
Write Locks
The following are the features of a WRITE lock:
o It is the session that holds the lock of a table and can read and write data both from the
table.
o It is the only session that accesses the table by holding a lock. And all other sessions
cannot access the data of the table until the WRITE lock is released.
The following is the syntax that allows us to release a lock for a table in MySQL:
The SELECT statement in MySQL is used to fetch data from one or more tables. We can
retrieve records of all fields or specified fields that match specified criteria using this statement.
The general syntax of this statement to fetch data from tables are as follows:
SELECT field_name1, field_name 2,..., field_nameN FROM table_name1, WHERE condition;
40
The SELECT statement uses the following parameters:
field_name(s) or * It is used to specify one or more columns to returns in the result set. The asterisk
(*) returns all fields of a table.
table_name(s) It is the name of tables from which we want to fetch data.
WHERE It is an optional clause. It specifies the condition that returned the matched records
in the result set.
Example:
1. If we want to retrieve a single column from the table, we need to execute the below query:
2. If we want to query multiple columns from the table, we need to execute the below query:
3. If we want to fetch data from all columns of the table, we need to use all column's names
with the select statement. Specifying all column names is not convenient to the user, so MySQL
uses an asterisk (*) to retrieve all column data as follows:
41
Now, let us use the SELECT DISTINCT statement and see the result.
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in
the "Customers" table:
The following SQL statement counts and returns the number of different (distinct) countries in
the "Customers" table:
An aggregate function in SQL returns one value after calculating multiple values of a column.
We often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT
statement.
An aggregate function ignores NULL values when it performs the calculation, except for the
count function.
42
SQL clause
SQL clause helps us to retrieve a set or bundles of records from the table.
SQL clause helps us to specify a condition on the columns or the records of a table.
1. WHERE CLAUSE
43
mysql> UPDATE employees SET Name = "Harshada Sharma" WHERE City = "Jaipur";
44
45
46
3. HAVING CLAUSE
Example 2:
4. ORDER BY CLAUSE
Whenever we want to sort anything in SQL, we use the ORDER BY clause.
The ORDER BY clause in SQL will help us to sort the data based on the specific column of a
table.
As we all know, sorting means either in ASCENDING ORDER or DESCENDING ORDER. In
the same way, ORDER BY CLAUSE sorts the data in ascending or descending order as per our
47
requirement. The data will be sorted in ascending order whenever the ASC keyword is used with
ORDER by clause, and the DESC keyword will sort the records in descending order.
By default, sorting in the SQL will be done using the ORDER BY clause in ASCENDING order
if we didn't mention the sorting order.
Syntax of ORDER BY clause without asc and desc keyword:
Example 2:
48
Application of DCL commands
DCL commands are used to manage database security and access control.
`ALL PRIVILEGES`: The user is granted all privileges except GRANT OPTION and
PROXY.
`ALTER`: The user can change the structure of a table or database.
`CREATE`: The user can create new databases and tables.
`DELETE`: The user can delete rows in a table.
`INSERT`: The user can add rows to a table.
`SELECT`: The user can read rows from a table.
`UPDATE`: The user can update rows in a table.
GRANT Statement
The grant statement enables system administrators to assign privileges and roles to
the MySQL user accounts so that they can use the assigned permission on the database whenever
required.
Syntax
The following are the basic syntax of using the GRANT statement:
GRANT privilege_name(s) ON object TO user_account_name;
49
Parameter Explanation
Example:
REVOKE statement
50
A database transaction is a series of one or more operations executed as a single atomic unit
of work.
Experts talk about a database transaction as a “unit of work” that is achieved within a
database design environment.
The effects of all the SQL statements in a transaction can be either all committed (applied
to the database) or all rolled back (undone from the database), insuring data consistency.
Transactions have the following four standard properties, usually referred to by the
acronym
ACID.
The following commands are used to control transactions but we are going to focus on the first
three.
Transactional control commands are only used with the DML Commands such as
INSERT, UPDATE and DELETE only.
They cannot be used while creating tables or dropping them because these operations are
automatically committed in the database.
51
COMMIT
The COMMIT Command The COMMIT command is the transactional command used to save
changes invoked by a transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all the transactions to the database.
Following is an example which would delete those records from the table which have age =
24 and then COMMIT the changes in the database.
ROLLBACK
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database.
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: Consider the CUSTOMER table having the following records
52
Following is an example, which would delete those records from the table which have the age =
24 and then ROLLBACK the changes in the database.
BEGIN / START TRANSACTION
DELETE FROM CUSTOMER WHERE CAGE= 24;
ROLLBACK;
Thus, the delete operation would not impact the table and the SELECT statement would produce
the following result.
SAVEPOINT
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.
53
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the
CUSTOMER table.
You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any
SAVEPOINT at any time to return the appropriate data to its original state.
SET Transaction
The SET TRANSACTION Statement in MYSQL is used to set the values to the characteristics
of the current transaction such as transaction isolation level and access mode.
Use the SET TRANSACTION statement to establish the current transaction as read-only or
read/write, establish its isolation level, assign it to a specified rollback segment, or assign a name
to the transaction.
SET Constraints
What is a SQL constraint?
SQL constraints are rules that allow data to be entered into a table only if it meets the predefined
conditions.
They are part of your database schema, the broader set of rules that governs your database.
Constraints 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 table. If there is any violation between the constraint and the data
action, the action is aborted.
54
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
END OF LO 3
55