0% found this document useful (0 votes)
46 views20 pages

Comprehensive SQL Guide for Beginners

This document provides a comprehensive overview of SQL, covering its various components such as data types, SQL constraints, operators, and commands including DDL, DML, DCL, and TCL. It also explains SQL queries, functions, joins, subqueries, keys, indexing, and advanced SQL concepts like views and transactions with ACID properties. Additionally, it details the usage of aggregate functions, clauses, and set operations in SQL.

Uploaded by

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

Comprehensive SQL Guide for Beginners

This document provides a comprehensive overview of SQL, covering its various components such as data types, SQL constraints, operators, and commands including DDL, DML, DCL, and TCL. It also explains SQL queries, functions, joins, subqueries, keys, indexing, and advanced SQL concepts like views and transactions with ACID properties. Additionally, it details the usage of aggregate functions, clauses, and set operations in SQL.

Uploaded by

venkypotla19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🔹 Basic SQL

 Introduction to SQL (DDL, DML, DCL, TCL)

 Data Types

 SQL Constraints (NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT)

 SQL Operators (Arithmetic, Comparison, Logical, IN, BETWEEN, LIKE)

🔹 SQL Queries

 SELECT Statement

 WHERE Clause

 DISTINCT

 ORDER BY

 LIMIT / TOP

 GROUP BY

 HAVING

🔹 Functions

 Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)

 String Functions (UPPER, LOWER, SUBSTRING, LENGTH, TRIM)

 Date Functions (NOW, GETDATE, DATEADD, DATEDIFF)

 Conversion Functions (CAST, CONVERT)

🔹 Joins

 INNER JOIN

 LEFT JOIN

 RIGHT JOIN

 FULL OUTER JOIN

 SELF JOIN

 CROSS JOIN

🔹 Subqueries & Clauses

 Subqueries (Single-row, Multi-row, Correlated)

 EXISTS / IN / ANY / ALL

🔹 Keys & Indexing

 Primary Key

 Foreign Key

 Candidate Key

 Composite Key

 Indexes (Clustered & Non-clustered)

🔹 Advanced SQL

 Views
 Stored Procedures & Functions (basic idea)

 Triggers (basic idea)

 Transactions & ACID Properties

 Normalization (1NF, 2NF, 3NF, BCNF)

SQL
 SQL is the Structured Query Language
 It is used to manage and manipulate relational databases.
 Not Case sensitive and keywords are uppercase
 Structed query language is programming language that stores
, manipulate and retrieve the data from the database
 Data base is a system that’s allows users to store and organise
the data
Commands in sql

1) DATA TYPES IN SQL


Data Type Description
INT Integer
VARCHAR(n) String of variable length n
CHAR(n) Fixed-length string of n chars
DATE Date value
FLOAT, DECIMAL Decimal values
BOOLEAN True/FalsE

OPERATORES
 Arithmetic → +, -, *, /, %
 Comparison → =, !=, >, <, >=, <=
 Logical → AND, OR, NOT
 Special → BETWEEN, IN, LIKE, NULL, EXISTS
 Bitwise → &, |, ^, ~, <<, >>
 Concatenation → || or + depending on DB
STRING FUNCTION
Function Description Example Output
UPPER() Converts to uppercase SELECT UPPER('sql') SQL
LOWER() Converts to lowercase SELECT LOWER('SQL') sql
SELECT
SUBSTRING() Extracts part of a string Hello
SUBSTRING('HelloWorld',1,5)
LENGTH() Counts characters SELECT LENGTH('SQL') 3
Removes
TRIM() SELECT TRIM(' SQL ') SQL
spaces/characters
DATA FUNCTIONS
Function Purpose Example Output
NOW()  Current system date SELECT NOW(); 2025-10-03 [Link]

DATEDIFF() Difference in days DATEDIFF('2025-12-31','2025-10-03') 89

DAY(), MONTH(),  Get day, month, MONTH('2025-10-


10
YEAR() year 03')
DATEADD() Add/subtract units DATEADD(DAY,10,'2025-10-03') 2025-10-13
FORMAT(), Format TO_CHAR(NOW(),'DD-Mon- 03-Oct-
TO_CHAR() date YYYY') 2025
LAST_DAY() Last day of month LAST_DAY('2025-10-03') 2025-10-31
NEXT_DAY() Next weekday NEXT_DAY(SYSDATE,'FRIDAY') 2025-10-10
2)
 DDL: data definition language
Command Description Example
Creates a new
CREATE table or CREATE TABLE student (...);
database
Modifies an ALTER TABLE student ADD
ALTER
existing table email VARCHAR(100);
Deletes a table
DROP DROP TABLE student;
or database
Deletes all
TRUNCATE data from a TRUNCATE TABLE student;
table (faster)
Renames a RENAME TABLE student TO
RENAME
table learners;

 DML – Data Manipulation Language

These commands are used to manipulate data (insert, update, delete).

Command Description Example


INSERT Adds new rows INSERT INTO student VALUES (1, 'Ravi', 20);
UPDATE Modifies existing data UPDATE student SET age = 21 WHERE rollno = 1;
DELETE Deletes rows DELETE FROM student WHERE rollno = 1;

 DQL – Data Query Language


Used to query data from the database.
Command Description Example
SELECT Retrieves data from tables SELECT * FROM student;

 DCL – Data Control Language


Controls access permissions to data.

Command Description Example


GRANT Gives privileges to users GRANT SELECT ON student TO user1;
REVOKE Removes privileges from users REVOKE SELECT ON student FROM user1;

 TCL – Transaction Control Language


Used to control transactions (like a set of operations).

Command Description Example


COMMIT Saves the changes made COMMIT;
ROLLBACK Undoes changes made ROLLBACK;
SAVEPOINT Sets a point to rollback to SAVEPOINT sp1;

SET TRANSACTION
Sets transaction SET TRANSACTION READ
properties ONLY;
……………………………………………………………………………………………………
Transactions & ACID Properties
What is a transaction?
A transaction is a sequence of one or more SQL statements treated as a single
logical unit of work. Either all statements succeed (and are made permanent
with COMMIT) or none take effect (using ROLLBACK).
Common uses: money transfers, booking/reservations, inventory changes.
-- Start a transaction

BEGIN TRANSACTION; -- SQL Server / standard

-- or

START TRANSACTION; -- MySQL / MariaDB

-- or in some clients simply:

BEGIN;

-- Make changes permanent

COMMIT;

-- Undo changes since transaction start (or since last SAVEPOINT)

ROLLBACK;

Atomicity
Description: The transaction is all-or-nothing. Either every operation inside the
transaction completes successfully, or none does.
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
-- if no errors
COMMIT;
-- if any error occurs -> ROLLBACK;
C — Consistency
Description: A transaction moves the database from one valid state to
another, preserving all rules: constraints, triggers, cascades, checks, unique
keys, foreign keys, etc.
I — Isolation
Description: Concurrent transactions must not interfere with each other in a
way that causes incorrect results. Each transaction should behave as if it were
running alone (to an extent determined by isolation level).
D — Durability
Description: Once a transaction commits, its changes are permanent and
survive subsequent system crashes, power failures, or errors
----------------------------------------------------------------------------------------------------

SQL Constraints
Constraint Description
PRIMARY KEY Unique identifier + NOT NULL

It is a COLUMN which can be


unqely identified(they may be
CANDIDATE KEY
multiple candidate keys) not
null , unique , not primary key

COMBINATION OF 2 COLUMNS
COMPOSIT KEYkm n
(UNIQUELY IDEFINED)

References primary key of


FOREIGN KEY
another table

UNIQUE Ensures all values are unique

NOT NULL Column cannot be NULL

CHECK Validates condition

DEFAULT Sets default value

Primary key :
 CREATE TABLE student ( id INT PRIMARY KEY, name VARCHAR(100))
Foreign key :
 Enforces a link between two tables.
 foreign key in one table points to the primary key in another table.

CREATE TABLE department


(deptid INT PRIMARY KEY, deptname VARCHAR(100));

CREATE TABLE student


(id INT PRIMARY KEY,name VARCHAR(100), deptid INT,
FOREIGN KEY (deptid) REFERENCES department(deptid));

UNIQUE key:
 Ensures all values in a column are different.

CREATE TABLE student (email VARCHAR(100) UNIQUE);


CHECK KEY :
 Validates values based on a condition.
 Rejects data that doesn't satisfy the condition.

CREATE TABLE student (id INT, age INT CHECK (age >= 18) );
DEFAULT KEY:
 Assigns a default value if no value is provided.

CREATE TABLE student (id INT,status VARCHAR(20) DEFAULT 'active'));

RENAME / DROP Constraints


 You can add/remove constraints after table creation.
Add:
ALTER TABLE student ADD CONSTRAINT chk_age CHECK (age >= 18);
Drop:
ALTER TABLE student DROP CONSTRAINT chk_age;
……………………………………………………………………………………………………..
Flow of execution in SQL
diff
 DISTINCT → affects only the result of SELECT.
 Removes duplicate rows from the result set.
SELECT DISTINCT City
FROM Students;
 Returns each city only once, even if multiple students live in the
same city.
 UNIQUE → affects the data in the table (constraint/ index).
 No diff rows have same value
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE
);
Clauses
 WHERE – filter records
 GROUP BY – group results
 HAVING – filter groups
 ORDER BY – sort results
 DISTINCT – remove duplicates
 LIMIT – limit rows
WHERE
 Used to filter the records based on condition
 We have to use this before any grouping by class
SELECT * FROM Employees
WHERE dept_id = 1 AND salary > 30000
GROUPING
 It groups the rows which have the same values in specified columns
 Often used with aggregate functions like SUM(), COUNT(), AVG().
 Each ani vaste we will use grouping
SELECT dept_id, COUNT(*) AS total_employees
FROM Employees
GROUP BY dept_id;
 Counts number of employees in each department.

HAVING Clause
 Filter the groups after aggregate function
 Similar to WHERE, but WHERE filters rows before grouping, HAVING
filters after grouping
SELECT dept_id, AVG(salary) AS avg_salary
FROM Employees
GROUP BY dept_id
HAVING AVG(salary) > 40000;
 Shows departments with average salary > 40000.
ORDER BY

 Sorts the result set by one or more columns.


 Default order is ASC . use DESC for D.O
 Lists employees from highest salary to lowest
SELECT emp_name, salary
FROM Employees
ORDER BY salary DESC;

DISTINCT Clause
 Removes the duplates in result set
 Returns a list of unique department IDs.
SELECT DISTINCT dept_id
FROM Employees;
LIMIT Clause
 Used to limit the number of rows retuned by the query
SELECT * FROM Employees
LIMIT 5;
 Returns first 5 rows of Employees.

INDEX -> An index in SQL is like the index of a book.


 Instead of reading every page to find a word, you go directly to the
index → it speeds up search.
 Similarly, an SQL index improves the speed of queries by allowing the
database to find rows more quickly.
Key Points
 Purpose: Speeds up data retrieval (SELECT queries).
 Downside: Slows down INSERT, UPDATE, and DELETE because the index
also has to be updated.
 Storage: Takes up extra memory space.
CREATE INDEX index_name
ON table_name(column_name);
Types of Index
1. Primary Index
o Automatically created when you define a PRIMARY KEY.
o Ensures uniqueness.
2. Unique Index
o Ensures all values in a column are unique (similar to UNIQUE
constraint).
3. Clustered Index
o It defines the order in which the data is physically stored in table.
o Example : dictionary (letter)
o It has only one cluster
4. Non-Clustered Index
o Indexed data is stored in one place , actually data is stored in one
palce .
o Creates a separate structure from the table data.
o Table can have multiple non-clustered indexes.

-- Create an index
CREATE INDEX index_name
ON table_name(column_name);

-- Create a unique index


CREATE UNIQUE INDEX index_name
ON table_name(column_name);

-- Drop (delete) an index


DROP INDEX index_name;

-- Create a table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
City VARCHAR(50)
);

-- Create an index on Name


CREATE INDEX idx_name
ON Students(Name);

-- Query using index


SELECT * FROM Students
WHERE Name = ‘Neeraj’;

………………………………………………………………………………..

Joins in SQL
Type Description
INNER JOIN Returns matching rows in both tables

LEFT JOIN All rows from left table + matched from right

RIGHT JOIN All rows from right table + matched from left

FULL JOIN All matched + unmatched rows from both tables


SELECT [Link], [Link]
FROM student s
INNER JOIN department d ON [Link] = [Link];
……………………………………………………………………………………..
Subquery
A query inside another query.
SELECT name FROM student WHERE age > (SELECT AVG(age) FROM
student):
TYPRS -> SINGLE ROW , MULTI ROW , CORELATED
IN , ANY , ALL , EXITS
EXISTS
 Checks if the subquery returns at least one row.
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE e.dept_id =
d.dept_id);

2. IN
 Compares a value with a list of values from the subquery.
SELECT name
FROM employees
WHERE dept_id IN (SELECT dept_id FROM departments WHERE
location='Delhi');

3. ANY
 Returns true if the condition matches at least one value.
SELECT name
FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE
dept_id=2);
👉 Salary greater than any one employee in dept 2.

4. ALL
 Returns true if the condition matches all values.
SELECT name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE
dept_id=2);

…………………………………………………………………….
Aggregate Functions
Function Description Syntax Example
COUNT() Counts rows SELECT COUNT(*) FROM Employees;

SUM() Total sum SELECT SUM(salary) FROM Employees;

AVG() Average SELECT AVG(salary) FROM Employees;

MIN() Minimum value SELECT MIN(salary) FROM Employees;

MAX() Maximum value SELECT MAX(salary) FROM Employees;

---------------------------------------------------------------------------------------
Aliases
Rename a column or table temporarily.
SELECT name AS student_name FROM student;
Views
 A view is a virtual table created based on the result of a SQL query
 We can reuse the view ,instead of full table

Creation of view
syntax
Create view view_name AS select col1 , col2 from table_name
condition
CREATE VIEW top_students AS
SELECT name, marks FROM student WHERE marks > 90;

Reuse of view
Syntax
Select * from view_name ;
Modify of view
Syntax
Create OR REPLACE VIEW view_name AS SELECT col1 , col2 FROM
table_name CONDITION;
DROP of view
syntax
DROP VIEW view_name ;
SETS IN SQL
 Sets are used to combine the results of 2 or more sql queries
 They are UNION , UNION all , INTERSECT , EXCEPT

 UNION → Combines results, removes duplicates.


 UNION ALL → Combines results, keeps duplicates.
 INTERSECT → Returns only common records.
 EXCEPT / MINUS → Returns records in first query but not in second.

UNION
 Combines the result of 2 queries
 Removes duplicates
Select col1 , col2 from stu

UNION

Select col1, col2 from stu1;

UNION ALL
 Similar to UNION, but keeps duplicates.
 Faster than UNION because it doesn’t check for duplicates.
Select col1 , col2 from stu
UNION ALL
Select col1, col2 from stu1;

INTERSECT
 Returns only common rows from both queries.
Select col1 , col2 from stu
INTERSECT
Select col1, col2 from stu1;

EXCEPT

 Returns rows from the first query that are not present in the second query.

SELECT column1, column2 FROM table1

EXCEPT

SELECT column1, column2 FROM table2;

What is a Trigger?
A Trigger is like an automatic action in a table.

 A trigger is a database object that is automatically executed or fired when a specific event occurs in a
database table.

 It runs automatically when you INSERT, UPDATE, or DELETE data.

 You don’t call it ma nually.

Think of it like a doorbell: when someone presses the button (event), the bell rings (trigger runs).

🔹 Types of Triggers

1. BEFORE Trigger

 Runs before the action happens.


 Example: Check if salary is negative before inserting a row.

2. AFTER Trigger

 Runs after the action happens.

 Example: After adding a new employee, add a record in audit table.

3. INSTEAD OF Trigger

 Runs instead of the action.

 Example: When someone tries to update a table, do your own custom update instead.

Key Points
 Trigger = automatic action
 Types = Before, After, Instead Of
 Common uses: check data, log changes, enforce rules

 Conversion functions are used to change data from one type to another.
 Useful when you need to convert numbers to strings, dates to strings, or strings to
numbers, etc.

🔹 1. CAST() Function
Definition:
 CAST() converts a value from one data type to another.
 Standard SQL function.
 Convert()

Nf1 ->

Important Queries
-- >Find total students
SELECT COUNT(*) FROM student;

-- >Find max marks


SELECT MAX(marks) FROM student;
-- >Find students in specific department
SELECT * FROM student WHERE deptid = 2;

--> List students alphabetically


SELECT * FROM student ORDER BY name ASC;

Common questions

Powered by AI

SQL triggers are beneficial for automatically enforcing business rules, ensuring data integrity, and maintaining audit logs by executing predefined operations in response to certain events like INSERT, UPDATE, or DELETE . For example, a BEFORE trigger can be used to validate data before it's inserted into a table . However, challenges include complexity in debugging and maintenance, as triggers can be difficult to trace and can lead to unintended effects if not managed carefully . There is also potential for performance issues, as triggers add overhead to data operations .

Subqueries are queries nested inside a main query and are used to perform operations that require multiple steps, such as filtering or aggregation, without needing multiple separate queries . They can return single or multiple rows or be correlated to provide dynamic filtering . Joins, however, are used to retrieve data from multiple tables in a single query, combining rows based on related columns . While joins are typically more efficient than subqueries for data retrieval across multiple tables, subqueries offer more complexity for filtering criteria that can't be directly achieved with joins alone .

Different types of joins, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, provide various ways to combine rows from two or more tables . INNER JOIN returns rows when there is a match in both tables, providing a precise and potentially faster result as it retrieves only necessary data . LEFT and RIGHT JOINs include all rows from one table and matching rows from the other, which can include NULLs for non-matching rows and may impact performance negatively with large datasets . FULL OUTER JOIN combines all data, filled with NULLs where necessary, which can slow down performance due to processing full dataset unions . These joins balance between data completeness and query simplicity, affecting performance based on the amount of data processed.

Constraints such as UNIQUE and PRIMARY KEY ensure data integrity by enforcing rules on data input, thus preventing duplicates and maintaining referential integrity . Indexing can be used alongside constraints to improve query performance. Indexes speed up data retrieval by allowing quick access to rows , while constraints like PRIMARY KEY often automatically generate indexes that ensure uniqueness and fast access . The combination allows for both efficient query execution and robust data integrity management.

ACID properties ensure that SQL transactions maintain data integrity during multiple operations by enforcing four key principles: Atomicity guarantees that all operations within a transaction are completed; if any operation fails, the entire transaction is rolled back . Consistency ensures that a transaction moves the database from one valid state to another, preserving database rules and constraints . Isolation prevents concurrent transactions from affecting each other, as each transaction operates as though it is the only one running . Durability ensures that once a transaction is committed, its changes are permanent, even in the event of a system failure .

The combination of SQL aggregate functions like COUNT, SUM, AVG, MIN, and MAX with the GROUP BY clause allows for the aggregation of data into meaningful statistics based on specified groups . GROUP BY collects data across rows with common values in specified columns, enabling functions to calculate statistics per group. For example, using COUNT and GROUP BY, you can find the number of employees in each department, or AVG combined with GROUP BY to determine average salaries per department . This approach provides deeper insights and summary statistics from detailed records.

Conversion functions like CAST and CONVERT enhance flexibility in SQL queries by allowing data to be transformed from one type to another, facilitating operations on mixed data types and ensuring compatibility across different functions . For example, CAST can convert a number to a string format or a string representing a date into a date type, allowing for consistent data processing . This functionality is crucial when integrating or comparing data from various sources or ensuring that operations requiring type consistency, such as arithmetic or date functions, are successfully executed.

SQL transaction control commands like COMMIT, ROLLBACK, and SAVEPOINT are essential for maintaining database consistency as they dictate whether a transaction's changes are preserved or reversed . COMMIT finalizes all operations in a transaction, ensuring permanent application in the database . ROLLBACK undoes changes, allowing recovery to a previous consistent state . SAVEPOINT enables partial rollbacks, increasing recovery precision . These commands interact with isolation levels, which define how transactions are isolated from one another to prevent issues like dirty reads or phantom reads . Properly managing these controls and levels is fundamental to maintaining consistency amid concurrent transactions.

Normalization organizes a database into tables and columns to reduce redundancy and dependency . It progresses through normal forms (1NF, 2NF, 3NF, BCNF) to minimize data duplication and ensure data dependencies make sense, resolving issues like data anomalies and redundant relationships . For example, 1NF eliminates repeating groups by ensuring atomic attributes; 2NF removes partial dependencies on a composite key, and 3NF eliminates transitive dependencies to ensure non-key attributes depend only on the primary key . This process optimizes storage space and improves data integrity by maintaining consistency across the database.

SQL views offer benefits like abstraction and security by allowing users to interact with data without accessing underlying tables directly . They can simplify complex queries by encapsulating them in a single view, which improves usability and reduces errors . Views can also restrict access to specific data, providing a layer of security by exposing only relevant information . However, views can add complexity to database management, as updating views requires consideration of the underlying changes in tables . Additionally, while views improve security by limiting data exposure, they do not inherently protect data from unauthorized access.

You might also like