SQL
SQL (Structured Query Language) is a standard programming
language used for managing and interacting with relational databases.
SQL commands are categorized based on their functionality:
1. Data definition language: Used to define or modify the
structure of the database
e.g; CREATE TABLE, ADD COLUMN, DROP COLUMN and so on.
2. Data manipulation language: Used to manipulate the data stored
in the database.
e.g.; INSERT, DELETE, UPDATE and so on.
3. Data control language: Used to control access to the database.
4. Transaction control language: Used to manage transactions in a
database.
5. Data Query Language: It is used to extract the data from the
relations.
e.g : SELECT
BASIC STRUCTURE OF SQL :
It consists of three clause :
Select:
The SELECT clause specifies the columns you want to retrieve from
the database
From:
The FROM clause specifies the table (or tables) from which data
will be retrieved.
Where:
The WHERE clause filters rows based on specified conditions. It
determines which rows will be included in the result set.
Syntax:
SELECT column1, column2
FROM table_name
WHERE condition;
Ex:
SELECT name, age
FROM students
WHERE age > 18;
DDL Commands – Syntax
SQL PURPOS SYNTAX EXAMPLE
COMMA E
ND
Database CREATE DATABASE CREATE DATABASE Test;
<DB_NAME>;
CREATE TABLE <TABLE_NAME> CREATE TABLE Student(
CREATE ( student_id INT,
Table
column_name1 datatype1, name VARCHAR(100),
column_name2 datatype2, age INT);
column_name3 datatype3,
column_name4 datatype4
);
Add new ALTER TABLE table_name ADD( ALTER TABLE student
column column_name datatype); ADD(
address
VARCHAR(200) );
ALTER TABLE table_name ADD( ALTER TABLE table_name
Add ADD(
column_name1 datatype1,
multiple Reg_no INT,
column-name2 datatype2,
column Stud_name
column-name3 datatype3);
VARCHAR(100),
ALTER Age INT);
Column ALTER TABLE table_name ADD( ALTER TABLE student
with column-name1 datatype1 ADD(
default DEFAULT some_value ); dob DATE DEFAULT
value '01-Jan-99');
Modify an ALTER TABLE table_name ALTER TABLE student
existing modify( MODIFY(
column address varchar(300));
column_name datatype );
Rename ALTER TABLE table_name ALTER TABLE student
a column RENAME RENAME
old_column_name TO address TO location;
new_column_name;
Drop a ALTER TABLE table_name DROP( ALTER TABLE student
column column_name); DROP(
address);
TRUNCATE TRUNCATE TABLE table_name TRUNCATE TABLE
student;
DROP DROP TABLE table_name DROP TABLE student;
DROP DATABASE Test;
RENAME RENAME TABLE old_table_name RENAME TABLE student
to new_table_name to students_info;
DML Commands – Syntax
SQL Commands
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables
SQL PURPOS SYNTAX EXAMPLE
COMMA E
ND
Data or INSERT INTO table_name INSERT INTO student
values VALUES(data1, data2, ...) VALUES(101, 'Adam', 15);
Specify INSERT INTO student(id,
INSERT columns name) values(102,
'Alex');
INSERT INTO student(id, name)
values(102, 'Alex'); INSERT INTO Student
Null
VALUES(102,'Alex', null);
value
Default INSERT INTO Student
value VALUES(103,'Chris',
default)
Any UPDATE student SET
record age=18 WHERE
student_id=102;
Updating UPDATE student SET
UPDATE multiple UPDATE table_name SET name='Abhi', age=17
column column_name = new_value
where s_id=103;
WHERE some_condition;
Incremen UPDATE student SET age
t integer = age+1;
value
All DELETE FROM student;
records
DELETE DELETE FROM table_name;
from
table
Particular DELETE FROM student
record WHERE s_id=103;
TCL Commands - Syntax
SQL SYNTAX EXAMPLE
COMMAND
INSERT INTO class VALUES(5,
COMMIT COMMIT; 'Rahul');
COMMIT;
UPDATE class SET name = 'Abhijit'
WHERE id = '5';
SAVEPOIN SAVEPOINT
T savepoint_name; SAVEPOINT A;
INSERT INTO class VALUES(6,
'Chris');
SAVEPOINT B;
INSERT INTO class VALUES(7,
'Bravo');
SAVEPOINT C;
SELECT * FROM class;
ROLLBACK TO B;
ROLLBACK ROLLBACK TO
savepoint_name; SELECT * FROM class;
DQL Commands - Syntax
SQL PURPOS SYNTAX EXAMPLE
COMMA E
ND
SELECT SELECT s_id, name, age
column_name1,
column_name2, FROM student;
column_name3,
...
column_nameN
FROM table_name;
SELECT
INSERT INTO student(id,
All record SELECT * FROM student;
name) values(102, 'Alex');
Particular
SELECT * FROM student SELECT eid, name,
record salary+3000 FROM
based on WHERE name = 'Abhi'; employee;
condition
DCL Commands - Syntax
SQL PURPOSE SYNTAX
COMMAND
Create session GRANT CREATE SESSION TO username;
Create table GRANT CREATE TABLE TO username;
GRANT
All privilege GRANT sysdba TO username
Drop any table GRANT DROP ANY TABLE TO username
REVOKE Get back REVOKE CREATE TABLE FROM username
permissions
The SQL Set operation is used to combine the two or more SQL SELECT
statements.
Types of Set Operation
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or
more SQL SELECT queries.
o In the union operation, all the number of datatype and columns
must be same in both the tables on which UNION operation is being
applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
Example:
The First table
ID NAME
1 Jack
2 Harry
3 Jackson
The Second table
ID NAME
3 Jackson
4 Stephan
5 David
Union SQL query will be:
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;
Note: The asterisk (*) is a wildcard character that means "all columns."
“USING UNION DUPLICATES ARE REMOVED”
The resultset table will look like:
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set
without removing duplication and sorting the data.
Syntax:
1. SELECT column_name FROM table1
2. UNION ALL
3. SELECT column_name FROM table2;
Example: Using the above First and Second table.
Union All query will be like:
1. SELECT * FROM First
2. UNION ALL
3. SELECT * FROM Second;
NOTE : “USING UNION ALL DUPIULICATE ARE NOT REMOVED”
The resultset table will look like:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect
operation returns the common rows from both the SELECT
statements.
o In the Intersect operation, the number of datatype and columns
must be the same.
o It has no duplicates and it arranges the data in ascending order by
default.
Syntax
1. SELECT column_name FROM table1
2. INTERSECT
3. SELECT column_name FROM table2;
Example:
Using the above First and Second table.
Intersect query will be:
1. SELECT * FROM First
2. INTERSECT
3. SELECT * FROM Second;
The result set table will look like:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is
used to display the rows which are present in the first query but
absent in the second query.
o It has no duplicates and data arranged in ascending order by
default.
Syntax:
1. SELECT column_name FROM table1
2. MINUS
3. SELECT column_name FROM table2;
Example
Using the above First and Second table.
Minus query will be:
1. SELECT * FROM First
2. MINUS
3. SELECT * FROM Second;
The result set table will look like:
ID NAME
1 Jack
2 Harry
5.Except:
Unique rows from the first table that are not found in the second table are
selected.
Syntax :
Select *FROM first table
Except
Select *from second table
Result :
ID NAME
1 Jack
2 Harry
Aggregate Functions in SQL:
Aggregate functions are used to perform calculations on a set of values
and return a single value.
o COUNT():
Syntax;
COUNT(column_name);
o SUM():
Syntax:
SUM(column_name);
o AVG():
AVG(column_name);
id product region amount
1 Apple East 100
2 Banana West 150
3 Apple East 200
4 Apple West 250
5 Banana East 300
Example:
SELECT product, SUM(amount) AS total_sales
FROM sales
GROUP BY product;
Output:
product total_sales
Apple 550
Banana 450
Nested Subqueries in SQL
A nested subquery (or subquery within a subquery) is a query
inside another query. It is used to perform operations that require
a second query to filter or manipulate the data of the main query.
There are two main types of subqueries:
1. Single-row subquery: Returns a single value.
2. Multiple-row subquery: Returns multiple rows
Syntax:
SELECT column1, column2
FROM table_name
WHERE column1 = (SELECT column_name FROM another_table
WHERE condition);
Join Expression in SQL
A join in SQL is used to combine rows from two or more tables based on a
related column between them. The join expression specifies the
condition for combining the rows, typically involving matching columns
from the tables.
Types of Joins:
1. Inner Join
2. Outer Join (Left, Right, Full)
3. Cross Join
4. Self Join
1. Inner Join
The INNER JOIN returns only the rows where there is a match in both
tables based on the join condition.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Example:
Combine employee data with their department information.
Tables:
employees:
emp_id emp_name dept_id
1 Alice 101
2 Bob 102
3 Charlie 103
departments:
dept_id dept_name
101 HR
102 IT
Query:
SELECT emp_name, dept_name
FROM employees
INNER JOIN departments
ON employees.dept_id = departments.dept_id;
Output:
emp_name dept_name
Alice HR
Bob IT
Only rows with matching dept_id in both tables are returned.
2. Left Outer Join (Left Join)
The LEFT JOIN returns all rows from the left table, and matching rows
from the right table. If no match is found, NULL is returned for columns
from the right table.
For detail : https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-
and-full-joins/
3. Right Outer Join (Right Join)
The RIGHT JOIN is similar to the left join, but it returns all rows from the
right table and matching rows from the left table.
4. Full Outer Join
The FULL OUTER JOIN returns all rows from both tables. If there’s no
match, NULL is returned for missing values.
5. Cross Join
The CROSS JOIN produces a Cartesian product, meaning every row in the
first table is combined with every row in the second table.
6. Self Join
A SELF JOIN is a join of a table with itself. It is useful for comparing rows
within the same table.
Transactions in SQL
A transaction in SQL is a sequence of one or more SQL statements
that are executed as a single unit of work.
Transactions are used to ensure data integrity and consistency in
a database, especially in environments with multiple concurrent
users or operations.
Key Properties of Transactions (ACID):
1. Atomicity:
o Ensures that a transaction is all-or-nothing.
o If one part of the transaction fails, the entire
transaction is rolled back.
2. Consistency:
o Ensures that the database transitions from one valid
state to another valid state.
o The database's rules and constraints are preserved.
3. Isolation:
o Ensures that transactions are executed independently.
o Changes made by one transaction are not visible to
other transactions until committed.
4. Durability:
o Ensures that once a transaction is committed, its
changes are permanent, even in the event of a system
failure.
Integrity Constraints in SQL
Integrity constraints are rules applied to database tables to ensure the
accuracy, consistency, and reliability of the data stored in them. These
constraints enforce business rules on data, ensuring that the database
remains valid and meaningful.
Types of Integrity Constraints:
Primary Key Constraint:
Ensures that each row in a table has a unique identifier.
A column or combination of columns marked as a primary
key must contain unique and non-null values.
Syntax:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50)
);
Foreign Key Constraint:
Establishes a relationship between two tables.
Ensures that a value in one table corresponds to a value in
another table (referential integrity).
Syntax:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES
customers(customer_id)
);
Note here the customer _id is common in both tables (orders and
customers).
Not Null Constraint:
Ensures that a column cannot have NULL values.
Syntax:
CREATE TABLE departments (
dept_id INT NOT NULL,
dept_name VARCHAR(50) NOT NULL
);
Authorization in SQL
Authorization in SQL refers to the process of granting or restricting access
to database resources based on user roles and privileges. It ensures that
only authorized users can perform specific operations, such as reading,
modifying, or deleting data, maintaining data security and integrity.
Syntax:
GRANT privilege_name ON object_name TO user_name;
Example :
GRANT select ON student TO user_1;
Note:Grant the permission to user_1 to view the student table
Now, user1 can run the following query:
SELECT * FROM employees;