Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

SQL TUTORIALS

WHAT IS SQL ?
• SQL stands for Structured Query Language. It is a standard programming
language designed for managing and manipulating relational databases. SQL is
used to perform tasks such as querying data from databases, updating data,
inserting new data, deleting data, and creating or modifying database schemas
(tables, indexes, views, etc.).

SELECT * FROM EMPLOYEES;


Subset of SQL
• A "subset" of SQL typically refers to a specific set of SQL features or
commands that are supported by a particular database management
system (DBMS) or a standardized version of SQL.

DML (data manipulation language)


DDL (data definition language)
DCL (data control language)
TCL (transaction control language)
Data Manipulation Language (DML) in SQL is a subset of
SQL that consists of commands used for manipulating data
stored in relational databases.

• SELECT: The SELECT statement is used to retrieve data from one or


more database tables. It allows users to specify the columns they want
to retrieve and apply filtering conditions using the WHERE clause.
Example:
SELECT employee_id, salary
FROM employees
WHERE employee_id=100;
 INSERT: The INSERT statement is used to add new records (rows) into a table. It allows
users to specify the values for each column in the new record.

Example:
INSERT INTO EMPLOYEES (employee_id, salary) VALUES (100, 25000);

 UPDATE: The UPDATE statement is used to modify existing records in a table. It allows
users to change the values of one or more columns in existing rows that meet certain
criteria specified by the WHERE clause.

Example:
UPDATE EMPLOYEES
SET SALARY = 26000
WHERE EMPLOYEE_ID=100;
DELETE: The DELETE statement is used to remove one or
more records from a table. It allows users to specify conditions
to identify the records to be deleted.

Example:

DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID=100;


Data Definition Language (DDL) in SQL is a subset of SQL used
for defining and managing the structure of database objects. DDL
commands are responsible for creating, altering, and dropping
database objects such as tables, indexes, views, schemas, and
constraints. Here are the main DDL commands along with their
definitions:
• CREATE: The CREATE statement is used to create new database objects such
as tables, indexes, views, or schemas.
Example:

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
salary DECIMAL(10, 2));
ALTER: The ALTER statement is used to modify the
structure of existing database objects. It can be used to
add, modify, or drop columns in a table, as well as to
modify constraints or rename objects.

Example :

ALTER TABLE employees


ADD email VARCHAR(100);
DROP: The DROP statement is used to
delete existing database objects such as
tables, indexes, views, or schemas.
Example: DROP TABLE EMPLOYEES;
The TRUNCATE statement is used to remove
all records from a table, effectively resetting the
table's data while keeping its structure intact.

Example:

TRUNCATE TABLE EMPLOYEES;


Data Control Language (DCL): DCL SQL commands are used
for controlling access to the database and its objects.
These commands include GRANT (to grant privileges) and
REVOKE (to revoke privileges).

• GRANT: The GRANT command is used to give specific privileges to database


users or roles.
GRANT SELECT, INSERT ON employees TO user1;

• REVOKE: The REVOKE command is used to revoke previously granted


privileges from users or roles.
REVOKE DELETE ON employees FROM user2;
Transactional Control Language (TCL) commands in SQL are used to
manage transactions within a database. The main TCL commands in SQL
are COMMIT, ROLLBACK, and SAVEPOINT. Here's an explanation of
each along with an example:
• COMMIT: The COMMIT command is used to permanently save the changes made in the
current transaction to the database.
COMMIT;

• ROLLBACK: The ROLLBACK command is used to undo changes made in the current
transaction and restore the database to its state before the transaction started.
ROLLBACK;

• SAVEPOINT: The SAVEPOINT command is used to set a named point within a


transaction to which you can later roll back.
SAVEPOINT savepoint_name;
The ORDER BY clause in SQL is used to sort the result set of a SELECT statement
based on one or more columns. By default, sorting is done in ascending order, but you
can specify descending order as well. Here's the syntax of the ORDER BY clause:

Suppose we have a table named students with the following data:

student_id first_name last_name age


1 John Doe 25

2 Jane Smith 23

3 Michael Johnson 22
To retrieve all records from the students table sorted by the students' ages in ascending order:

• SELECT * FROM students ORDER BY age;


This will return this result:

student_id first_name last_name age


3 Michael Johnson 22
2 Jane Smith 23
1 John Doe 25
To retrieve all records from the students table sorted by the students' last names in descending order:

SELECT * FROM students ORDER BY last_name DESC;

This will return:

student_id first_name last_name age


1 John Doe 25
3 Michael Johnson 22
2 Jane Smith 23
The GROUP BY clause in SQL is used to group rows that have the same
values into summary rows. It is typically used in conjunction with
aggregate functions (like SUM, COUNT, AVG, MAX, MIN) to perform
operations on each group.

Suppose we have a table named orders with the following data:

order_id customer_id product_id quantity amount


1 101 1 2 100.00
2 101 2 1 50.00
3 102 1 3 150.00
4 103 3 2 120.00
5 103 2 1 50.00
To get the total amount of orders placed by each customer:

SELECT customer_id, SUM(amount) AS total_amount


FROM orders
GROUP BY customer_id;

customer_id total_amount

101 150.00

102 150.00

103 170.00
To get the total quantity of each product ordered:

SELECT product_id, SUM(quantity) AS total_quantity


FROM orders
GROUP BY product_id;

product_id total_quantity

1 5

2 2

3 2
The HAVING clause in SQL is used to filter the results of a GROUP BY clause
based on specified conditions. It allows you to apply conditions to groups of rows,
rather than individual rows.
Suppose we have one table customers with the following data:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
SELECT ADDRESS, AGE, MIN(SALARY) AS MIN_SUM FROM CUSTOMERS GROUP BY
ADDRESS, AGE
HAVING AGE > 25;

Result is as shown:

ADDRESS AGE MIN_SUM

Ahmedabad 32 2000.00

Bhopal 27 8500.00
In SQL, constraints are rules defined on a table column or a group of columns to enforce
data integrity and ensure accuracy, consistency, and reliability of the data stored in the
database. Constraints help in maintaining the quality of data by restricting the type of
values that can be inserted, updated, or deleted in a table.
• A primary key constraint is a type of constraint that ensures each row in a
table is uniquely identified. It uniquely identifies each record in a table and
ensures that there are no duplicate values in the column or columns defined
as the primary key.

CREATE TABLE students (


student_id INT PRIMARY KEY,
student_name VARCHAR(50),
student_age INT,
student_grade VARCHAR(2));
In SQL, a unique key constraint ensures that all values in a column or a group of
columns are unique. Unlike the primary key constraint, a unique key constraint
allows NULL values, but if a column has a unique key constraint applied, only one
row can have a NULL value in that column.

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
emp_email VARCHAR(50) UNIQUE,
emp_name VARCHAR(50),
emp_age INT,
emp_department VARCHAR(50));
In SQL, a foreign key constraint is a mechanism used to enforce referential
integrity between two tables. It ensures that the values in a column (or a group
of columns) in one table match the values in another table's column, typically
the primary key column of the referenced table.

CREATE TABLE departments (


dept_id INT PRIMARY KEY,
dept_name VARCHAR(50));

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_age INT,
emp_department_id INT,
FOREIGN KEY (emp_department_id) REFERENCES departments(dept_id));
In SQL, a CHECK constraint is a type of constraint that ensures that all values
in a column meet specific conditions or expressions. It allows you to define
conditions that must be satisfied for each row in a table, and any row that
violates these conditions will not be allowed to be inserted or updated.

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_age INT,
emp_salary DECIMAL(10, 2),
emp_department VARCHAR(50),
CONSTRAINT chk_emp_age CHECK (emp_age >= 18 AND emp_age <= 65));
In SQL, the NOT NULL constraint is used to ensure that a column does not
accept NULL values. NULL represents a missing or unknown value in a database,
and sometimes you want to enforce that certain columns must always have a
value.

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
emp_age INT NOT NULL,
emp_salary DECIMAL(10, 2),
emp_department VARCHAR(50));
In SQL, an index is a database structure that improves the speed of data
retrieval operations on a table. It works similar to an index in a book - it
provides a quick way to look up data based on the values of certain columns.
Indexes are created on one or more columns of a table to allow the database
management system (DBMS) to quickly locate rows in the table without having
to scan the entire table sequentially.

CREATE INDEX idx_emp_name ON employees (emp_name);

You can also create composite indexes that span multiple columns:

CREATE INDEX idx_emp_department_salary ON employees


(emp_department, emp_salary);
In Oracle, there are several types of indexes that can be used to optimize
data retrieval and improve query performance. Here are the main types
of indexes in Oracle:

B-Tree Index: This is the most common type of index in Oracle and is suitable for most types of queries.
B-tree indexes are balanced tree structures that allow for efficient searches, range queries, and sorting
operations. They are created using the CREATE INDEX statement.

CREATE INDEX idx_emp_name ON employees (emp_name);


Bitmap Index: Bitmap indexes are particularly useful for low-cardinality columns,
where there are a small number of distinct values. They work by creating a bitmap
for each distinct value in the indexed column(s), which can be very efficient for
certain types of queries, such as data warehousing queries involving boolean
operations or queries with predicates on multiple columns.

CREATE BITMAP INDEX idx_dept_id ON employees(dept_id);


Function-Based Index: Function-based indexes allow you to create an
index based on the result of a function applied to one or more columns
in a table. This can be useful for indexing expressions, calculations, or
transformations of data. Function-based indexes can improve query
performance for certain types of queries involving these expressions.

CREATE INDEX idx_emp_name_upper ON


employees(UPPER(emp_name));
Reverse Key Index: Reverse key indexes are a type of B-tree index where the bytes
of the index key are reversed before being stored in the index. This helps to spread
inserts across the index structure, reducing contention on the rightmost leaf block
and improving concurrency in high-insert environments.

CREATE INDEX idx_emp_id_reverse ON employees(EMP_ID)


REVERSE;

You might also like