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

SQL_unit2dbms

SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, widely used across various database management systems. It allows users to perform tasks such as querying, modifying data, and maintaining database transactions with a user-friendly syntax. SQL supports various operations, data types, and ensures data integrity through ACID properties, making it a powerful tool for database management.

Uploaded by

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

SQL_unit2dbms

SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, widely used across various database management systems. It allows users to perform tasks such as querying, modifying data, and maintaining database transactions with a user-friendly syntax. SQL supports various operations, data types, and ensures data integrity through ACID properties, making it a powerful tool for database management.

Uploaded by

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

SQL(structured query language)

• SQL is the standard database language used by almost every


Relational Database Management System (RDMS) such as MySQL, MS
Access, Oracle, Postgres, and SQL Server. SQL is a popularly used
acronym for Structured Query Language. It is a computer language
used to store, manipulate, and retrieve data from a relational
database. SQL may do a variety of other tasks, including database
optimization and maintenance. SQL is applicable to both relational
and multidimensional databases. SQL does not require a lot of
programming experience, although it does help to understand how a
given SQL command behaves in terms of executing and retrieving SQL
queries.
Why is SQL Used?
• SQL is useful for querying and maintaining data in a relational database management
system. This is one of the most common uses of SQL.

• It is used to change or modify previous data

• It provides a large number of commands that allow us to perform a variety of database


activities.

• SQL is also used to maintain transactions in a database.

• Almost every website today is supported by a backend database. SQL is most commonly
used to connect with that database.

• Setting table, procedure, and view permissions

• To create functions, views, and to store procedures


Characteristics of SQL

1. Easy to learn
• SQL is an extremely practical and user-friendly language. Even if you have no prior
experience with technology, you can learn the basics of the language. SQL has a
syntax that is remarkably close to English, resulting in a smooth learning curve.
2. Stored Procedures
• A stored procedure is a piece of SQL code that you can save and reuse any
number of times. Stored Procedures are used to carry out one or more DML
operations on a database. It’s just a collection of SQL statements that take some
input in the form of arguments, perform some work, and may or may not return a
result.
3. Joins
SQL supports join which is a command that joins two sets of data together (i.e. two
or more tables). INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN are the joins
supported by SQL.
Characteristics of SQL

5. Declarative Language
• SQL is a declarative language, which means you specify what data you want, not
how to get it.
• You write queries that describe the desired result, and the DBMS figures out the
best way to execute them.
6. High-Level Language
• SQL is a high-level language, easy to understand and use without deep
knowledge of how the data is stored or processed internally.
• It abstracts the complex operations behind simple commands.
7. Non-Procedural
• Unlike procedural programming languages, SQL doesn’t require you to write step-
by-step instructions.
• You just state the conditions and the DBMS handles the procedural details.
Characteristics of SQL

8. Standardized Language
• SQL is a standardized language by organizations like ANSI and ISO, ensuring
consistent use across different DBMS platforms (e.g., MySQL, Oracle, SQL Server).
• Though different systems may have extensions, the core SQL commands are
standardized.
9. Set-Based Operations
• SQL works on sets of data rather than individual records one by one.
• This allows for efficient processing and optimization.
10. Portable
SQL queries written for one DBMS can often be used with little or no modification
in another DBMS.
This makes database applications more portable.
Characteristics of SQL

11. High performance


• In large database systems, SQL provides performance programming capabilities for
highly transactional heavy workloads.
12. Scalability and Flexibility
• SQL is a scalable and flexible database. It’s simple to build new tables, and tables that
have already been created or those which are no longer in use can be dropped or
deleted from a database. SQL is capable of handling big data sets and several
transactions.
13. Transactions
• TCL, which supports a variety of transactions, is supported by SQL. Transactions are
logically ordered units or sequences of work that can be completed manually by a
human or automatically by a database application. SQL commands such as COMMIT,
ROLLBACK, SAVEPOINT, and others support transactions.
14. Security
• SQL allows setting permissions in views, tables, and procedures. This ensures the safety
of data in sensitive databases. Also, constraints can be specified in SQL. These are rules
that limit the types of data that can be entered into a table column.
Characteristics of SQL

15. Powerful and Flexible


•SQL supports various operations like:
•Data retrieval (SELECT)
•Data manipulation (INSERT, UPDATE, DELETE)
•Data definition (CREATE, ALTER, DROP)
•Data control (GRANT, REVOKE)
•It can handle complex queries, joins, subqueries, transactions, and more.

16. Integrated with DBMS


• SQL is tightly integrated with DBMS, allowing it to interact directly with the database
for defining schema, querying data, and controlling access.
What are ACID
properties?
• To maintain consistency in database before and after transaction, certain
properties are followed, these properties are called ACID properties. These
properties are:

• Atomicity: Any operation performed should be executed completely, or not


completed at all.

• Consistency: The integrity of data should be maintained.

• Isolation: Operation on one data should not affect operation on the other.

• Durability: After the execution of an operation, the data should become


permanent.
Advantages of SQL

• Faster Query Processing: Large amount of data is retrieved quickly and efficiently.
Operations like Insertion, deletion, manipulation of data is also done in almost no
time.
• No Coding Skills: For data retrieval, large number of lines of code is not required.
All basic keywords such as SELECT, INSERT INTO, UPDATE are used and also the
syntactical rules are not complex in SQL, which makes it a user-friendly language.
• Standardized Language: Due to documentation and long establishment over years,
it provides a uniform platform worldwide to all its users.
• Portable: It can be used in programs in PCs, server, laptops independent of any
platform. Also, it can be embedded with other applications as per
need/requirement/use.
• Security: SQL databases have built-in security features that help protect data from
unauthorized access, such as user authentication, encryption, and access control.
Advantages of SQL

• Interactive Language: Easy to learn and understand, answers to complex queries


can be received in seconds.
• Multiple data views: One of the advantages of SQL is its ability to provide multiple
data views . This means that SQL allows users to create different views or
perspectives of the data stored in a database, depending on their needs and
permissions.
• Scalability: SQL databases can handle large volumes of data and can be scaled up or
down as per the requirements of the application.
• Data Integrity: SQL databases enforce data integrity by enforcing constraints such
as unique keys, primary keys, and foreign keys, which help prevent data duplication
and maintain data accuracy.
• Backup and Recovery: SQL databases have built-in backup and recovery tools that
help recover data in case of system failures, crashes, or other disasters.
• Data Consistency: SQL databases ensure consistency of data across multiple tables
through the use of transactions, which ensure that changes made to one table are
reflected in all related tables.
SQL Data Types
•SQL uses data types to define the kind of data a column can store.

•Categories include: Numeric, Text, Date/Time, Boolean, and Others.

•Each column in a database table is required to have a name and a data type.

•An SQL developer must decide what type of data that will be stored inside each column
when creating a table. The data type is a guideline for SQL to understand what type of
data is expected inside of each column, and it also identifies how SQL will interact with
the stored data.

•In MySQL there are three main data types: string, numeric, and date and time.
String Data Types

Data Type Description

CHAR(n), CHARACTER(n) Fixed-length string (e.g., CHAR(10))

VARCHAR(n), CHARACTER VARYING(n) Variable-length string up to n characters

Variable-length text (limit depends on


TEXT DBMS)
Numeric Data
Types
Data Type Description
INT, INTEGER Whole numbers (e.g., 1, 100, -20)
SMALLINT Smaller range of integers
BIGINT Larger range of integers
Exact fixed-point (e.g., 12.34); p =
DECIMAL(p, s) precision, s = scale
NUMERIC(p, s) Same as DECIMAL
FLOAT Approximate floating-point number
REAL Lower precision float
DOUBLE, DOUBLE PRECISION High precision floating-point
Date and Time Data Types

Data Type Description

DATE Date only (e.g., '2025-08-01')

TIME Time only (e.g., '13:45:30')

DATETIME Date and time (MySQL)

TIMESTAMP Date/time with optional timezone

YEAR Year only (MySQL-specific)


Boolean Data Type

Data Type Description

Stores TRUE, FALSE, or NULL (varies by


BOOLEAN DBMS)
UUID Universally Unique Identifier

JSON Stores JSON-formatted data

ARRAY Array of values (PostgreSQL)


Predefined string values (MySQL,
PostgreSQL)
ENUM
SQL LITERALS
• In SQL, literals are fixed values (constants) that are directly written into SQL
statements. They represent specific data values and are not tied to variables or
columns. Literals are used to define values explicitly in queries like SELECT,
INSERT, UPDATE, or DELETE.
• SQL supports four kinds of literal values, which are constants used in SQL
statements. These literal values are used to represent fixed data and can be
written directly in the SQL code. The four types of SQL literals are:
• Character String Literals
• Bit String Literals
• Exact Numeric Literals
• Boolean Literals
• Null Literals
1. Character String Literals

• Any string enclosed in single quotes is considered a character string


literal. In a situation where a single quote is needed, simply quoting it
makes it valid.
• Enclosed in single quotes (')
• Represent text data
Examples:
‘ Hello'
'16378'
'It''s a Good day'
2. Bit String Literals

• These can be defined as the 0s and 1s in binary language. There are


two ways of writing them: It can be B’ and ‘s or in hexadecimal format
using X and single quotes like so: X’1F’.
Examples:
• - Binary format
B'10001011'
B'1'
B'0'

-- Hexadecimal format
X'C5'
X'0'
3. Exact Numeric Literals

• Any wholes or decimal numbers such as 10 and 0.99 have the ability to be written
entirely, which is great while stating an item’s approximate value.
• Represent integers or decimals
• No quotes needed
• Examples:
• SELECT 100 AS amount;
• SELECT 3.14 AS pi;
Boolean Literals
• The MySQL Boolean literals are logical values that evaluate to either 1 or 0. Let us
see some example for a better understanding.
• There are various ways a boolean value is evaluated to true in MySQL. Here, we
use the integer 1 as a boolean literal −Example
SELECT 1 AS 'boolean literal';
• We can also use the keyword TRUE to evaluate the boolean literal to 1.
SELECT TRUE AS 'boolean literal'; SELECT TRUE AS 'boolean literal';
SELECT TRUE AS 'boolean literal';
• We can also use the lowercase of the keyword TRUE, as true, to evaluate the
boolean literal to 1.
SELECT true AS 'boolean literal';
Output- 1
Similarly, there are multiple ways a boolean value is evaluated to false in MySQL.
Here, we use the integer 0 as a boolean literal −
Date and Time Literals

• The MySQL date and time literals represent date and time values. Let us see
examples to understand how date and time values are represented in various
ways in MySQL.
Date literal
• In this example, we will display a date literal formatted as 'YYYY-MM-DD‘
• SELECT '2023-04-20' AS 'Date literal';
Following output is obtained −
2023-04-20
Time literal
In this example, we are displaying a time literal formatted as 'HH:MM:SS'.
SELECT '10:45:50' AS 'Time literal';
Following output is obtained −
10:45:50
Null Literals

• The MySQL Null literals represents the absence of a value. It is case in-sensitive.
Example
Following are some examples of valid NULL literals −
SELECT NULL AS 'NULL literals';
In lowercase −
SELECT null AS 'NULL literals';
• Output
• Following output is obtained −
NULL
What is Database?

A database is an organized collection of data stored electronically. It


allows users and applications to easily access, update, and manipulate
information. This data contains text, numbers, images, videos and
more. Databases are managed using specialized software known as
a Database Management System (DBMS), which facilitates the storage,
retrieval, and manipulation of data.
DDL - Data Definition Language

• DDL or Data Definition Language actually consists of the SQL


commands that can be used for 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.
• Table - to store data
• View - to project data in a desired format from one or more tables
• Sequence - to generate numeric values
• Index - to improve performance of queries on the tables
• Synonym - alternative name of an object
DML - Data Manipulation Language

• In SQL, DML (Data Manipulation Language) refers to commands used


to manipulate and manage data stored in a database. These
commands allow you to retrieve, insert, update, and delete data
within tables. DML is essential for interacting with the data itself, as
opposed to the structure of the database
Key Points:
• DML commands work directly with the data in the database.
• They do not alter the database schema or structure.
• Changes made by DML commands can be rolled back or committed
using TCL (Transaction Control Language) commands like COMMIT
and ROLLBACK.
DQL - Data Query Language
• DQL statements are used for performing queries on the data within
schema objects. The purpose of the DQL Command is to get some
schema relation based on the query passed to it. This command
allows getting the data out of the database to perform operations
with it. When a SELECT is fired against a table or tables the result is
compiled into a further temporary table, which is displayed or
perhaps received by the program.
• The SQL SELECT query is one of the most frequently used commands
to retrieve data from a database. It allows users to access and extract
specific records based on defined conditions, making it an essential
tool for data management and analysis
DCL - Data Control Language

• DCL (Data Control Language) includes commands such as GRANT and


REVOKE which mainly deal with the rights, permissions and other
controls of the database system. These commands are used to control
access to data in the database by granting or revoking permissions.
• In SQL, DCL (Data Control Language) is used to control access to data
in a database. It primarily deals with permissions, rights, and security.
The two main DCL commands are: grant and revoke.
Example of DCL
• GRANT SELECT, UPDATE ON employees TO user_name;
• This command grants the user user_name the permissions to select
and update records in the employees table.
TCL - Transaction Control Language

• Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group are successfully
completed. If any of the tasks fail, the transaction fails. Therefore, a transaction has
only two results: success or failure.
Common TCL Commands : commit, rollback ,savepoint. Example:
• BEGIN TRANSACTION;
• UPDATE employees SET department = 'Marketing' WHERE department = 'Sales';
• SAVEPOINT before_update;
• UPDATE employees SET department = 'IT' WHERE department = 'HR';
• ROLLBACK TO SAVEPOINT before_update;
• COMMIT;

In this example, a transaction is started, changes are made, and a savepoint is set. If
needed, the transaction can be rolled back to the savepoint before being committed.
SQL Operators

• 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
SQL Arithmetic Operators

• Arithmetic operators in SQL are used to perform mathematical


operations on numeric data types in SQL queries. Some common
arithmetic operators:
Example: Arithmetic Operations

• In this example, we calculates a 5% increment on employee salaries


and returns both the original and updated salary values.
• Query:
SELECT emp_salary, emp_salary * 1.05 AS "Revised Salary" FROM
employee;
Output:
SQL Comparison Operators

• Comparison Operators in SQL are used to compare one expression's


value to other expressions. SQL supports different types of
comparison operator, which are described below:
Example: Comparison Operation

• In this example, we will retrieve all records from the "MATHS" table
where the value in the "MARKS" column is equal to 50.
• Query:
• SELECT * FROM MATHS WHERE MARKS=50;
SQL 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..

• Example-In this example, retrieve all records from the "employee" table where
the "emp_city" column is equal to 'Allahabad' and the "emp_country" column is
equal to 'India'.
• SELECT * FROM employee WHERE emp_city =
'Allahabad' AND emp_country = 'India';
Special Operator (BETWEEN)

• Example:
• In this example, we will retrieve all records from the "employee" table
where the "emp_id" column has a value that falls within the range of
101 to 104 (inclusive).
• Query:
• SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
• Output:
Table

• Create Table-The CREATE TABLE statement is used to create a new table in a


database. In that table, if you want to add multiple columns, use the below
syntax.
• Syntax-
• CREATE TABLE table_name ( column1 datatype,
column2 datatype, column3 datatype, .... );
• Create Table Example

• Viewing Table Structure: After creating a table, use the following command to
view the structure of your table: DESC table_name;
Insert Value in this Table

• The INSERT INTO statement is used to insert new records in a table.


• Syntax - INSERT INTO table_name VALUES (value1, value2, value3, ...);
• Example-
Output:
SQL ALTER TABLE

• The SQL ALTER TABLE statement is a powerful tool that allows you to modify the
structure of an existing table in a database. Whether you are adding new
columns, modifying existing ones, deleting columns or renaming them, the ALTER
TABLE statement enables you to make changes without losing the data stored in
the table.
• ALTER TABLE table_name
[ADD | DROP | MODIFY] column_name datatype;
• 1. ADD - To add a new column to the table
• The ADD clause is used to add a new column to an existing table. You must
specify the name of the new column and its data type.
• Query:
2. MODIFY/ALTER - To change the data type of an
existing column
• The MODIFY (or ALTER COLUMN in some databases like SQL Server) clause is used
to modify the definition of an existing column, such as changing its data type or
size.
• Query:

• 3. DROP - To delete an existing column from the table


• The DROP clause allows you to remove a column from a table. Be cautious when
using this command as it will permanently remove the column and its data.
• Query:
4. RENAME COLUMN - To rename an existing column
• We can rename an existing column using the RENAME COLUMN clause. This
allows you to change the name of a column while preserving its data type and
content.
• Query:

• 5. RENAME TO - To rename the table itself


• We can rename an entire table using the RENAME TO clause. This changes the
name of the table while preserving its structure and data.
SQL DROP TABLE

• The DROP TABLE command in SQL is a powerful and essential tool


used to permanently delete a table from a database, along with all of
its data, structure, and associated constraints such as indexes,
triggers, and permissions.
• Drop table table_name;
SQL
UPDATE
• In SQL, the UPDATE statement is used to modify existing records in a table.
Whether you are updating a single record or multiple records at once, SQL
provides the necessary functionality to make these changes.
key points about UPDATE statement
• Modify Specific Data: The UPDATE statement can be used to change specific data in
one or more columns for rows that meet a certain condition.
• Target Specific Rows: You can control which rows to update by using the WHERE
clause. If you omit the WHERE clause, all rows in the table will be updated, so it’s
important to use this clause carefully to avoid unintended changes.
• Single or Multiple Columns: The UPDATE statement allows you to modify one or
more columns at a time. This makes it versatile when you need to update multiple
pieces of information for the same record.
• UPDATE table_name
SET column1 = value1, column2 = value2,...
Parameters

• UPDATE: The SQL command used to modify the data in a table.


• SET: This clause defines which columns will be updated and what their new
values will be.
• WHERE: The condition that determines which rows will be updated. Without it,
all rows will be affected.
• table_name: name of the table in which you want to make updates
• column1, column2, ...: The columns you want to update.
• value1, value2, ...: The new values to assign to these columns.
• condition: Specifies which rows to update. This condition is crucial, as omitting it
will update all rows in the table.
• UPDATE Customer SET CustomerName = 'Nitin' WHERE Age = 22;
output

You might also like