0% found this document useful (0 votes)
2 views48 pages

Structured Query Language

The document provides a comprehensive overview of SQL (Structured Query Language), covering its history, characteristics, components, and various types of databases. It details SQL data types, operators, commands, and functionalities essential for managing and manipulating relational databases. Additionally, it explains the importance of databases, their features, and the role of Database Management Systems (DBMS) in ensuring data integrity and efficient access.

Uploaded by

bishtkaran126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views48 pages

Structured Query Language

The document provides a comprehensive overview of SQL (Structured Query Language), covering its history, characteristics, components, and various types of databases. It details SQL data types, operators, commands, and functionalities essential for managing and manipulating relational databases. Additionally, it explains the importance of databases, their features, and the role of Database Management Systems (DBMS) in ensuring data integrity and efficient access.

Uploaded by

bishtkaran126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

SQL

(STRUCTURED QUERY
LANGUAGE)
Contents
SQL Introduction ....................................................................................................................... 5
SQL History........................................................................................................................... 5
What are the Characteristics of SQL? ................................................................................... 5
Components of a SQL System .............................................................................................. 6
What is Database? ..................................................................................................................... 6
Key Features of a Database ................................................................................................... 6
Why is a Database Important? .............................................................................................. 7
Types of Databases ................................................................................................................ 7
What is a DBMS? ................................................................................................................ 10
SQL Data Types....................................................................................................................... 10
Data types ............................................................................................................................ 11
Operators in SQL..................................................................................................................... 12
Types of SQL Operators ...................................................................................................... 12
Arithmetic Operators ....................................................................................................... 12
Comparison Operators..................................................................................................... 13
Logical Operators ............................................................................................................ 13
Bitwise Operators ............................................................................................................ 13
Compound Operators ...................................................................................................... 14
SQL Commands ...................................................................................................................... 14
1. Data Definition Language (DDL) ................................................................................... 15
Common DDL Commands .............................................................................................. 15
2. Data Manipulation Language .......................................................................................... 15
Common DML Commands ............................................................................................. 15
3. Data Control Language ................................................................................................... 15
Common DCL Commands .............................................................................................. 15
4. Transaction Control Language ........................................................................................ 15
Common TCL Commands .............................................................................................. 16
Database Related Queries........................................................................................................ 16
SQL Table ................................................................................................................................ 16
CREATE TABLE ................................................................................................................ 17
DROP TABLE ..................................................................................................................... 18
ALTER Command in SQL .................................................................................................. 19
DROP and TRUNCATE .......................................................................................................... 19
SQL SELECT queries ............................................................................................................. 20
SQL UPDATE Statement .................................................................................................... 22
SQL Clauses ............................................................................................................................ 23
Aggregate functions ................................................................................................................ 24
SQL Data Constraints .............................................................................................................. 25
SQL Joins ................................................................................................................................ 29
Inner Join ............................................................................................................................. 29
Example of SQL INNER JOIN ......................................................................................... 30
LEFT JOIN (LEFT OUTER JOIN)..................................................................................... 30
SQL RIGHT JOIN ............................................................................................................... 31
SQL Full Join ...................................................................................................................... 33
SQL Date Data Types .............................................................................................................. 35
SQL Date Functions ............................................................................................................ 35
String functions ....................................................................................................................... 36
Common SQL String Functions .......................................................................................... 36
Numeric Functions .................................................................................................................. 37
Commonly Used SQL Numeric Functions ......................................................................... 37
SQL Views ............................................................................................................................... 38
CREATE VIEWS IN SQL .................................................................................................. 38
Examples ........................................................................................................................... 39
Listing all Views in a Database ........................................................................................... 41
Delete View in SQL ............................................................................................................ 41
Update View in SQL ........................................................................................................... 41
Example ............................................................................................................................... 41
SQL Indexes ............................................................................................................................ 42
Creating an Index ................................................................................................................ 42
Creating a Unique Index: ................................................................................................ 43
When Should Indexes Be Created? ..................................................................................... 43
Example ............................................................................................................................... 43
DROP INDEX ..................................................................................................................... 44
Subqueries in SQL................................................................................................................... 44
Examples of SQL Subqueries.............................................................................................. 45
SQL Wildcard Characters ........................................................................................................ 45
Types of SQL Wildcard Characters ..................................................................................... 45
Example of SQL Wildcard Characters ................................................................................ 46
SQL Introduction

SQL is a short-form of the structured query language. It is a standardized programming


language used to manage and manipulate relational databases. It enables users to perform a
variety of tasks such as querying data, creating and modifying database structures, and
managing access permissions. SQL is widely used across various relational database
management systems such as MySQL, PostgreSQL, Oracle, and SQL Server.
Whether we’re handling a small user database or analysing terabytes of sales records, SQL
allows efficient querying, updating, and management of relational databases. When data
needs to be retrieved from a database, SQL is used to construct and send the request. The
Database Management System (DBMS) processes the SQL query, retrieves the requested
data, and returns it to the user or application. Instead of specifying step-by-step procedures,
SQL statements describe what data should be retrieved, organized, or modified, allowing the
DBMS to handle how the operations are executed efficiently.
SQL History

 SQL was invented in 1970s and was first commercially distributed by Oracle.
 The original name was given by IBM as Structured English Query Language,
abbreviated by the acronym SEQUEL.

What are the Characteristics of SQL?

 User-Friendly and Accessible: SQL is designed for a broad range of users, including
those with minimal programming experience, making it approachable for non-technical
individuals.
 Efficient Database Management: SQL enables the creation, modification, and
management of databases efficiently, saving time and simplifying complex database
operations.
 Standardized Language: Based on ANSI (American National Standards Institute) and
ISO (International Organization for Standardization) standards, SQL ensures
consistency and stability across various database management systems (DBMS).
 Command Structure: SQL does not require a continuation character for multi-line
queries, allowing flexibility in writing commands across one or multiple lines.
 Execution Mechanism: Queries are executed using a termination character (e.g., a
semicolon ;), enabling immediate and accurate command processing.
 Built-in Functionality: SQL includes a rich set of built-in functions for data
manipulation, aggregation, and formatting, empowering users to handle diverse data-
processing needs effectively.

Components of a SQL System

A SQL system consists of several key components that work together to enable efficient data
storage, retrieval, and manipulation. Some of the Key components of a SQL System are:
 Databases: Databases are structured collections of data organized into tables, rows, and
columns. Databases serve as repositories for storing information efficiently and provide
a way to manage and access data.
 Tables: Tables are the fundamental building blocks of a database, consisting of rows
(records) and columns (attributes or fields). Tables ensure data integrity and consistency
by defining the structure and relationships of the stored information.
 Queries: Queries are SQL commands used to interact with databases. They enable users
to retrieve, update, insert, or delete data from tables, allowing for efficient data
manipulation and retrieval.
 Constraints: Constraints are rules applied to tables to maintain data
integrity. Constraints define conditions that data must meet to be stored in the database,
ensuring accuracy and consistency.
 Transactions: Transactions are groups of SQL statements that are executed as a single
unit of work. Transactions ensure data consistency and integrity by allowing for the
rollback of changes if any part of the transaction fails.

What is Database?

A database is an electronically stored, systematic collection of data that can


include words, numbers, images, videos, and other types of files. Databases are managed
using specialized software called a Database Management System (DBMS), which allows
users to store, retrieve, and manipulate data efficiently. Databases are the backbone of
modern applications, supporting businesses, organizations, and systems across industries.

Key Features of a Database

 Organized Data Storage: Data is stored in structured formats, such as tables,


documents, or key-value pairs.
 Efficient Access: Advanced search and query capabilities allow for quick data retrieval.
 Security and Scalability: Databases provide robust security measures and can scale
with growing data needs.

Why is a Database Important?

Databases play a critical role in managing and organizing data, enabling businesses to
operate efficiently and make informed decisions. Here’s why they are essential:
1. Efficient Scaling: Databases can handle massive amounts of data, scaling to millions or
billions of records. Without databases, managing this level of digital data would be impossible.
2. Data Integrity: Built-in rules and conditions in databases ensure data
consistency and accuracy, even as it grows or changes.
3. Data Security: Databases protect sensitive information by implementing user
authentication, access control, and compliance with privacy regulations.
4. Data Analytics: Modern databases support analytics tools to identify patterns, trends,
and predictions. This capability helps organizations make data-driven decisions.

Types of Databases

1. Hierarchical Databases: These databases organize data in a tree-like structure where


data is arranged in levels or ranks. Higher-level data serves as a common link
for lower-level data, similar to a hierarchy. For example, in a university, “University”
is at the top level, while “Departments” and “Administration” are at lower levels,
even though they are distinct entities.

2. Network Databases: A network database builds on the hierarchical model but allows
child records to link to multiple parent records, creating a web-like structure of
interconnected data. For example, in a university database, “Students,” “Faculty,” and
“Resources” can be linked to both “Departments” and “Clubs,” forming a flexible, two-
directional relationship.

3. Object-Oriented Databases: Object-oriented databases are based on the principles


of object-oriented programming (OOP), where data is stored as objects. These objects
include attributes (data) and methods (functions), making them
easily referenced and manipulated. For instance, a “Person” object in the database could
include attributes like Name and Address and methods like getLatestAddress () to
retrieve information.

4.Relational Databases: Considered the most mature of all databases, these databases lead
in the production line along with their management systems. In this database, every piece of
information has a relationship with every other piece of information. This is on account of
every data value in the database having a unique identity in the form of a record.

5. Cloud Databases: A cloud database operates in a virtual environment hosted on cloud


computing platforms. It is designed for storing, managing, and executing data over the internet,
providing flexibility and scalability. Cloud databases are widely used for applications
requiring dynamic workloads, as they eliminate the need for on-premises infrastructure.
Popular cloud platforms offering database services include:
 Amazon Web Services (AWS)
 Google Cloud Platform (GCP)
 Microsoft Azure
 ScienceSoft
6. Centralized Database: A centralized database is a database stored and managed at a single
location, such as a central server or data centre. It ensures higher security and consistency as
all data is maintained in one place, making it easier to control and manage. Centralized
databases are commonly used in enterprise systems where data consistency and security are
critical.
7. Personal Databases: A personal database is a small-scale database designed for a single
user, typically used on personal computers or mobile devices. These databases are ideal for
managing individual data like contacts, budgets, notes, or schedules. They are lightweight,
easy to use, and require minimal database administration, making them accessible for non-
technical users.
Examples:
 Microsoft Access: A simple database solution for personal or small business needs.
 SQLite: A lightweight, self-contained database commonly used in mobile and desktop
applications.

8. Operational Databases: An operational database is designed to manage and process real-


time data for daily operations within organizations and businesses. It allows users to create,
update, and delete data efficiently, ensuring that the database reflects current activities and
transactions.
9. NoSQL Databases: A NoSQL database (short for “non-SQL” or “non-relational”) provides
a mechanism for storing and retrieving data that does not rely on traditional table-based
relational models. Instead, it uses flexible data models like key-value
pairs, documents, column families, or graphs, making it ideal for handling unstructured, semi-
structured, and structured data.
NoSQL databases are known for their simplicity of design, horizontal scalability (adding
more servers for scaling), and high availability. Unlike relational databases, their data
structures allow faster operations in certain use cases. MongoDB, for instance, is a widely
used document-based NoSQL database.

What is a DBMS?

A DBMS is a system that allows users to create, modify, and query databases while
ensuring data integrity, security, and efficient data access. Unlike traditional file systems,
DBMS minimizes data redundancy, prevents inconsistencies, and simplifies data management
with features like concurrent access and backup mechanisms. It organizes data
into tables, views, schemas, and reports, providing a structured approach to data management.
Example:
A university database can store and manage student information, faculty records, and
administrative data, allowing seamless retrieval, insertion, and deletion of information as
required.

SQL Data Types

SQL Data Types are very important in relational databases. It ensures that data is stored
efficiently and accurately. Data types define the type of value a column can hold, such
as numbers, text, or dates.
Data types mainly classified into three categories for every database.
o String Data types
o Numeric Data types
o Date and time Data types
Data types
❖ CHAR
o Description: String (0-255), can store characters of fixed length
o Usage: CHAR(50)
❖ VARCHAR
o Description: String (0-255), can store characters up to a given length
o Usage: VARCHAR(50)
❖ BLOB
o Description: String (0-65535), can store binary large objects
o Usage: BLOB(1000)
❖ INT
o Description: Integer (-2,147,483,648 to 2,147,483,647)
o Usage: INT
❖ TINYINT
o Description: Integer (-128 to 127)
o Usage: TINYINT
❖ BIGINT
o Description:Integer(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
o Usage: BIGINT
❖ BIT
o Description: Can store x-bit values. x can range from 1 to 64
o Usage: BIT(2)
❖ FLOAT
o Description: Decimal number with precision up to 23 digits
o Usage: FLOAT
❖ DOUBLE
o Description: Decimal number with precision from 24 to 53 digits
o Usage: DOUBLE
❖ BOOLEAN
o Description: Boolean values 0 or 1
o Usage: BOOLEAN
❖ DATE
o Description: Date in the format YYYY-MM-DD, ranging from 1000-01-01 to
9999-12-31
o Usage: DATE
❖ YEAR
o Description: Year in 4 digits, ranging from 1901 to 2155
o Usage: YEAR

Operators in SQL

SQL operators are important in database management systems (DBMS) as they allow us to
manipulate and retrieve data efficiently. SQL operators are symbols or keywords used to
perform operations on data in SQL queries. These operations can include mathematical
calculations, data comparisons, logical manipulations, other data-processing tasks.
Operators help in filtering, calculating, and updating data in databases, making them crucial
for query optimization and accurate data management.

Types of SQL Operators


SQL operators can be categorized based on the type of operation they perform. Here are the
primary types of SQL operators:
• Arithmetic Operator
• Comparison Operator
• Logical Operator
• Bitwise Operators
• Compound Operators
• Special Operators
Arithmetic Operators
Arithmetic operators in SQL are used to perform mathematical operations on numeric data
types in SQL queries.
Operator Description
+ The addition is used to perform an addition operation on the data values.
– This operator is used for the subtraction of the data values.
/ This operator works with the ‘ALL’ keyword and it calculates division
operations.
* This operator is used for multiplying data values.
% Modulus is used to get the remainder when data is divided by another.

Comparison Operators
Comparison Operators in SQL are used to compare one expression’s value to other
expressions.
Operator Description
= Equal to.
> Greater than.
< Less than.
>= Greater than equal to.
<= Less than equal to.
<> Not equal to.

Logical Operators
Logical Operators in SQL are used to combine or manipulate conditions in SQL queries to
retrieve or manipulate data based on specified criteria..
Operator Description
AND Logical AND compares two Booleans as expressions and returns true when both
expressions are true.
OR Logical OR compares two Booleans as expressions and returns true when one
of the expressions is true.
NOT Not takes a single Boolean as an argument and change its value from false to
true or from true to false.

Bitwise Operators
Bitwise operators in SQL are used to perform bitwise operations on binary values in SQL
queries, manipulating individual bits to perform logical operations at the bit level.
Operator Description
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise XOR (exclusive OR) operator
~ Bitwise NOT (complement) operator

Compound Operators
Compound operators combine an operation with assignment. These operators modify the value
of a column and store the result in the same column in a single step.
Operator Description
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign

SQL Commands

SQL Commands are like instructions to a table. It is used to interact with the database with
some operations. It is also used to perform
specific tasks, functions, and queries of data.
SQL can perform various tasks like creating a
table, adding data to tables, dropping the table,
modifying the table, set permission for users.
SQL Commands are mainly categorized into
five categories:
❖ DDL – Data Definition Language
❖ DML – Data Manipulation Language
❖ DCL – Data Control Language
❖ TCL – Transaction Control Language
1. Data Definition Language (DDL)

DDL or Data Definition Language actually consists of the SQL commands that can be used
to defining, altering, and deleting database structures such as tables, indexes, and schemas.
It simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database.
Common DDL Commands
❖ Create: It is used to create a new table in the database or a Database.
❖ Drop: It is used to delete both the structure and record stored in the table.
❖ Alter: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
❖ Truncate: It is used to delete all the rows from the table and free the space containing
the table.

2. Data Manipulation Language

DML commands are used to modify the database. It is responsible for all form of changes in
the database. The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollback.
Common DML Commands
❖ Insert: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
❖ Update: This command is used to update or modify the value of a column in the table.
❖ Delete: It is used to remove one or more row from a table.
❖ Select: It is used to select the attribute based on the condition.
3. Data Control Language

DCL commands are used to grant and take back authority from any database user.
Common DCL Commands
❖ Grant: To give permission
❖ Revoke: It is used to take back permissions from the user.
4. Transaction Control Language

Transactions are atomic i.e. either every statement succeeds or none of statement succeeds.
There are number of Transaction Control statements available that allow us to control this
behaviour. These statements ensure data consistency. TCL commands can only use with DML
commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
Common TCL Commands
❖ Commit: Commit command is used to save all the transactions to the database. It makes
your changes permanent and ends the transaction.
❖ Rollback: Rollback command is used to undo transactions that have not already been
saved to the database. Rollback also serves to end the current transaction and begin a
new one.

Database Related Queries

CREATE DATABASE
Syntax:
CREATE DATABASE database_name;
SHOW DATABASES
Syntax:
SHOW DATABASES;
Delete a Database
Syntax:
DROP DATABASE db_name;
DROP DATABASE IF EXISTS: use the IF EXISTS clause, which will delete the database
only if it exists in the system.
Syntax:
DROP DATABASE IF EXISTS Database_Name;
Select the Database: To set database as the active database, use the USE command
Syntax:
USE db_name;

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
Note: A table has a specified number of columns, but can have any number of rows.
EMP_NAME ADDRESS SALARY
Ankita Lucknow 15000
Ramanand Allahabad 18000
Jack New York 20000

CREATE TABLE
The CREATE TABLE command is a crucial tool for database administration because of these
limitations, which aid in ensuring data integrity. To create a table in SQL, use this CREATE
TABLE syntax:
CREATE TABLE table_name(
Column1 datatype(size),
Column2 datatype(size),
.
.
Column n datatype(size)
);
• table_name: The name you assign to the new table.
• column1, column2, … : The names of the columns in the table.
• datatype(size): Defines the data type and size of each column.

INSERT DATA INTO THE CREATED TABLE


After creating the table, we can use INSERT INTO command to add data to it.
Syntax:
INSERT INTO table_name (column1, column2, …) VALUES (value1, value2, …);

SELECT DATA FROM TABLE


To retrieve or select data from table, we can use SELECT command or query.
Syntax:
#For All columns:
SELECT * FROM Table_name;
#For Specific column:
SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N FROM Table_Name;

Important Points About SQL CREATE TABLE Statement


• CREATE TABLE statement is used to create new table in a database.
• It defines the structure of table including name and datatype of columns.
• The DESC table_name; command can be used to display the structure of the created
table
• If you try to create a table that already exists, MySQL will throw an error. To avoid this,
you can use the CREATE TABLE IF NOT EXISTS syntax.
DROP TABLE

A SQL DROP TABLE statement is used to delete a table definition and all data from a table.
• This operation cannot be undone, and once the table is dropped all data in that table is
lost.
• Once executed, this operation removes the table definition and all of its rows, so the
table can no longer be accessed or used.
• This action is irreversible which means that once a table is dropped, it cannot be
recovered.
Syntax:
DROP TABLE "table_name";
SQL DELETE Statement
The SQL DELETE statement removes one or more rows from a database table based on a
condition specified in the WHERE clause. It’s a DML (Data Manipulation Language)
operation that modifies the data within the table without altering its structure.
Syntax:
DELETE FROM table_name
WHERE some_condition;
• Some_condition: condition to choose a particular record.
• table_name: name of the table
ALTER Command in SQL

If we need to rename a table, add a new column, or change the name of an existing column
in SQL, the ALTER command is crucial for making schema changes without affecting the
data that is already there. This is essential for tasks like:
• Renaming a table.
• Changing a column name.
• Adding or deleting columns.
• Modifying the data type of a column.
Syntax:
1.Renaming a Table
ALTER TABLE table_name RENAME TO new_table _name;
2. Renaming a column
ALTER TABLE table_name RENAME COLUMN old_column_name to
new_column_name;
3. Adding a column
ALTER TABLE table_name ADD COLUMN new_column _name data_type;
4. Modifying the data type a column
ALTER TABLE table_name MODIFY COLUMN column_name
new_data_type;

DROP and TRUNCATE

DROP Table
To delete an entire table, including its data and structure:
Syntax:
DROP TABLE table_name;
TRUNCATE Command
The TRUNCATE command is a Data Definition Language (DDL) action that removes all
rows from a table but preserves the structure of the table for future use.
Syntax:
TRUNCATE TABLE table_name;
Key Differences Between DROP and TRUNCATE
The key differences between DROP and TRUNCATE statements are explained in the
following table:
Feature DROP TRUNCATE
Effect on Table Completely removes both the data Removes all rows but preserves
Structure and the table structure the table structure
Data Deletion Deletes both data and table Deletes only the data, not the table
definition structure
Recovery Non-recoverable; once dropped, Can be rolled back if used in a
the table cannot be restored (unless transaction (if supported by the
you have backups) DBMS)
Triggers Does not activate triggers Does not activate DELETE
associated with the table triggers
Performance Slower due to data and structural Faster, especially for large datasets
removal
Usage Used when you want to completely Used to quickly remove all rows
remove a table or database from a table but keep the structure
for future use

SQL SELECT queries

SELECT DISTINCT
The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or
unique data.
Syntax:
SELECT DISTINCT column name ,column_name
FROM table_name;
SELECT COUNT
The SQL COUNT() is a function that returns the number of records of the table in the output.
Syntax:
SELECT COUNT(column_name)
FROM table_name;
Syntax of Count (*) Function in SQL
SELECT COUNT(*) FROM table_name;
Example:
Bike_Name Bike_Color Bike_Cost
Livo Black 185,000
Apache Red NULL
Pulsar Red 90,0000
Royal Enfield Black NULL
KTM DUKE Black 80,000
KTM RC White 195,000

SELECT COUNT (*) FROM Bikes ;


Output:

The count(*) function in SQL shows all the Null and Non-Null records present in the table.
Count() Function with WHERE clause in SQL
SELECT COUNT(column_name) FROM table_name WHERE [condition];

Bike_Name Bike_Color Bike_Cost


Apache Black 90,0000
Livo Black NULL
KTM RC Red 185,000
KTM DUKE White NULL
Royal Enfield Red 80,000
Pulsar Black 195,000

SELECT COUNT (Bike_Name) AS TotalBikeBlackColor FROM Bikes WHERE Bike_Colo


r = 'Black';
Output:
3
SQL LIMIT Clause
SELECT Column1,Column2 FROM table_name WHERE condition LIMIT ;
SELECT RANDOM
SELECT column1,column2, FROM table_name ORDER BY RAND() LIMIT;

ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT SUM
It is also known as SQL SUM() function. It is used in a SQL query to return
summed value of an expression.
Syntax:
SELECT SUM (expression)
FROM tables
WHERE conditions;

SQL UPDATE Statement


UPDATE statement is used to modify existing records in a table. Whether you need to update
a single record or multiple rows at once, SQL provides the necessary functionality to make
these changes. The UPDATE statement is essential for maintaining the integrity of your data
by allowing you to correct or modify existing entries in your database.

Syntax:
The syntax for SQL UPDATE Statement is :
UPDATE table_name SET column1 = value1, column2 = value2,…
WHERE condition;
• table_name: name of the table
• column1: name of first, second, third column….
• value1: new value for first, second, third column….
• condition: condition to select the rows for which the

SQL Clauses

WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
The WHERE clause is not only used in SELECT statements, it is also used
in UPDATE, DELETE, etc.!

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
GROUP BY Clause
The GROUP BY statement in SQL is used to arrange identical data into groups based on
specified columns.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() , AVG().
2. table_name: Name of the table.
3. condition: Condition used.

HAVING Clause
The HAVING clause in SQL is used to filter query results based on aggregate functions. It is
commonly used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
It allows filtering grouped data using Boolean conditions (AND, OR).
Key Features of the HAVING Clause
• Used to filter grouped data based on aggregate functions.
• Works with Boolean conditions (AND, OR
• Cannot be used without GROUP BY unless an aggregate function is present.
• Must be placed after the GROUP BY clause and before the ORDER BY clause (if
used).
Syntax:

SELECT column_name AGGREGATE_FUNCTION(column_name)


FROM table_name
GROUP BY column_name
HAVING condition;

Aggregate functions

SQL Aggregate Functions are essential for summarizing and analyzing large datasets. These
functions operate on multiple rows of a table, combining them into a single, more meaningful
result. SQL Aggregate functions are mostly used with the GROUP BY clause of the SELECT
statement.
Common SQL Aggregate Functions
Sum():
The SUM() function provides the total sum of a numeric column. This function is ideal for
calculating totals such as sales, revenue, or any other cumulative numeric value.
Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Avg():
The AVG() function provides the average value of a numeric column, helping you determine
central tendencies in your data. This is useful for understanding the mean value of a set of
numbers, such as salaries, prices, or scores.
Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Min():
MIN() function returns the smallest value in the column. It can be used with various data types,
including numbers, strings, and dates.
Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Max():
MAX() function returns the largest value in the column. It can can be used with various data
types, including numbers, strings, and dates.
The MAX() function in SQL can be used in combination with other SQL clauses and
functions, such as GROUP BY, HAVING.
Syntax:
SELECT MAX(column_name)
FROM table_name
WHERE condition;

SQL Data Constraints


In SQL, constraints are used to enforce rules on data, ensuring the accuracy, consistency, and
integrity of the data stored in a database.
NOT NULL Constraint
The NOT NULL constraint is used to enforce that a column in a table must always contain a
value; it cannot contain a NULL value. By default, columns in SQL can hold NULL values,
meaning they can have no data.
Syntax:
CREATE TABLE table_Name
(
column1 data_type(size) NOT NULL,
column2 data_type(size) NOT NULL,
….
);
UNIQUE Constraint
The SQL UNIQUE constraint ensures that all values in a column or a set of columns are
different from one another. It can be applied to one or more columns in a table. When applied,
the database will reject any insert or update operation that would create a duplicate value in
the specified column(s).
Syntax:
CREATE TABLE table_name(
Column1 datatype UNIQUE,
Column2 datatype,

);
PRIMARY KEY Constraint
The PRIMARY KEY constraint in SQL is one of the most important constraints used to
ensure data integrity in a database table. PRIMARY KEY in SQL is a column (or group of
columns) that uniquely identifies the records in that table. A primary key must contain unique
values and can not have any NULL value.
SQL PRIMARY KEY Properties
1. No duplicate values are allowed, i.e. The column assigned as the primary key should
have UNIQUE values only.
2. NO NULL values are present in the Primary key column. Hence there is a Mandatory
value in the column having the Primary key.
3. Only one primary key per table exists although the Primary key may have multiple
columns.
4. No new row can be inserted with the already existing primary key.
5. Primary keys can be classified into two categories Simple primary key that consists of
one column and composite primary key that consists of Multiple columns.
6. Defined in CREATE TABLE or ALTER TABLE statement.
Syntax:
• Using CREATE TABLE Statement
CREATE TABLE table_name(
Column1 datatype constraints,
Column2 datatype constraints,

PRIMARY KEY(column1,column2)
);
• Using ALTER TABLE Statement
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY(column1,column2);

FOREIGN KEY Constraint


A FOREIGN KEY constraint is a fundamental concept in relational databases, ensuring data
integrity by enforcing relationships between tables. By linking a child table to a parent table,
the foreign key establishes referential integrity.
A FOREIGN KEY is a column or set of columns in one table that references the primary
key columns of another table. This creates a relationship between the two tables, ensuring
that the child table (which contains the foreign key) can only have values that exist in the
parent table’s primary key column(s).

New Table
Syntax:
CREATE TABLE child_table_name (
column_name1 DATA_TYPE,
column_name1 DATA_TYPE,
column_name1 DATA_TYPE,
FOREIGN KEY (column_name) REFERENCES parent_table(parent_column)
);
Add Foreign key to Existing Table
ALTER TABLE child_table
ADD CONSTRAINT constraint_name
FOREIGN KEY (column_name) REFERENCES parent_table(parent_column);

ADD CONSTRAINT constraint_name : Adds a named foreign key constraint


(constraint_name).
Composite Key in SQL
A composite key is a primary key that is made up of more than one column to uniquely
identify records in a table. Unlike a single-column primary key, a composite key combines
two or more columns to ensure uniqueness.
Key Points to Remember:
• A composite key is formed from multiple columns.
• It ensures uniqueness when the combined values of the columns are considered together.
• None of the columns involved in a composite key can be NULL.
• The composite key helps in tables where single columns cannot guarantee uniqueness,
but a combination of columns can.
DEFAULT Constraint
The DEFAULT constraint in SQL is used to provide a default value for a column when no
value is specified during an INSERT operation. If a column has a DEFAULT constraint and
no value is explicitly provided during the insertion of a record, the database will automatically
insert the default value defined for that column.
Syntax :
CREATE TABLE table_name (
column1 datatype DEFAULT default_value,
column2 datatype DEFAULT default_value,
...
);

SQL Joins

The SQL JOIN clause takes records from two or more tables in a database and combines it
together. SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them. It can access data from multiple tables
simultaneously using common key values shared across different tables. We can use SQL
JOIN with multiple tables. It can also be paired with other clauses, the most popular use will
be using JOIN with WHERE clause to filter data retrieval.
SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, is critical for
working with relational databases.
SQL JOIN Syntax
SELECT columns_from_both_tables
FROM table1
JOIN table2
ON table1.column1 = table2.column2

Inner Join
The INNER JOIN clause in SQL is used to combine records from two or more tables. The
result contains only the rows that have matching values in both tables based on a specific
condition. This makes INNER JOIN a valuable tool when we need to work with related data
across multiple tables in a database.

Syntax:
SELECT columns_from_both_tables
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column2

Key Terms
• columns: The specific columns we want to retrieve.
• table1 and table2: The two tables we are joining.
• column_name: The columns from both tables that we want to match based on the join
condition.

Example of SQL INNER JOIN

Department

Employees

Output:

LEFT JOIN (LEFT OUTER JOIN)

The LEFT OUTER JOIN (referred to as LEFT JOIN) returns all


rows from the left table, and the matching rows from the right
table. If there is no match, the result will include NULL
values for columns from the right table.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Output:

SQL RIGHT JOIN

The RIGHT JOIN in SQL returns a table that contains all the records from the right table and
only matching records from the left table. In simpler terms, if a row is present in the right table
but not in the left table, the result will include this row
with NULL values for columns from the left table.
Conversely, if a record from the left table is not in the
right table, it will not be included in the result.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Example:
EMPLOYEE TABLE

DEPARTMENT TABLE
Query:
SELECT emp_no,emp_name,dept_name,location
FROM employee
RIGHT JOIN department
ON employee.dept_no=department.dept_no;
OUTPUT:

SQL Full Join

• The FULL JOIN or FULL OUTER JOIN in SQL is used to retrieve all rows from
both tables involved in the join, regardless of whether there is a match between the rows
in the two tables.
• It combines the results of both a LEFT JOIN and a RIGHT JOIN.
• When there is no match, the result will include NULLs for the columns of the table that
do not have a matching row.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
• SELECT columns: Specifies the columns to retrieve.
• FROM table1: The first table to be joined.
• FULL JOIN table2: Specifies the second table to join with the first table using a FULL
JOIN.
• ON table1.column = table2.column: Defines the condition to match rows between the
two tables.
Note: MySQL does NOT support FULL OUTER JOIN directly. However, we can achieve the
same result by using a combination of LEFT JOIN and UNION with a RIGHT JOIN.

Example:

Students

Courses

Query:
Output:

SQL Date Data Types


In SQL, dates are complicated for newbies, since while working with a database, the format
of the data in the table must be matched with the input data to insert.

DATE format YYYY-MM-DD


DATETIME format: YYYY-MM-DD HH:MI: SS
TIMESTAMP format: YYYY-MM-DD HH:MI: SS
YEAR format YYYY or YY

SQL Date Functions

1. NOW()
The NOW() function retrieves the current date and time in YYYY-MM-DD
HH:MI:SS format.
2. CURDATE()
CURDATE() returns the current date in YYYY-MM-DD format, without the time part.
3. CURTIME()
The CURTIME() function returns the current time in HH:MI:SS format, excluding the date.
4. DATE()
Extracts the date part of a date or date/time expression.
5. EXTRACT()
The EXTRACT() function retrieves a specific part of a DATE, DATETIME,
or TIMESTAMP value, such as the day, year, or second.
Syntax:
EXTRACT(unit FROM date);

String functions

SQL String Functions are powerful tools that allow us to manipulate, format, and extract
specific parts of text data in our database. These functions are essential for tasks like cleaning
up data, comparing strings, and combining text fields.

Common SQL String Functions

1. CONCAT(): Concatenate Strings


The CONCAT() function is used to concatenate (combine) two or more strings into one string.
It is useful when we want to merge fields like first and last names into a full name.
2. CHAR_LENGTH()
The CHAR_LENGTH() or LENGTH() function returns the length of a string in characters.
It’s essential for validating or manipulating text data, especially when you need to know how
many characters a string contains.
3. UPPER() and LOWER(): Convert Text Case
These functions convert the text to uppercase or lowercase, respectively. They are useful for
normalizing the case of text in a database.
4. REVERSE(): Reverse the String
The REVERSE() function reverses the characters in a string. It’s useful in situations where we
need to process data backward, such as for password validation or certain pattern matching.
Numeric Functions

SQL Numeric Functions are used to perform operations on numeric data types such as INT,
FLOAT, DECIMAL, DOUBLE, and others. These functions help you manipulate numbers in
various ways, including performing arithmetic operations, rounding, formatting, and
aggregating data.
Commonly Used SQL Numeric Functions

1. ABS() – Absolute Value


The ABS() function returns the absolute value of a number, which is the number without its
sign (i.e., it converts negative numbers to positive).
Syntax:
SELECT ABS(number);
2. CEIL()
The CEIL() (or CEILING()) function rounds a number up to the nearest integer, regardless
of whether the decimal part is greater than or less than 0.5.
Syntax:
SELECT CEIL(number);
3. FLOOR() – Round Number Down
The FLOOR() function rounds a number down to the nearest integer, ignoring the decimal
part.
Syntax:
SELECT FLOOR(number);
4. ROUND() – Round a Number to a Specified Decimal Place
The ROUND() function rounds a number to a specified number of decimal places. It is very
useful for financial calculations or whenever precise rounding is necessary.
Syntax:
SELECT ROUND(number, decimal_places);
5. TRUNCATE() – Remove Decimal Places
The TRUNCATE() function is used to remove the decimal portion of a number without
rounding. It truncates the number to the specified number of decimal places.
Syntax:
SELECT TRUNCATE(number, decimal_places);
6. MOD() – Modulo or Remainder
The MOD() function returns the remainder of a division operation (i.e., it computes the
modulus). This function is useful for tasks like determining even/odd numbers or finding
remainders in mathematical operations.
Syntax:
SELECT MOD(dividend, divisor);
7. POWER() – Raise a Number to the Power of Another
The POWER() function is used to raise a number to the power of another number. It is often
used in mathematical calculations like compound interest or growth rate.
Syntax:
SELECT POWER(base, exponent);
8. SQRT() – Square Root
The SQRT() function returns the square root of a number. This is useful for mathematical
calculations involving geometry or statistical analysis.
Syntax:
SELECT SQRT(number);

SQL Views

Views in SQL are a type of virtual table that simplifies how users interact with data across
one or more tables. Unlike traditional tables, a view in SQL does not store data on disk;
instead, it dynamically retrieves data based on a pre-defined query each time it’s accessed.
A view in SQL is a saved SQL query that acts as a virtual table. It can fetch data from one or
more tables and present it in a customized format, allowing developers to:
• Simplify Complex Queries: Encapsulate complex joins and conditions into a single
object.
• Enhance Security: Restrict access to specific columns or rows.
• Present Data Flexibly: Provide tailored data views for different users.
CREATE VIEWS IN SQL
We can create a view using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2…..
FROM table_name
WHERE condition;
Parameters:
• view_name: Name for the View
• table_name: Name of the table
• condition: Condition to select rows

Examples
Table 1: StudentDetails

Table 2: StudentMarks

1: Creating View from a Single Table


CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
2: Create View from Table
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

3: Creating View from Multiple Tables


CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
Listing all Views in a Database
We can list View using the SHOW FULL TABLES statement. A View can be created from a
single table or multiple tables.
Syntax:
SHOW FULL TABLES WHERE table_type LIKE "%VIEW";
Delete View in SQL

SQL allows us to delete an existing View. We can delete or drop View using the DROP
statement.
Syntax:
DROP VIEW view_name;
Update View in SQL

To update the existing data within the view, use the UPDATE statement.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Rules to Update Views in SQL:
Certain conditions need to be satisfied to update a view. If any of these conditions are not met,
the view cannot be updated.
1. The SELECT statement which is used to create the view should not include GROUP
BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple
tables, then we will not be allowed to update the view.
Example
we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table.
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

SQL Indexes

SQL Indexes are important components in relational databases that significantly


enhance data retrieval speeds by reducing the need for full table scans. By providing quick
access paths, indexes allow queries to perform faster, especially on large datasets.
An index in SQL is a schema object that improves the speed of data retrieval operations on
a table. It works by creating a separate data structure that provides pointers to the rows in a
table, making it faster to look up rows based on specific column values. Indexes act as a table
of contents for a database, allowing the server to locate data quickly and efficiently, reducing
disk I/O operations.
Creating an Index
SQL indexes can be applied to one or more columns and can be either unique or non-
unique. Unique indexes ensure that no duplicate values are entered in the indexed columns,
while non-unique indexes simply speed up queries without enforcing uniqueness.
Syntax:
CREATE INDEX index_name
ON table_name (column_name);
Key Terms
• index_name: The name of the index.
• table_name: The name of the table on which the index is created.
• column_name: The column(s) on which the index is applied.
Creating a Unique Index:
A unique index ensures that all values in the indexed columns are unique preventing duplicate
values.
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column_name);
When Should Indexes Be Created?

Indexes should be created under the following conditions:


• Frequent Search Columns: When a column is frequently used in WHERE clauses or
as part of joins.
• Wide Range of Values: When a column has a large variety of distinct values (e.g.,
product IDs, customer IDs).
• Low Null Values: Indexes work best on columns that contain a low number of NULL
values.
Example

Create an Index
CREATE INDEX idx ON STUDENT(student_id);
Retrieve Data Using the Index
SELECT * FROM STUDENTS USE INDEX(idx);
DROP INDEX

The DROP INDEX statement in SQL is used to delete an index from a table.
ALTER TABLE table_name DROP INDEX index_name;
Key Terms
• table_name: The name of the table.
• index_name: The name of the index to be dropped

Subqueries in SQL

In SQL, subqueries are one of the most powerful and flexible tools for writing efficient
queries. A subquery is essentially a query nested within another query, allowing users
to perform operations that depend on the results of another query. This makes
it invaluable for tasks such as filtering, calculating aggregates, or even modifying data
dynamically.
In SQL, a subquery can be defined as a query embedded within another query. It is often
used in the WHERE, HAVING, or FROM clauses of a statement. Subqueries are commonly
used with SELECT, UPDATE, INSERT, and DELETE statements to achieve complex
filtering and data manipulation.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);
Examples of SQL Subqueries

Q1:Students who scored below the class average.


SELECT name, marks
FROM students
WHERE marks < (SELECT AVG(marks) FROM students);

SQL Wildcard Characters


SQL wildcard Characters are special characters used in SQL queries to search
for patterns within string data. These wildcards can help us perform partial searches,
matching parts of a string or allowing complex filtering based on patterns. They are most
commonly used with the LIKE and NOT LIKE clauses in SQL. Using wildcard
characters in SQL allows us to search for patterns rather than exact matches, which is
especially useful in cases where we only know part of the string we are looking for.
Syntax:
SELECT column1,column2 FROM table_name
WHERE column LIKE wildcard_operator;
Types of SQL Wildcard Characters
There are several wildcard characters in SQL, each serving a different purpose in pattern
matching. Let’s break down the most common wildcard characters and their usage:
Wildcard Description
Character
% Represents zero or more characters.
_ Represents exactly one character.
[] Represents a range of characters, used to match any single character
within the range.
[ ] with ^ or ! Matches any character that is NOT in the specified range.

Example of SQL Wildcard Characters

1. Using the % Wildcard


The % wildcard is used to substitute for zero or more characters. It’s very flexible and is
commonly used for matching partial strings.
Records Starting with a Specific Letter
To fetch records where the CustomerName starts with the letter ‘A’.
Query:
SELECT * FROM customers
WHERE customerName LIKE “A%”;
Output

Records Ending with a Specific Letter


To fetch records from the Customer table with NAME ending with the letter ‘A’.
Query:
SELECT *
FROM customers
WHERE customerName LIKE “%A”;
Output:

Records Containing a Specific Letter at Any Position


To fetch records from the Customer table with NAME with the letter ‘A’ at any position. This
query will return records where A appears anywhere within the name, whether at
the beginning, middle, or end.
Query
SELECT * FROM Customers WHERE CustomerName LIKE '%A%';
Output:

Fetching Records with ‘ri’ in Country Field and Removing Duplicates


To fetch records from the Customer table where the Country contains the substring ‘ri’ at
any position, and ensure the result set does not contain duplicate data:
Query:
SELECT * FROM Customers WHERE Country LIKE '%ri%';

2. Using the _ Wildcard


The _ wildcard is used to substitute for exactly one character. This is useful when we know
part of the string but need to match one specific unknown character.
Records with a Specific Prefix and Any Three Letters
To fetch records where the CustomerName starts with ‘Nav’ and is followed by any three
characters.
Query:
SELECT * FROM Customer WHERE CustomerName LIKE 'Nav___';
Output:

Records with a Specific Length


To fetch records from the Customer table with Country containing a total of 7 characters. The
query will return all records where the Country field has exactly seven characters.
Query:
SELECT * FROM Customer WHERE Country LIKE '_______';
Output:

You might also like