SQL for Beginners to Advance Le - RAJPUT, ANANT
SQL for Beginners to Advance Le - RAJPUT, ANANT
TO ADVANCE LEVEL
LEARN SQL FROM BASIC TO
ADVANCE LEVEL IN SIMPLEST WAY
WITH SOME INTERVIEWS
QUESTIONS
We will start with definitions and will carry on with query and
interview questions.
SQL COMMANDS
In this example, we've inserted four rows into the Employees table.
Note that:
Unique Constraint:
Drop Constraint:
Dropping a constraint removes the constraint from a table. The
specific syntax for dropping a constraint can vary depending on
the DBMS (e.g., SQL Server, PostgreSQL, MySQL). You
typically need to specify the constraint name you want to drop.
Dropping a PRIMARY KEY Constraint:
ALTER TABLE Students
DROP CONSTRAINT PK_Students;
INDEX
An index in a database is a data structure that improves the speed of
data retrieval operations on a database table. It's like an organized
reference to the data stored in a table, making it faster to search,
filter, and retrieve specific records. Indexes are essential for
optimizing database performance, especially when dealing with large
datasets.
Here are some key points to understand about indexes:
1. Purpose of Indexes:
Database Normalization
Now we will go through SQL Commands , I hope you are with your
laptop to perform query in practical .
SQL COMMANDS
CREATE AND INSERT
Let start with SQL commands, first we will learn how to Create a
table and then how to insert data into that table.
Let's create a table called Students with the following columns:
StudentID, FirstName, LastName, and Birthdate.
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Birthdate DATE
);
This SQL command creates a table named Students with four
columns: StudentID (as the primary key), FirstName, LastName,
and Birthdate.
Now, let's insert some sample data into the Students table:
## Inserting a single student
INSERT INTO Students (StudentID, FirstName, LastName,
Birthdate)
VALUES (1, 'John', 'Doe', '1995-03-15');
ALTER TABLE
In SQL, you can use the ALTER TABLE statement to make
structural changes to an existing table, such as adding, dropping, or
modifying columns. Here are examples of each of these actions:
1. Adding a Column:
To add a new column to the "Employees" table, you use the ALTER
TABLE statement with the ADD clause. For instance, if you want to
add a "Department" column to the "Employees" table, you can use
the following SQL statement:
ALTER TABLE Employees
ADD Department VARCHAR(50);
DELETE Command:
The DELETE command is used to remove records from a table. You
can also use a WHERE clause to specify which rows to delete.
Here's the basic syntax:
DELETE FROM table_name
WHERE condition;
These are just a few common SQL data types. The specific data
types available may vary slightly between database systems, but the
concepts are largely consistent. Choosing the appropriate data type
for each column is crucial for efficient storage and data integrity in a
database.
OPERATORS
AIRTHMETIC OPERATORS
Arithmetic operators in SQL are used to perform mathematical
operations on numerical values in the database. These operators
allow you to perform addition, subtraction, multiplication, division,
and modulo operations. Here's a brief description of each arithmetic
operator:
Addition Operator (+): The addition operator is used to add two or
more numerical values together. It returns the sum of the values.
Example: SELECT 5 + 3 AS sum result; ---- Returns 8
Subtraction Operator (-): The subtraction operator is used to
subtract one numerical value from another. It returns the difference
between the values.
Example: SELECT 10 - 5 AS difference result; ---- Returns 5
Multiplication Operator (*): The multiplication operator is used to
multiply two or more numerical values together. It returns the product
of the values.
Example: SELECT 4 * 6 AS product result; --- Returns 24
Division Operator (/): The division operator is used to divide one
numerical value by another. It returns the quotient of the division. Be
cautious with this operator, as dividing by zero can lead to errors.
Example: SELECT 20 / 4 AS division result; -- Returns 5
COMPARISON OPERATORS
Comparison operators in SQL are used to compare values in a database table.
They return a Boolean (TRUE or FALSE) result based on the comparison. These
operators are essential for filtering and querying data based on specific conditions.
Now, let's describe each of the comparison operators in more detail:
Equal to (=): The equal-to operator checks if two values are equal. It
returns TRUE if they are, and FALSE if they are not.
Example: SELECT * FROM employees WHERE department_id = 5;
Not equal to (!= or <>): The not-equal-to operator checks if two values are not
equal. It returns TRUE if they are not equal, and FALSE if they are equal.
Example: SELECT * FROM products WHERE category_id != 2;
-- OR
SELECT * FROM products WHERE category_id <> 2;
Less than (<): The less-than operator checks if one value is less than another. It
returns TRUE if the condition is met and FALSE otherwise.
Example:
SELECT * FROM orders WHERE order_total < 100;
Greater than (>): The greater-than operator checks if one value is greater than
another. It returns TRUE if the condition is met and FALSE otherwise.
Example:
SELECT * FROM products WHERE price > 50;
Less than or equal to (<=): The less-than-or-equal-to operator checks if one
value is less than or equal to another. It returns TRUE if the condition is met and
FALSE otherwise.
Example:
SELECT * FROM students WHERE score <= 75;
Greater than or equal to (>=): The greater-than-or-equal-to operator checks if
one value is greater than or equal to another. It returns TRUE if the condition is
met and FALSE otherwise.
Example:
SELECT * FROM employees WHERE salary >= 50000;
Not Less Than (!<): The not-less-than operator checks if one value is not less
than another. It returns TRUE if the condition is met and FALSE otherwise.
Example: SELECT * FROM products WHERE stock_quantity !< 10;
Not Greater Than (!>): The not-greater-than operator checks if one value is not
greater than another. It returns TRUE if the condition is met and FALSE otherwise.
Example:
SELECT * FROM customers WHERE age !> 30;
LOGICAL OPERATORS
Logical operators in SQL are used to combine or modify conditions in SQL
statements. They allow you to create complex conditions for filtering and selecting
data. The commonly used logical operators are:
#As we discuss earlier AND and OR operators so we will not discuss it again
Now, let's describe the other operators in the context of the "employees" table:
ALL Operator: The "ALL" operator is used to compare a value to all values in a
subquery. It returns true if the condition is true for all rows in the subquery. For
example, you might use it to find employees with salaries greater than all salaries
in a particular department.
SELECT employee_name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department =
'Sales');
ANY Operator: The "ANY" operator is used to compare a value to any values in a
subquery. It returns true if the condition is true for at least one row in the subquery.
For instance, you could find employees with salaries greater than any salary in the
IT department.
SELECT employee_name
FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE department =
'IT');
EXISTS Operator: The "EXISTS" operator is used to check for the existence of
rows in a subquery. It returns true if the subquery returns one or more rows.
SELECT department_name
FROM departments
WHERE EXISTS (SELECT 1 FROM employees WHERE department_id =
departments.department_id);
LIKE Operator: The "LIKE" operator is used for pattern matching using wildcard
characters. It's often used to search for rows with values that match a specific
pattern. For instance, you could find employees whose names start with "J."
SELECT employee_name
FROM employees
WHERE employee_name LIKE 'J%';
NOT Operator: The "NOT" operator negates a condition. It returns true if the
condition is false. You can use it to find employees who are not in the IT
department.
SELECT employee_name
FROM employees
WHERE department_name <> 'IT';
IS NULL Operator: The "IS NULL" operator is used to check for NULL values in a
column. It returns true if a column contains a NULL value. For example, you can
find employees with no assigned manager.
SELECT employee_name
FROM employees
WHERE manager_id IS NULL;
UNIQUE Operator: The "UNIQUE" operator, often implied by the use of a unique
constraint or primary key, enforces uniqueness of values in a column, ensuring
that no two rows have the same value in that column.
-- Assuming the "employee_id" column is unique (usually a primary key)
SELECT DISTINCT employee_id
FROM employees;
DISTINCT:
DISTINCT is used to filter out duplicate values in the
result set. It ensures that the query returns only unique
rows, removing any duplicates.
You can use DISTINCT with one or more columns to
specify the uniqueness constraint. The query will then
return distinct combinations of values in those columns.
Example:
SELECT DISTINCT department FROM employees;
ALIAS
In SQL, an alias is a temporary name or shorthand for a table or
column that you can use in a query to make your SQL statements
more readable or to avoid naming conflicts. Aliases are often used to
simplify complex queries, especially when working with self-joins,
subqueries, or when column names are long or not user-friendly.
There are two primary types of aliases in SQL:
In this query, "e" and "d" are table aliases for the
"employees" and "departments" tables,
respectively.
Aliases improve the readability and clarity of SQL queries and are
especially helpful when working with complex queries or large
databases. They don't affect the underlying data in the tables; they
are used solely for presentation in the query result.
JOINS
This one is very important topic, so read it properly before
going to theory portion just look at this image carefully.
Table : Employees
EmployeeID EmployeeName DepartmentID
1 John 101
2 Sarah 102
3 Michael 101
4 Emily 103
5 Chris 104
Table : Departments
DepartmentID DepartmentName
101 HR
102 Sales
103 IT
INNER JOIN: An INNER JOIN returns only the rows that have
matching values in both tables. In this case, it will return employees
who belong to a department.
SELECT EmployeeName, DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
Run this Query in your device see the results
LEFT JOIN (LEFT OUTER JOIN): A LEFT JOIN returns all rows
from the left table (Employees) and the matching rows from the right
table (Departments). If there's no match in the right table, it still
includes the left table data with NULL values for the right table.
SELECT EmployeeName, DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
RIGHT JOIN (RIGHT OUTER JOIN): A RIGHT JOIN returns all rows
from the right table (Departments) and the matching rows from the
left table (Employees). If there's no match in the left table, it still
includes the right table data with NULL values for the left table.
SELECT EmployeeName, DepartmentName
FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
FULL JOIN (FULL OUTER JOIN): A FULL JOIN returns all rows
when there is a match in either the left or the right table. If there's no
match in one of the tables, it includes NULL values for that side.
SELECT EmployeeName, DepartmentName
FROM Employees
FULL JOIN Departments ON Employees.DepartmentID =
Departments.DepartmentID;
UNION ALL:
INTERSECT:
TRUNCATE
The SQL TRUNCATE TABLE command is used to delete complete
data from an existing table. You can also use DROP TABLE
command to delete complete table but it would remove complete
table structure form the database and you would need to re-create
this table once again if you wish you store some data.
Syntax: The basic syntax for the TRUNCATE statement is:
TRUNCATE TABLE table_name;
1. Key Points:
TRUNCATE is typically used for removing all
rows from a table, but it can be used for
temporary tables and materialized views,
depending on the database system.
Unlike the DELETE statement, TRUNCATE
does not generate individual row delete
operations. It simply deallocates the data
pages associated with the table, effectively
dropping all rows in a single operation.
Due to its efficiency, TRUNCATE is usually
faster than DELETE for removing all rows
from a table.
TRUNCATE is typically used for removing all
data from a table without affecting the table's
structure (columns, constraints, indexes,
etc.). After truncating a table, it's still possible
to insert data into it.
Because TRUNCATE is a minimally logged
operation, it generates fewer log entries and
uses fewer system resources, making it a
good choice for quickly cleaning out a table,
especially in high-performance or batch
processing scenarios.
Considerations:
1. ACID Properties:
Atomicity: A transaction is atomic, meaning
it is an all-or-nothing operation. Either all its
changes are applied, or none are. If any part
of the transaction fails, the entire transaction
is rolled back.
Consistency: A transaction ensures that the
database transitions from one consistent
state to another. It preserves the integrity of
the data by enforcing constraints and rules.
Isolation: Transactions are executed in
isolation from one another, meaning the
changes made by one transaction are not
visible to other transactions until the first
transaction is committed.
Durability: Once a transaction is committed,
its changes are permanent and survive
system failures. Even if the system crashes,
the changes are not lost.
2. Beginning and Ending a Transaction:
A transaction begins with the BEGIN
TRANSACTION, START TRANSACTION, or
similar statement.
It ends with a COMMIT to make the changes
permanent or a ROLLBACK to undo the
changes.
3. Savepoints:
Savepoints allow you to mark a point within a
transaction to which you can later roll back
without affecting the entire transaction.
4. Nested Transactions:
Some database systems support nested
transactions, allowing transactions to be
divided into subtransactions. Subtransactions
can be committed or rolled back
independently, but the outer transaction's
final outcome affects all subtransactions.
Transaction Control Statements:
3. ROLLBACK:
Undoes all changes made within the transaction,
reverting the database to the state it was in before the
transaction started.
Example: BEGIN TRANSACTION;
--------- SQL statements within the transaction
ROLLBACK;
4. SAVEPOINT:
Defines a savepoint within a transaction, allowing you to
roll back to that point later.
Example: BEGIN TRANSACTION;
-- SQL statements
SAVEPOINT my_savepoint;
-- More SQL statements
In this example, a savepoint named my_savepoint is
created within the transaction. You can later use this
savepoint to roll back to this specific point.
5. ROLLBACK TO SAVEPOINT:
Rolls back the transaction to a specific savepoint.
Example: BEGIN TRANSACTION;
-- SQL statements
SAVEPOINT my_savepoint;
-- More SQL statements
ROLLBACK TO my_savepoint;
-- Any changes made after my_savepoint are undone
RELEASE:
6. SET TRANSACTION:
Used to set characteristics of a transaction,
such as isolation level.
Transaction Isolation Levels:
Isolation levels control how transactions interact with each other. The
standard isolation levels include:
1. READ UNCOMMITTED:
Allows a transaction to read uncommitted
changes made by other transactions. It offers
the lowest isolation but the highest
concurrency.
2. READ COMMITTED:
A transaction can only read committed
changes made by other transactions. This
provides a balance between isolation and
concurrency.
3. REPEATABLE READ:
Ensures that a transaction can read the same
data consistently throughout its duration.
However, it may still allow new data to be
inserted by other transactions.
4. SERIALIZABLE:
Provides the highest level of isolation by
preventing other transactions from modifying
or inserting data that a transaction is reading.
5. SNAPSHOT ISOLATION:
This is a variation of isolation that allows a
transaction to see a consistent snapshot of
the database as it existed at the start of the
transaction.
Transaction management is crucial for maintaining data consistency
and integrity in a multi-user database environment. Choosing the
appropriate isolation level and using transaction control statements
correctly are essential for developing robust and reliable database
applications.
TEMPORARY TABLES
Temporary tables are a type of database table that is used for storing
temporary data. These tables are typically created and managed
within a session and exist only for the duration of that session. Once
the session ends or the connection is closed, temporary tables are
automatically deleted. Temporary tables are useful for storing
intermediate results, temporary data, or isolating data within a
specific session without affecting the global database schema.
Here are some key characteristics and uses of temporary tables:
2. Session Scope:
Temporary tables are local to the session or
connection in which they are created.
They are not visible or accessible to other
sessions or connections.
Each session can create its own set of
temporary tables with the same name without
conflicts.
3. Automatic Cleanup:
Temporary tables are automatically dropped
(deleted) when the session ends or the
connection is closed.
They do not persist beyond the duration of
the session.
This automatic cleanup simplifies
management and ensures that temporary
tables do not clutter the database.
4. Data Isolation:
Temporary tables are useful for isolating and
segregating data within a specific session.
They are often used to store intermediate
results during complex query operations or to
prevent naming conflicts in scenarios where
multiple sessions may be working with similar
data.
5. Performance Optimization:
Temporary tables can be employed to
improve query performance by allowing you
to store and manipulate intermediate results
rather than repeatedly recalculating them.
6. Data Transformation:
Temporary tables are commonly used during
data transformation, such as data cleansing,
aggregation, or data loading processes.
7. Materialized Views:
Temporary tables can be used to create
materialized views, which store the results of
complex or time-consuming queries for faster
retrieval.
8. Security and Permissions:
Temporary tables may inherit the security and
permissions settings of the user who creates
them, and they can be restricted to specific
users or roles.
9. Database System Compatibility:
The support and syntax for temporary tables
may vary between database systems. It's
important to refer to the documentation of
your specific database management system
to understand how temporary tables are
implemented.
Temporary tables are a valuable tool in database development and
query optimization, allowing for the efficient management of data
within a session while minimizing the impact on the overall database
schema. They are particularly useful in scenarios where data needs
to be isolated, transformed, or stored temporarily.
CLONING A TABLE
Cloning a table involves creating a new table that has the same
structure as an existing table. The clone, or copied table, typically
has the same columns, data types, and constraints as the original
table. Cloning is useful for various purposes, such as creating
backups, creating a working copy for analysis or experimentation, or
creating a template for new tables. The specific SQL syntax for
cloning a table may vary depending on the database system you are
using, but here's a general outline of how it is done:
Basic Steps to Clone a Table:
1. Auto-Increment Column:
An auto-increment column is a column in a
database table that automatically generates a
unique value for each new row.
It is often used as the primary key of the
table, ensuring that each row has a distinct
identifier.
2. Primary Key Use:
Auto-increment columns are commonly used
as primary keys, but they can also be used in
other situations where unique identifiers are
needed.
3. Data Type:
Auto-increment columns are typically of
numeric data types, such as INT, BIGINT, or
SERIAL, depending on the database system
being used.
4. Initialization and Increment:
The initial value and increment (step size) are
configurable. You can set the starting value
and specify how much the column should
increment by for each new row.
5. Database Support:
The syntax and implementation of auto-
increment columns may vary between
database systems. For example, in MySQL,
you use AUTO_INCREMENT, in
PostgreSQL, you use SERIAL, and in SQL
Server, you use IDENTITY.
6. Uniqueness:
Auto-increment values are unique within the
table. This uniqueness is guaranteed by the
database system.
7. No Manual Assignment:
You typically don't need to manually provide a
value for an auto-increment column when
inserting a new row. The database system
handles it automatically.
8. Concurrency Considerations:
Auto-increment columns are designed to
handle concurrent inserts. Even in a multi-
user environment, each new row will receive
a unique value.
9. Resetting or Restarting:
In some database systems, you can reset or
restart the auto-increment value, but this
operation should be used with caution as it
can affect data integrity.
Example in MySQL:
CREATE TABLE Employees (
EmployeeID INT AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
In this example, the EmployeeID column is defined as an auto-
increment primary key. When new rows are inserted into the
Employees table, the EmployeeID value is automatically generated
and incremented.
1. SELECT DISTINCT:
Use the SELECT DISTINCT statement to
retrieve unique values from a column or
combination of columns in a table. This
eliminates duplicate values and returns only
distinct rows.
SYNTAX: SELECT DISTINCT column1, column2
FROM table_name;
SYNTAX:
DELETE FROM table_name
WHERE (column1, column2) NOT IN (
SELECT MIN(column1), MIN(column2)
FROM table_name
GROUP BY column1, column2
);
This query keeps the minimum row for each set of
duplicates based on column1 and column2.
6. INSERT INTO with SELECT DISTINCT:
To insert data into a new table while removing
duplicates, you can use the INSERT INTO
statement with a SELECT DISTINCT
subquery from the original table.
SYNTAX:
INSERT INTO new_table (column1, column2)
SELECT DISTINCT column1, column2
FROM original_table;
Handling duplicates in SQL depends on the specific
requirements and the database system you are using.
Depending on the situation, you may choose one or a
combination of these techniques to address duplicate
records in your data.
SQL INJECTION
SQL injection is a malicious technique in which an attacker
manipulates the data input into an application's SQL query,
exploiting vulnerabilities in the application's code to gain
unauthorized access to a database. It is one of the most
common and dangerous web application security
vulnerabilities. Here's an overview of SQL injection, its risks,
and how to prevent it:
How SQL Injection Works:
CONCAT() Function:
These functions are part of the standard SQL language and are
widely supported by most relational database systems, including
MySQL, PostgreSQL, SQL Server, and others. They are useful for a
variety of tasks, including data manipulation, report generation, and
random data generation.
INTERVIEW QUESTIONS