Explain the basics of Introduction to SQL (Structured Query Language) or
introduction to SQL
SQL(Structured Query Language) is a standardized programming language used to
manage and manipulate relational databases.
SQL is used to query, insert, update, and delete data stored in relational database
management systems (RDBMS) like MySQL, PostgreSQL, Microsoft SQL Server,
Oracle, and SQLite.
1. Database: A collection of data organized in a structured way, usually into
tables.
2. Table:A collection of rows and columns where data is stored .Each table
in a database represents a specific entity, such as customers, products, or
orders.
3. Row: Also known as are tuple, represents a single data entry in a table.
A row contains values corresponding to the columns of the table.
4. Column: Defines the type of data that will be stored in a table. Columns
are also referred to as fields or attributes.
5. Primary Key:A unique identifier for each row in a table. Not rows
can have the same primary key value.
6. Foreign Key :A column that creates a relationship between two tables by
referencing the primary key of another table.
1
Basic SQL Operations
Data Querying
Data Definition Language(DDL)
Data Manipulation Language(DML)
Data Control Language(DCL)
Data Querying (SELECT)
Retrieve data from the table using SELECT query.
Syntax
SELECT column1,
column2, ... FROM
table_name WHERE
condition;
Example 1
SELECT * FROM Employees;
Output
2
Example 2 : Selecting Specific Columns
SELECT Name, Department FROM Employees;
Example 3: Filtering Data Using WHERE Clause
SELECT * FROM Employees WHERE Department = 'IT';
Data Definition Language (DDL)or Explain DDL commands with example
DDL (Data Definition Language) is used to define and manage the structure of database
objects like tables,
3
It includes commands such as
CREATE a table,
ALTER a table,
DROP a table,
TRUNCATE a table,
RENAME a table.
CREATE a table
Create a new database object (table)
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....);
Example 1
SQL>CREATE TABLE student ( ID NUMBER(6) , Name VARCHAR2(100), Address
NUMBER(10 );
Table created
Output
Table student
ID Name Address
Example 2
4
SQL>CREATE TABLE employee ( empID NUMBER(6) , Name VARCHAR2(100),
Address NUMBER(10 );
Table created
Table employee
empID Name Address
Create a table with Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
It does not permit duplication.
Primary Key=Unique +Not null
Syntax
CREATE TABLE table_name
( column1 datatype PRIMARY KEY, column2 datatype, ... );
Example 1
CREATE TABLE Products ( Product_ID NUMBER(4) PRIMARY KEY, Product_Name
VARCHAR2(200), Price NUMBER(8) );
OUTPUT
Table :Products
Product_ID Product_Name Price
Example 2 For primary key
CREATE TABLE student ( STUID NUMBER(4) PRIMARY KEY, stuName
VARCHAR2(200), address Varchar2(10));
OUTPUT
Table :student
5
STUID stuName address
Create a table using foreign Key
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
Syntax
CREATE TABLE child_table ( column1 datatype, column2 datatype REFERENCES
parent_table (parent_column) );
Table1 : Students
CREATE TABLE Students ( StuID NUMBER(5) PRIMARY KEY, Name
VARCHAR2(50), Age NUMBER(2) );
output
StuID Name Age
1 raj 17
2 ravi 18
5 rakesh 19
Table 2 stumarks
CREATE TABLE stumarks (Course_Name VARCHAR2(50), StuID NUMBER(5)
REFERENCES Students (Stu_ID),
output
Course_Name StuID
BCA 1
BCOM 2
BCOM(CA) 5
Alter a table
The ALTER TABLE statement is used to modify an existing table by adding,
modifying, or deleting columns.
6
Syntax
ALTER TABLE table_name
ADD column_name datatype;
Example 1: Adding a New Column
ALTER TABLE student ADD Email VARCHAR2(100);
output
ID Name Address Email
Example 2:ALTER TABLE - DROP COLUMN
Syntax
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE student DROP COLUMN Email;
Output
ID Name Address
Drop aTable
The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
7
Example1
DROP TABLE Shippers;
Example2
DROP TABLE employee;
Example 3
DROP TABLE student;
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
Syntax
TRUNCATE TABLE table_name;
Example 1: Truncate the Students Table
TRUNCATE TABLE Students;
8
Example 2: Truncate the Employees Table
TRUNCATE TABLE Employees;
Deletes all employee records but retains the table structure.
Rename
The RENAME statement is used to change the name of a table or a column in SQL.
Syntax
RENAME TABLE old_table_name TO new_table_name;
Example 1 old table name : Employees
RENAME TABLE Employees TO Staff;
9
Example 2 old table name : students
RENAME Table Students TO Learners;
*********** Data Definition Language or DDL commands end************
Explain Data Manipulation Language(DML)or explain in detail about DML
commands with example
DML is used for managing and manipulating data within database objects (tables). It
includes the following commands:
1. INSERT – To add new records to a table.
2. UPDATE – To modify existing records in a table.
3. DELETE – To remove records from a table.
4. SELECT – To retrieve data from one or more tables.
Insert
The INSERT statement in SQL is used to add new records (rows) to a table. You can
insert data into specific columns or all columns in a table.
10
Syntax
INSERT INTO <tablename> VALUES (value1, value2, value3, ...);
Example 1
SQL>INSERT INTO students values ( 1001, 'Alice', 20);
SQL> INSERT INTO students values ( 1002, 'BOb', 22);
Output
Example 2
SQL>INSERT INTO Employee VALUES (101, 'John', 'Doe', 30, 'Marketing');
SQL> NSERT INTO Employee VALUES (102, 'Jane', 'Smith', 25, 'Sales');
SQL> INSERT INTO Employee VALUES (103, 'David', 'Johnson', 35, 'HR');
Output
Example 3
SQL> CREATE TABLE library_books (
book_id number(5)PRIMARY KEY,
title VARCHAR(100),
author VARCHAR(100));
Table created
Inserting a Single Book
11
INSERT INTO library_books VALUES(1, 'The Alchemist', 'Paulo Coelho');
INSERT INTO library_books VALUES(2, '1984', 'George Orwell');
INSERT INTO library_books VALUES( 3, 'The Great Gatsby', 'F. Scott Fitzgerald');
NSERT INTO library_books Values(4, 'The Hobbit', 'J.R.R. Tolkien');
Output
Update
The UPDATE statement in SQL is used to modify existing records in a table. It allows
you to change one or more columns for specific rows based on conditions.
Syntax
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
UPDATE: Specifies the table to update.
SET: Defines the columns and their new values.
WHERE: Filters which rows to update. (If omitted, all rows will be updated!)
example 1
Example1 Using UPDATE
12
UPDATE students SET grade = 'A+' WHERE name = 'Bob';
UPDATE students SET age = 18, grade = 'B' WHERE name = 'Charlie';
Output
Example2 Using UPDATE
Update a Single Column
UPDATE employees SET salary = 55000 WHERE name = 'John';
output
Update Multiple Columns
UPDATE employees SET department = 'IT', salary = 65000 WHERE name = 'Bob';
13
DELETE
The DELETE statement in SQL is used to remove existing records from a table. You
can delete specific rows based on a WHERE condition or remove all records from a
table.
Syntax:
DELETE FROM table_name WHERE condition;
DELETE FROM table_name — Specifies the table to delete data from.
WHERE — Filters which rows to delete. (Omitting this will delete all rows!)
Example 1
Delete a Specific Row
Remove the student Bob from the table.
DELETE FROM students WHERE name = 'Bob';
Output
14
Delete Multiple Rows Based on Condition
DELETE FROM students WHERE grade = 'B';
Example 2
Delete a Specific Employee
Remove employee Bob from the table.
DELETE FROM employees WHERE name = 'Bob';
Output
15
DELETE FROM employees WHERE department = 'IT';
Output
Select
The SELECT statement in SQL is used to retrieve data from one or more tables.
It allows you to choose specific columns, filter rows, and even perform calculations or
aggregations on the data.
Syntax
SELECT column1, column2, ... FROM table_name WHERE condition;
SELECT — Specifies which columns to retrieve.
FROM — Indicates the table to pull data from.
WHERE (optional) — Filters rows based on conditions.
Example 1
16
Select All Columns
Retrieve all data from the employees table.
SELECT * FROM employees;
Select Specific Columns
Retrieve only employee names and their departments.
SELECT name, department FROM employees;
Select with Condition
Get details of employees with a salary greater than 60000.
SELECT name, salary FROM employees WHERE salary > 60000;
17
Example2
Select All Columns
Retrieve all data from the students table.
SELECT * FROM students;
Select Specific Columns
SELECT name, grade FROM students;
18
Select with Condition
Get details of students with grade 'B'.
SELECT name, age, city FROM students WHERE grade = 'B';
***** DML commands or( data Manipulation Language****
Data Control Language(DCL)
Data Control Language (DCL) is a subset of SQL commands that deals with rights,
permissions, and access control in a database. It is used to grant or revoke user
privileges and control how users interact with the database.
DCL Commands:
1. GRANT — Gives users access privileges to the database.
2. REVOKE — Removes previously granted permissions.
19
Syntax
Example1
Grant SELECT Privilege
Allow user john to read data from the students table.
GRANT SELECT ON students TO john;
Example2
GRANT SELECT ON emplyees TO Raj;
Grant Multiple Privileges
Allow user John to read and insert data into the employees table.
GRANT SELECT, INSERT ON students TO john;
Example 1
REVOKE INSERT ON employees FROM john;
Example 2
REVOKE SELECT ON students FROM john;
Example3
Revoke SELECT ON employees from Raj;
***** Data control Language (or) DCL end ***********
20
Explain Additional Select Query keywords and Queries
Example
Using DISTINCT example
Get a list of unique grades from the students table.
Query1
SELECT DISTINCT grade FROM students;
Output
21
Using BETWEEN
Find students aged between 18 and 20.
Query
SELECT name, age FROM students WHERE age BETWEEN 18 AND 20;
Using IN
List students who live in either Chicago or Miami.
Query
SELECT name, city FROM students WHERE city IN ('Chicago', 'Miami');
Output
22
Using LIKE for Pattern Matching
Find students whose names start with the letter 'A'.
Query
SELECT name FROM students WHERE name LIKE 'A%';
Order BY
Query
SELECT name, marks FROM students ORDER BY marks DESC LIMIT 3;
Group By
The GROUP BY clause groups rows that have the same values in specified columns and
is often used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), or
MAX().
23
Syntax:
SELECT column_name, AGGREGATE_FUNCTION(column_name) FROM
table_name GROUP BY column_name;
AGGREGATE_FUNCTION — Functions like COUNT(), SUM(), AVG(), etc.
GROUP BY — Groups rows that share the same value in one or more columns.
Example
Count Students by Grade
🔄 Find the number of students in each grade.
SELECT grade, COUNT(*) AS student_count FROM students GROUP BY grade;
Average Marks by Grade
Calculate the average marks for each grade.
SELECT grade, AVG(marks) AS average_marks FROM students GROUP BY grade;
24
****** Additional Select Queries and Keywords end************
Explain in detail about Relational Set Operators
Relational Set Operators in SQL are used to combine the results of two or more SELECT
queries. These operators follow set theory principles (like in mathematics) and help manage data
across multiple tables.
Union
Union ALL
Intersect
Minus or Except
Union
The UNION operator in SQL is used to combine the results of two or more SELECT
statements into a single result set. It removes duplicate records by default.
Syntax
SELECT column1, column2, ... FROM table1
UNION
SELECT column1, column2, ... FROM table2;
Both SELECT statements must have the same number of columns with similar data
types.
UNION removes duplicates;
Example
25
SELECT name, course FROM students_science
UNION
SELECT name, course FROM students_arts;
Example 2 for Union
SELECT name, course FROM BCA
UNION
26
SELECT name, course FROM Bcom(CA);
Sample table 1: BCA
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
Sample table 2: BCOM(CA)
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
4 sekar KK nagar
Output
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
4 sekar KK nagar
Union ALL
The UNION ALL operator is used to combine the results of two or more SELECT
statements including duplicates.
Combine both tables and include duplicates.
Syntax
SELECT column1, column2, ... FROM table1
UNION ALL
27
SELECT column1, column2, ... FROM table2;
Example for Union ALL
SELECT name, course FROM BCA
UNION ALL
SELECT name, course FROM Bcom(CA);
Sample table 1: BCA
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
Sample table 2: BCOM(CA)
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
4 sekar KK nagar
Output
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
1 Raj KJ steet
2 Ravi TJ Nagar
4 sekar KK nagar
Example 2 for union All
SELECT name, course FROM students_science
UNION ALL
28
SELECT name, course FROM students_arts;
Output
Intersect
The INTERSECT operator returns common rows from two or more SELECT queries.
Syntax:
SELECT column1, column2, ... FROM table1
INTERSECT
SELECT column1, column2, ... FROM table2;
Both SELECT statements must have the same number of columns with compatible
data types.
Duplicates are automatically removed in the final result.
Example 1 for Intersect
SELECT name, city FROM employees_sales
INTERSECT
SELECT name, city FROM employees_marketing;
29
Output
Example 2 for intersect
Sample table 1: BCA
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
Sample table 2: BCOM(CA)
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
4 sekar KK nagar
30
Output
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
Minus or except
The EXCEPT (or MINUS )operator returns rows from the first SELECT query that are
not present in the second SELECT query.
Syntax
SELECT column1, column2, ... FROM table1
EXCEPT
SELECT column1, column2, ... FROM table2;
Both SELECT statements must have the same number of columns with
compatible data types.
Duplicates are automatically removed from the final result.
Sample Tables:
31
Find Math Students Not Enrolled in Science
🔄 List students who are enrolled in Math but not in Science.
SELECT name FROM students_math
EXCEPT
SELECT name FROM students_science;
Output
Example 2
Sample table 1: BCA
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
3 kamal Jj Nagar
Sample table 2: BCOM(CA)
Sno name address
1 Raj KJ steet
2 Ravi TJ Nagar
4 sekar KK nagar
Output
Sno name address
3 kamal Jj Nagar
***** relational Set Operators end ***************
32
Explain Additional Data Definition Commmands
Data Definition Language (DDL) commands are used to define, modify, and manage
database structures like tables, schemas, and indexes.
RENAME — Rename a Table or Column
🔄 Used to rename existing tables or columns.
Syntax
RENAME TABLE students TO student_records;
Example 2: Rename Column
ALTER TABLE student_records RENAME COLUMN name TO full_name;
COMMENT — Add Comments to Database Objects
🔄 Used to describe tables, columns, or other objects.
COMMENT ON TABLE student_records IS 'This table stores student details';
COMMENT ON COLUMN student_records.full_name IS 'Full name of the student';
[In addition to that Refer data definition Language with example ]
33
TRUNCATE — Remove All Data but Keep Table Structure
Deletes all rows in a table but retains the table structure.
TRUNCATE TABLE student_records;
CREATE INDEX — Improve Query Performance
Creates an index to speed up query searches.
CREATE INDEX idx_student_name ON student_records(full_name);
******Unit IV Completed *******
34