0% found this document useful (0 votes)
52 views26 pages

SQL Unleashed Part1 Part2 1701889964

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)
52 views26 pages

SQL Unleashed Part1 Part2 1701889964

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/ 26

By - Aastha Agarwal

LinkedIn - https://www.linkedin.com/in/aasthaa1jan/

TOPIC - SQL

Part 1 --> DATABASE BASICS


Data is a new fuel!!!
The revolutions

Computer
Internet
AI

In all these revolutions DATA is common!!

WHAT IS A DATABASE??
Share collection of logicallyy related data description of these data, designed to meet the
information needs of an organization.

1. Data Storage: A Database is used to store large amounts of structured data, making
it easily accessible, searchable, & retrievable.
2. Data Analysis: A Database can be used to perform complex data analysus, generate
reports, & provide insights into the data.
3. Record Keeping: A Database is often used to keep track of important records, such
as financial transactions, customer information, & inventory levels.
4. Web Applications: Databases are an essential component of many web
applications, providing dynamic content & user management.

CRUD
Create
Retreate
Update
Delete

Properties of an ideal Database...


1. Integrity -> Accuracy + Consistency
2. Availability -> 24*7
3. Security
4. Independent of Application -> Multiple Aplications must have same database
5. Concurrency -> Parallel Tasks must run smoothly

Types of Databases
1. Relational Databases: Also known as SQL databases, these databases use a
relational model to organize data into tables with rows & columns.

2. NoSQL Databases: These Databases are designed to handle large amount of


unstructured or semi-structured data, such as documents, images or videos.
(MongoDB)

3. Column Databases: These databses store data in columns rather than in rows,
making them well suited for data warehousing & analytical applications. (Amazon
Redshift, Google BigQuery)

4. Graph Databases: These databases store & query graph-structured, such as social
network connections or recommendation systems.

5. Key Value Database: These databases store data as a collection of key-value


pair, making them well-suited for caching and simple data storage needs (Redis &
Amazon DynamicDB)

Relational Databases
1. Tabular Data
2. Columns -> Attributes -> Fields
3. Rows -> Tuples -> Records
4. Cardinality of the relation -> No. of records / rows / tuples
5. Degree of the relationn -> No. of attributes / columns / fields
DATABASE MANAGEMENT SYSTEM
DBMS is a software system that provides the interfaces and tools needed to store,
organize, & manage data in the database.

It acts as an intermediary between the database and applications or users that


access the data stored in the datases
Functions of DBMS
1. Data Management Store, Retrieve, Modify data
2. Integrity Maintain accuracy of data
3. Concurrency Simultaneous data access for multiple users
4. Transaction Modification to database must either be successfull or must not happen
at all
5. Security Access to authorized users only
6. Utilities Data Import/Export, user management, backup, logging

DATABASE KEYS
Let's consider a database table for student information with the following columns:

1. Roll No (Primary Key):

This column uniquely identifies each student in the table. It ensures that each
student has a unique identifier, and no two students can have the same roll
number. The primary key is essential for data integrity and to establish
relationships with other tables.
2. Name:

This column stores the name of the student. It does not need to be unique, as
different students can have the same name.
3. Branch:

This column represents the branch or major in which the student is enrolled
(e.g., Computer Science, Mechanical Engineering, etc.). The branch information
can be duplicated because multiple students can belong to the same branch.
4. Email (Unique Key):

This column contains the email address of the student. While not every student
may have an email address, for those who do, it's assumed to be unique. Using
a unique key constraint on the email column ensures that each email address is
unique across all records in the table.

Here's an example of how you might fill the table with random data:

Roll No Name Branch Email

101 John Doe Computer Science [email protected]

102 Jane Smith Mechanical Engineering [email protected]

103 Bob Johnson Electrical Engineering [email protected]

104 Alice Brown Computer Science [email protected]

105 Charlie White Civil Engineering [email protected]

Explanation of Keys:

Primary Key (Roll No):

The "Roll No" column serves as the primary key for the table. It uniquely
identifies each student, and no two students can have the same roll number.
The primary key is crucial for establishing relationships with other tables,
ensuring data integrity, and enabling efficient data retrieval.
Unique Key (Email):

The "Email" column is marked as a unique key. This ensures that each email
address in the table is unique. While not every student may have an email
address, for those who do, the email must be unique to avoid duplication.
Unique keys help maintain data integrity by preventing duplicate entries in the
specified column.

These key constraints (primary key and unique key) play a vital role in maintaining the
consistency and uniqueness of data in the database table.

Types of Keys in DBMS


1. Primary Key:
Uniquely identifies each record in a table.
Ensures data integrity and acts as a reference in other tables.
Only one primary key per ta

ble.

2. Foreign Key:
Establishes relationships between tables.
Refers to the primary key in another table.
Maintains referential i

ntegrity.

3. Unique Key:
Ensures the uniqueness of values in a column or set of columns.
Allows NULL values (unless specified otherwise).
A table can have multipl

e unique keys.

4. Composite Key:
Consists of multiple columns that, together, uniquely identify a record.
Each individual column in the composite key

may not be unique.

5. Candidate Key:

A set of columns that could uniquely identify a record.


The actual primary key is chosen from the candidate keys.
Provides flexibility in se
6. . Super Key:

A set of one or more columns that, taken together, can uniquely identify a
record in a table.
It may include more columns than necessary for uniquely identifying a record.
A super key can have redundant or extra attributes beyond what is required for
unique
7. Surrogate Key:

A surrogate key is an artificially generated key used as the primary key for a
table.
It is typically a numeric or alphanumeric identifier assigned to each record.
Surrogate keys have no inherent meaning and are used purely for the purpose
of uniquely identifying records.
Commonly used when a natural key is impractical or when a stable, unchanging
identifier is needed. is needed.te and maintainable data.

CARDINALITY OF RELATIONSHIPS
Cardinality in Database relationships refers to the number of occurances of an entity
in a relationship with another entity.
It defines the number of instances of ana entity that can be associated with the
single instance of the related entity.

Types:
1. One-to-One (1:1) Cardinality:

Definition: Each record in the first table is related to only one record in the
second table, and vice versa.
Example: A relationship where each person has only one passport, and each
passport is issued to only one person.
2. One-to-Many (1:N) Cardinality:

Definition: Each record in the first table can be related to multiple records in
the second table, but each record in the second table is related to only one
record in the first table.
Example: A relationship where one customer can place multiple orders, but
each order is associated with only one customer.
3. Many-to-Many (M:N) Cardinality:

Definition: Each record in the first table can be related to multiple records in
the second table, and vice versa.
Example: A relationship where students can enroll in multiple courses, and each
course can have multiple students.

Examples

A. One-to-One (1:1) Cardinality:


1. Example: Employee and EmployeeID Card
Each employee has only one employee ID card.
Each employee ID card is issued to only one employee.

B. One-to-Many (1:N) Cardinality:


1. Example: Author and Books

An author can write multiple books.


Each book is written by only one author.
2. Example: Department and Employees

A department can have multiple employees.


Each employee works in only one department.

C. Many-to-Many (M:N) Cardinality:


1. Example: Students and Courses

A student can enroll in multiple courses.


Each course can have multiple students.
2. Example: Actors and Movies

An actor can act in multiple movies.


Each movie can have multiple actors.

DRAWBACKS OF DATABASES
1. Complexity:

Description: Database systems can be complex to design, implement, and


maintain. Creating a well-structured database requires understanding the data
model, relationships, and optimizing queries.
Implications: Complexity can lead to errors in database design, making it
harder to manage and potentially impacting performance.
2. Cost:

Description: Establishing and maintaining a database system can be expensive.


Costs include software licenses, hardware, skilled personnel, ongoing
maintenance, and training.
Implications: High costs may be a barrier for smaller organizations or projects
with limited budgets.
3. Scalability:

Description: Scaling a database to handle increasing amounts of data or users


may be challenging. Some databases may face performance issues as data
volume grows.
Implications: Inadequate scalability can result in decreased performance and
may necessitate redesigning the database architecture.
4. Data Integrity:

Description: Ensuring data integrity, accuracy, and consistency can be


challenging. Updates, deletions, or additions to data must be carefully managed
to prevent inconsistencies.
Implications: Data integrity issues can lead to incorrect information, impacting
decision-making and application functionality.
5. Security:

Description: Databases are susceptible to security threats such as unauthorized


access, data breaches, and SQL injection attacks. Implementing robust security
measures is essential.
Implications: Security breaches can compromise sensitive information,
resulting in legal consequences, financial losses, and damage to an
organization's reputation.
6. Data Migration:
Description: Moving data between different databases or systems can be
complex and may result in data loss, format mismatches, or compatibility issues.
Implications: Data migration challenges can lead to disruptions, increased
downtime, and potential loss of important information during the transition.
7. Flexibility:

Description: Some databases may lack flexibility in accommodating changes to


the data model or structure. Altering the database schema may be difficult,
especially in production environments.
Implications: Lack of flexibility can hinder adaptability to evolving business
requirements, making it challenging to incorporate changes.
By - Aastha Agarwal

LinkedIn - https://www.linkedin.com/in/aasthaa1jan/

Part 2 --> SQL BASICS & DDL


COMMANDS
For this module we'll be using Apache Xampp. Make sure you download the software
before starting this module.

Once you have downloaded the Software

Open Xampp control panel.


Start Apache & MySQL Modules..

After that open this url - http://localhost/phpmyadmin/

SQL
SQL is a programming language used for managing and manipulating data in
relational databases.
It allows you to insert, update, retrieve and delete data in a database.
It is widely used for data management in many applications, websites and
businesses.
In simple terms, it is used to communicate with and control databases.

Types of SQL Commands


Data Query Language (DQL)
1. SELECT Statement:
Used for retrieving data from one or more tables.
Syntax: SELECT column1, column2, ... FROM table WHERE condition;
Examples: SELECT * FROM Employees; , SELECT FirstName, LastName
FROM Customers WHERE Country = 'USA';

Data Definition Language (DDL)


1. CREATE Statement:

Used to create database objects such as tables, indexes, or views.


Syntax: CREATE TABLE table_name (column1 datatype, column2
datatype, ...);
Example: CREATE TABLE Students (StudentID INT, FirstName
VARCHAR(50), LastName VARCHAR(50));
2. ALTER Statement:

Modifies the structure of an existing database object (e.g., table).


Syntax: ALTER TABLE table_name ADD COLUMN column_name datatype;
Example: ALTER TABLE Students ADD COLUMN Age INT;
3. DROP Statement:

Deletes an existing database object (e.g., table, index).


Syntax: DROP TABLE table_name;
Example: DROP TABLE Students;
4. TRUNCATE Statement:

Removes all records from a table but retains the table structure for reuse.
Syntax: TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE Students;

UNDERSTANDING CREATE & DROP


STATEMENTS
CREATING A DATABASE student
A BETTER WAY OF CREATING A DATABASE student

DELETING A DATABASE student


A BETTER WAY OF DELETING A DATABASE student

CREATING sample DATABASE

Command 1 -> CREATE DATABASE IF NOT EXISTS sample

Creating a table users into sample database

Command 2 -> CREATE TABLE users( user_id INTEGER, name VARCHAR(255),


email VARCHAR(255), password VARCHAR(255));

UNDERSTANDING TRUNCATE STATEMENTS


For this we first need to create a table. We'll be continuing with our sample database
where we created a basic table structure having four headers i.e user_id , name ,
email & password .

Let's first learn to insert the data into the table users

Inserting Tuple 1 -
Resulting table with Tuple 1 -

Inserting Tuple 2 -
Resulting table -

Truncating table users -

Let's try truncate command on the table users

After Truncating the table users -


Observe That on Truncating the data inside the table users is deleted but the
structure of the table is still there.

Dropping table users -

Result After Dropping the table users -

Observe That on Dropping the table users , the structure of the table is deleted i.e
existence of the table users has been deleted.
DATA INTEGRITY:
Data integrity refers to the accuracy, consistency, and reliability of data in a database. It
ensures that data remains correct and valid throughout its lifecycle, from creation to
modification and deletion. Maintaining data integrity is crucial for reliable decision-
making, and it is enforced through various mechanisms in a relational database system.

Methods to Ensure Data Integrity:

1. Constraints:

Contraints in databases are the rules or conditions that must be met for data to be
inserted, updated, or deleted in a database table. They are used to enforce the integrity
of the data stored in a database & to prevent data from becoming inconsistent or
corrupted .

2. Transactions:

A sequence of database operations that are treated as a single unit of work.

Atomicity:
Ensures that a transaction is treated as a single, indivisible unit. If any part of the
transaction fails, the entire transaction is rolled back to its previous state.
Consistency:
Ensures that a transaction brings the database from one valid state to another,
maintaining integrity constraints.
Isolation:
Ensures that multiple transactions can occur concurrently without interfering
with each other.
Durability:
Ensures that once a transaction is committed, its changes are permanent and
survive system failures.

3. Normalizations:

A design technique that minimizes data redundancy & ensures data consistency by
organizing data into seperate tables.

First Normal Form (1NF):


Ensures that each column in a table contains atomic (indivisible) values, and
there are no repeating groups.
Second Normal Form (2NF):
Ensures that the table is in 1NF and every non-key column is fully functionally
dependent on the entire primary key.
Third Normal Form (3NF):
Ensures that the table is in 2NF and eliminates transitive dependencies. Non-key
columns are not dependent on other non-key columns.
Donot get overwhelmed with the theory above. We'll cover everything in the coming
modules..

CONSTRAINTS IN MYSQL
In MySQL, constraints are rules that you can apply to columns in a table to enforce data
integrity. Constraints help ensure that the data stored in the database follows specific
rules, preventing inconsistencies or errors. Here are some common constraints in MySQL:

1. Primary Key Constraint:

Ensures that each record in a table has a unique identifier.


Used when the values in the columns should be Not Null and must be Unique.
Syntax example:
CREATE TABLE example (
id INT PRIMARY KEY,
name VARCHAR(50)
);
2. Unique Constraint:

Ensures that values in a specific column or a combination of columns are


unique.
Syntax example:
CREATE TABLE example (
email VARCHAR(100) UNIQUE,
phone_number VARCHAR(20) UNIQUE
);
3. Foreign Key Constraint:

Maintains referential integrity by linking a column to the primary key of another


table.
Syntax example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
4. Check Constraint:

Defines a condition that must be true for data to be inserted or updated.


Syntax example:
CREATE TABLE example (
age INT CHECK (age >= 18),
salary DECIMAL(10, 2) CHECK (salary > 0)
);
5. Default Constraint:

Specifies a default value for a column, used if no value is provided during an


insert.
Syntax example:
CREATE TABLE example (
status VARCHAR(20) DEFAULT 'Active',
registration_date DATE DEFAULT CURRENT_DATE
);
6. Not Null Constraint:

Ensures that a column cannot have a NULL value.


Used when the information is really important
Syntax example:
CREATE TABLE example (
username VARCHAR(50) NOT NULL,
age INT NOT NULL
);
7. Primary Key Constraint with AUTO_INCREMENT:

Ensures that each record in a table has a unique identifier, automatically


incremented for each new record.
Syntax example:
CREATE TABLE example (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50)
);

These constraints play a crucial role in defining the structure of your database and
maintaining the integrity of your data. They help prevent issues such as duplicate
records, inconsistent relationships, and data that doesn't adhere to specified rules.

REFERENTIAL ACTIONS IN MYSQL


Referential actions in the context of a relational database are actions that can be
automatically triggered when a referenced (foreign key) record in a table is modified or
deleted. These actions help maintain referential integrity between tables. In MySQL, there
are different referential actions that you can specify when defining foreign keys. Here are
the common referential actions:

1. CASCADE:

When a referenced record (parent) is modified or deleted, the corresponding


records in the child table are also modified or deleted automatically.
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON
UPDATE CASCADE ON DELETE CASCADE
);
2. SET NULL:
When a referenced record (parent) is modified, the corresponding foreign key
values in the child table are set to NULL. If the referenced record is deleted, the
foreign key values are set to NULL as well.
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON
UPDATE SET NULL ON DELETE SET NULL
);
3. SET DEFAULT:

Similar to SET NULL, but the foreign key values are set to their default values
instead of NULL.
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT DEFAULT 0,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON
UPDATE SET DEFAULT ON DELETE SET DEFAULT
);
4. RESTRICT:

Prevents the modification or deletion of a referenced record if there are


dependent records in the child table.
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON
UPDATE RESTRICT ON DELETE RESTRICT
);
5. NO ACTION:

Similar to RESTRICT, where the modification or deletion is restricted if there are


dependent records.
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON
UPDATE NO ACTION ON DELETE NO ACTION
);

These referential actions help you define the behavior of the database when changes
occur in the referenced tables, ensuring that relationships between tables remain
consistent and maintain integrity.

DATATYPES IN MYSQL
MySQL supports various data types that allow you to store different kinds of data in your
database tables. Here are some common data types in MySQL:

Numeric Types:
1. INTEGER or INT:

Whole numbers without decimal points.


Example: INT
2. TINYINT:

Small integers.
Example: TINYINT
3. SMALLINT:

Medium-sized integers.
Example: SMALLINT
4. MEDIUMINT:

A medium-sized integer.
Example: MEDIUMINT
5. BIGINT:

Large integers.
Example: BIGINT
6. FLOAT:

Single-precision floating-point numbers.


Example: FLOAT
7. DOUBLE:

Double-precision floating-point numbers.


Example: DOUBLE
8. DECIMAL or NUMERIC:

Fixed-point numbers.
Example: DECIMAL(10,2)

String Types:
9. CHAR:

Fixed-length character strings.


Example: CHAR(50)
10. VARCHAR:

Variable-length character strings.


Example: VARCHAR(255)
11. TEXT:
Variable-length text strings.
Example: TEXT

Date and Time Types:


12. DATE:

Date values in 'YYYY-MM-DD' format.


Example: DATE
13. TIME:

Time values in 'HH:MM:SS' format.


Example: TIME
14. DATETIME:

Date and time values in 'YYYY-MM-DD HH:MM:SS' format.


Example: DATETIME
15. TIMESTAMP:

Similar to DATETIME but with a narrower range.


Example: TIMESTAMP
16. YEAR:

Four-digit year values.


Example: YEAR(4)

Other Types:
17. BOOLEAN or BOOL:

Synonyms for TINYINT(1).


Example: BOOLEAN
18. ENUM:

Enumeration, a string object with a value chosen from a predefined list of


values.
Example: ENUM('Red', 'Green', 'Blue')
19. SET:

Similar to ENUM, but can have multiple values chosen from a predefined list.
Example: SET('Option1', 'Option2', 'Option3')

Binary Types:
20. BINARY:

Fixed-length binary strings.


Example: BINARY(10)
21. VARBINARY:
Variable-length binary strings.
Example: VARBINARY(255)
22. BLOB:

Binary large objects for storing large binary data.


Example: BLOB

These are some of the common data types in MySQL. The choice of data type depends
on the nature of the data you are storing and the operations you intend to perform on
that data.

EXAMPLE ILLUSTRATING CONSTRAINTS


& DATATYPES
Certainly! Let's create a comprehensive example that includes various constraints,
including PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, DEFAULT, NOT NULL, and
AUTO_INCREMENT.

-- Create a table for customers


CREATE TABLE customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone_number VARCHAR(20) UNIQUE,
birth_date DATE CHECK (birth_date >= '1900-01-01'),
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create a table for orders


CREATE TABLE orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
order_date DATE DEFAULT CURRENT_DATE,
total_amount DECIMAL(10, 2) CHECK (total_amount >= 0),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON UPDATE
CASCADE ON DELETE SET NULL
);

-- Create a table for order items


CREATE TABLE order_items (
item_id INT PRIMARY KEY AUTO_INCREMENT,
order_id INT,
product_name VARCHAR(100) NOT NULL,
quantity INT CHECK (quantity > 0),
price DECIMAL(8, 2) CHECK (price >= 0),
FOREIGN KEY (order_id) REFERENCES orders(order_id) ON UPDATE CASCADE
ON DELETE CASCADE
);
Explanation of the example:
The customers table includes a PRIMARY KEY constraint on customer_id ,
UNIQUE constraints on email and phone_number , a CHECK constraint on
birth_date to ensure it's not before 1900-01-01, and a DEFAULT constraint on
registration_date to set it to the current timestamp.

The orders table includes a PRIMARY KEY constraint on order_id , a FOREIGN


KEY constraint on customer_id referencing the customers table with ON
UPDATE CASCADE and ON DELETE SET NULL actions, a DEFAULT constraint on
order_date to set it to the current date, and a CHECK constraint on
total_amount to ensure it's not negative.

The order_items table includes a PRIMARY KEY constraint on item_id , a


FOREIGN KEY constraint on order_id referencing the orders table with ON
UPDATE CASCADE and ON DELETE CASCADE actions, and CHECK constraints on
quantity and price to ensure they are greater than 0 and not negative,
respectively.

This example demonstrates how to use various constraints to ensure data integrity in a
relational database.

UNDERSTANDING ALTER TABLE STATEMENTS


The ALTER TABLE command in MySQL is used to modify an existing table structure.
You can use this command to add, modify, or drop columns, change data types, set
constraints, and perform other table-related operations.

Things that can be done using ALTER TABLE statement include

1. Add Columns
2. Delete Columns
3. Modify Columns

Here are some common use cases of the ALTER TABLE command:

Adding a Column:
ALTER TABLE table_name
ADD COLUMN new_column_name INT;

Modifying a Column:
ALTER TABLE table_name
MODIFY COLUMN existing_column_name VARCHAR(50);

Changing Data Type of a Column:


ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name VARCHAR(100);
Dropping a Column:
ALTER TABLE table_name
DROP COLUMN column_to_be_dropped;

Adding a Primary Key:


ALTER TABLE table_name
ADD PRIMARY KEY (column1, column2);

Adding a Foreign Key:


ALTER TABLE child_table
ADD FOREIGN KEY (column_name) REFERENCES parent_table(parent_column);

Adding an Index:
ALTER TABLE table_name
ADD INDEX index_name (column1, column2);

Renaming a Table:
ALTER TABLE old_table_name
RENAME TO new_table_name;

Adding a Unique Constraint:


Not possible in MySQL , we need to delete the constraint first and re-add it again. But
this can be done in other softwares.

ALTER TABLE table_name


ADD CONSTRAINT unique_constraint_name UNIQUE (column1, column2);

Changing the Auto-Increment Value:


ALTER TABLE table_name
AUTO_INCREMENT = 100;
These are just a few examples of what you can do with the ALTER TABLE command.
The specific syntax and options may vary depending on the modification you want to
make. Always ensure that you have a backup of your data before performing significant
alterations to a table.

You might also like