Unit-03 Structured Query Language (SQL)
Unit-03 Structured Query Language (SQL)
Unit-03 Structured Query Language (SQL)
1
2
SQL
• SQL is a standard language for accessing and manipulating databases.
What is SQL?
o SQL stands for Structured Query Language
o SQL lets you access and manipulate databases
o SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
3
Introduction to Relational Database
→ A relational database is a type of database that stores and organizes data in a structured manner
based on the principles of the relational model. This model represents data as tables with rows and
columns, and it establishes relationships between tables.
→ Relational databases are widely used in various applications and industries due to their ability to
model complex relationships between entities and provide a reliable, structured way to store and
retrieve data. Popular relational database management systems (RDBMS) include MySQL,
PostgreSQL, Microsoft SQL Server, and Oracle Database.
DDL
• DDL is used for specifying the database schema. It is used for creating tables, schema, indexes, constraints
etc. in database. Lets see the operations that we can perform on database using DDL:
• To create the database instance – CREATE
• To alter the structure of database – ALTER
• To drop database instances – DROP
• To delete tables in a database instance – TRUNCATE
• To rename database instances – RENAME
• To drop objects from database such as tables – DROP
• To Comment – Comment
• All of these commands either defines or update the database schema that’s why they come under Data
Definition language.
REVOKE SELECT, UPDATE ON student FROM BCA, MCA; Grant select , update on Student to
root,santosh123.
1. SELECT Clause:
→ The SELECT clause is used to specify the columns you want to retrieve from one or more tables. It
is followed by a comma-separated list of column names or expressions.
Example: SELECT column1, column2 FROM table name;
2. FROM Clause:
→ The FROM clause specifies the table or tables from which to retrieve data. It comes after the
SELECT clause.
Example: SELECT column1, column2 FROM employees;
3. WHERE Clause:
6
→ The WHERE clause is used to fetch the data which specify the given condition. It is used to filter
records and select only necessary records. It is used with SELECT, UPDATE, DELETE, etc. query.
SQL also implements and, or, and not in the WHERE clause which is known as the Boolean
condition.
Example: SELECT column1, column2 FROM employees WHERE department = 'IT';
4. INSERT INTO Statement:
→ The INSERT INTO statement is used to insert new records into a table.
Example: INSERT INTO employees (employee_id, employee_name, department_id, salary)
VALUES (1, 'John Doe', 101, 60000);
5. UPDATE Statement:
→ The UPDATE statement is used to modify existing records in a table.
Example: UPDATE employees SET salary = 65000 WHERE employee_id = 1;
6. DELETE Statement:
→ The DELETE statement is used to remove records from a table.
Example: DELETE FROM employees WHERE employee_id = 1;
7. HAVING Clause
→ The HAVING clause is generally used along with the GROUP BY clause. This clause is used in the
column operation and is applied to aggregate rows or groups according to given conditions.
String/Pattern Matching
String or pattern matching in a database involves searching for specific patterns, substrings, or characters
within text data. SQL provides several operators and functions to perform string matching operations.
String or pattern matching in a database involves searching for specific patterns, substrings, or characters
within text data. SQL provides several operators and functions to perform string matching operations. Here
are some commonly used SQL constructs for string/pattern matching:
1. LIKE Operator:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
7
SELECT * FROM employees WHERE last_name LIKE '_o%';
2. SUBSTRING Function:
The SUBSTRING function extracts a substring from a string.
SELECT SUBSTRING(last_name FROM 1 FOR 3) AS initials FROM employees;
7. TRIM Function:
The TRIM function removes specified prefixes or suffixes from a string.
SELECT TRIM(BOTH ' ' FROM email) AS trimmed_email FROM employees;
8
SELECT * FROM employees ORDER BY salary DESC;
3. Expression in ORDER BY:
SELECT * FROM employees ORDER BY LENGTH(first_name) DESC;
Cartesian product
A Cartesian product, also known as a cross product, is a mathematical operation that returns all possible
combinations of two sets. In the context of databases, particularly relational databases, the Cartesian
product involves combining all rows from two or more tables, resulting in a new table where each row is a
combination of rows from the original tables. This operation is expressed using the Cartesian product
symbol (×) or the CROSS JOIN keyword in SQL.
Basic Syntax in SQL:
SELECT * FROM table1 CROSS JOIN table2;
In this example, the Cartesian product of table1 and table2 is formed by combining every row from table1
with every row from table2.
Join Conditions:
The join condition specifies how tables should be connected. It typically involves matching values in
corresponding columns between the tables.
1. Equi Join:
The most common join condition where tables are joined based on the equality of values in the specified
columns.
SELECT * FROM employees JOIN departments ON employees.department_id =
departments.department_id;
2. Non-Equi Join:
Joining tables based on a condition other than equality (e.g., using <, >, <=, >=).
SELECT *FROM orders JOIN products ON orders.product_id > products.product_id;
3. Self Join:
Joining a table with itself. This is often used when you have hierarchical data within a single table.
SELECT e1.employee_id, e1.first_name, e1.manager_id, e2.first_name AS manager_name FROM
employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;
4. Cross Join:
Implicitly joins every row from the first table with every row from the second table, resulting in a Cartesian
product.
SELECT * FROM table1 CROSS JOIN table2;
10
SELECT column1, column2 FROM table2;
2. Intersection ( ∩ ):
• The intersection operation returns a new set that contains only the common rows between two sets.
• In terms of SQL, the INTERSECT operator is used to perform an intersection operation between
two SELECT statements.
Example:
SELECT column1, column2 FROM table1
INTERSECT
SELECT column1, column2 FROM table2;
Null Values
In Database Management Systems (DBMS), a NULL value is a special marker used to indicate that a data
value does not exist in the database. NULL is not the same as an empty string or zero; it specifically
represents the absence or unknown status of a value. A column in a database table can contain NULL
values, even if it is defined to hold a particular data type.
Nested Queries: Set membership Test, Set Comparison and Test for Empty Relations
11
Nested queries, also known as subqueries, are queries that are embedded within another query. They are
used for various purposes like set membership tests, set comparison, and testing for empty relations.
2. Set Comparison
Set comparison involves comparing the result of a subquery with a set of values or another subquery using
comparison operators.
Example using =:
SELECT product_name FROM products WHERE price = (SELECT MAX(price) FROM products);
12
Aggregate Functions, Group by Clause and Having Clause
In SQL, aggregate functions, the GROUP BY clause, and the HAVING clause are used together to perform
operations on groups of rows and filter the results based on aggregate conditions.
1. Aggregate Functions:
Aggregate functions operate on a set of values and return a single value. Common aggregate functions
include:
SUM (): Calculates the sum of values in a numeric column.
SELECT SUM (salary) AS total_salary FROM employees;
2. GROUP BY Clause:
The GROUP BY clause is used to group rows that have the same values in specified columns into summary
rows. It is often used in conjunction with aggregate functions to perform operations on each group.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;
In this example, rows are grouped by the department_id column, and the average salary is calculated for
each department.
13
3. HAVING Clause:
The HAVING clause is used to filter the results of a GROUP BY query based on aggregate conditions. It
is similar to the WHERE clause but is applied after the GROUP BY operation.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;
In this example, the HAVING clause filters out groups where the average salary is less than or equal to
50,000.
INSERT INTO employees (employee_id, first_name, last_name, salary) VALUES (2, 'Jane', 'Smith',
60000), (3, 'Bob', 'Johnson', 55000);
2. DELETE Operation:
The DELETE statement is used to remove records from a table based on a specified condition.
DELETE FROM employees WHERE employee_id = 1;
14
DELETE FROM employees;
3. UPDATE Operation:
The UPDATE statement is used to modify the values of existing records in a table based on a specified
condition.
UPDATE employees SET salary = 55000 WHERE employee_id = 2;
Data Definition Language: Domain Types in SQL, Create, Alter and Drop statements
In SQL, the Data Definition Language (DDL) is responsible for defining and managing the structure of the
database. DDL includes statements for creating, altering, and dropping database objects. Here are some key
DDL statements related to domain types, and creating, altering, and dropping database objects:
1. Domain Types:
A domain is a set of values representing the attributes of an entity. In SQL, data types define the domain of
a column. Common domain types include INTEGER, VARCHAR, DATE, etc.
2. CREATE Statement:
The CREATE statement is used to create database objects such as tables, views, indexes, etc.
Example: Creating a Table:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
Example: Creating a View
CREATE VIEW high_salary_employees AS SELECT * FROM employees WHERE salary > 50000;
3. ALTER Statement:
The ALTER statement is used to modify the structure of an existing database object.
Example: Adding a Column to a Table:
ALTER TABLE employees ADD COLUMN email VARCHAR(100);
15
Example: Modifying a Column in a Table:
ALTER TABLE employees MODIFY COLUMN salary DECIMAL(10,2);
4. DROP Statement:
The DROP statement is used to remove database objects like tables, views, or indexes.
Example: Dropping a Table:
DROP TABLE employees;
Example: Dropping a View:
DROP VIEW high_salary_employees;
View
In a Database Management System (DBMS), a view is a virtual table based on the result of a SELECT
query. It does not store the data itself but provides a way to represent the data stored in one or more tables
in a specific way. Views can be used for various purposes in a database, and their primary concept is to
provide a logical abstraction of the underlying tables.
16
Authorization in SQL : grant and revoke privileges
In SQL, authorization involves controlling access to database objects and operations. The GRANT and
REVOKE statements are used to assign and remove privileges, respectively, for users and roles. Privileges
can include the ability to SELECT, INSERT, UPDATE, DELETE, or perform other operations on tables,
views, and other database objects. Here's an overview of how GRANT and REVOKE are used:
GRANT Statement:
The GRANT statement is used to give specific privileges to users or roles. The syntax generally looks like
this:
GRANT privilege(s) ON object TO user_or_role [WITH GRANT OPTION];
→ privilege(s): The specific privileges being granted (e.g., SELECT, INSERT, UPDATE, DELETE).
→ object: The database object (e.g., table, view) on which the privileges are granted.
→ user_or_role: The user or role receiving the privileges.
→ WITH GRANT OPTION: Optionally allows the recipient to grant the same privileges to other users
or roles.
Example: Granting SELECT privilege on a table
GRANT SELECT ON employees TO john_doe;
REVOKE Statement:
The REVOKE statement is used to remove specific privileges from users or roles. The syntax generally
looks like this:
REVOKE privilege(s) ON object FROM user_or_role [CASCADE];
→ privilege(s): The specific privileges being revoked.
→ object: The database object from which privileges are revoked.
→ user_or_role: The user or role from which privileges are revoked.
→ CASCADE: Optional keyword that revokes the specified privileges from the target user or role and
any roles that depend on it.
Example: Revoking INSERT privilege on a table
REVOKE INSERT ON employees FROM john_doe;
17