SQL Basics and Key Concepts Explained
SQL Basics and Key Concepts Explained
com/sql-nosql
What is SQL?
Database
Table
Record
Column
1 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance
• SELECTEdit
Add new
- this
extracts
post
data from a database Nitesh Synergy
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
2 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
• Example:
sql
• Example:
sql
• Example:
sql
• Example:
sql
3 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
• Example:
sql
• Example:
sql
• Example:
sql
sql
sql
4 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
• Example:
sql
Summary
5 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
For Oracle (which does not support LIMIT and OFFSET, but
uses ROWNUM or FETCH):
SELECT * FROM (
SELECT * FROM Products
ORDER BY ProductID
)
WHERE ROWNUM = n;
SELECT * FROM (
SELECT * FROM Products
ORDER BY ProductID DESC
)
WHERE ROWNUM = n;
FETCH FIRST
SELECT * FROM Customers
6 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
→
SQL Sub Languages in every
database
1. Data Definition Language (DDL)
DDL is used to define and manage database structures such as
tables, schemas, and indexes. These commands modify the
structure of the database.
7 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
INSERT INTO employees (id, name, age) VALUES (1, 'John Doe',
30);
8 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
COMMIT;
ROLLBACK;
SAVEPOINT savepoint_name;
9 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
1. Atomicity (ROLLBACK)
• Definition: A transaction is treated as a single
unit, which either fully succeeds or fully fails.
If a transaction fails at any point, all changes
made during the transaction are rolled back,
ensuring the database remains in a consistent
state.
2. Consistency
• Definition: A transaction brings the database from
one valid state to another, ensuring that the
database constraints, rules, and integrity are
maintained before and after the transaction.
• Use Case: E-Commerce Inventory Management
◦ When a customer places an order on an e-
commerce platform, the system must ensure that
the quantity of the item purchased is updated
correctly in the database.
◦ Example: If a customer buys the last 3 units of
a product, the system checks that the inventory
count is updated to reflect this after the
10 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
3. Isolation
• Definition: Transactions are executed in isolation
from one another, meaning the intermediate state
of one transaction is not visible to other
transactions. This ensures that transactions do
not interfere with each other.
• Use Case: Online Reservation System
◦ When two users are booking the last available
seat on a flight, the system ensures that they
do not both "see" the seat as available at the
same time.
◦ Example: User 1 begins the booking process, and
before the transaction is complete, User 2
tries to book the same seat. The system
isolates the two transactions to ensure that
only one user can successfully complete the
booking while the other will receive an error
stating that the seat is no longer available.
4. Durability (COMMIT)
• Definition: Once a transaction has been committed,
the changes are permanent, even in the event of a
system crash. The database ensures that all
changes made by the transaction are saved and will
persist.
• Use Case: Order Processing System
◦ Once a customer places an order, the system
confirms the order and records it in the
database. After the order is confirmed, no
matter what happens (e.g., power failure), the
order data is saved.
◦ Example: A customer successfully places an
order for a product, and the system commits the
transaction. If the server crashes immediately
afterward, the order is still intact and
retrievable when the system comes back online.
In summary:
11 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
import [Link];
import
[Link];
@Service
public class BankService {
@Transactional
public void transferFunds(Long senderId, Long receiverId,
double amount) {
// Deduct from sender's account
Account sender =
[Link](senderId).orElseThrow(() -> new
RuntimeException("Sender not found"));
[Link]([Link]() - amount);
[Link](sender);
2. Consistency
12 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
import [Link];
import
[Link];
@Service
public class InventoryService {
public InventoryService(ProductRepository
productRepository) {
[Link] = productRepository;
}
@Transactional
public void purchaseProduct(Long productId, int quantity)
{
Product product =
[Link](productId)
.orElseThrow(() -> new
RuntimeException("Product not found"));
[Link]([Link]() - quantity);
[Link](product);
}
}
3. Isolation
Isolation ensures that one transaction is not affected by
another transaction, which is critical in multi-user
environments.
@Service
public class ReservationService {
13 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
@Transactional
public void bookSeat(Long seatId, Long customerId) {
// Fetch seat and customer details
Seat seat =
[Link](seatId);
if ([Link]()) {
throw new RuntimeException("Seat is already
booked");
}
[Link](true);
[Link](seat);
4. Durability (COMMIT)
Once a transaction is committed, it should be saved
permanently in the database even if the system crashes
afterward.
import [Link];
import
[Link];
@Service
public class OrderService {
@Transactional
public void placeOrder(Long customerId, List<Long>
productIds) {
14 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
[Link](order);
Key Notes:
• Atomicity is achieved by ensuring the transaction
is all or nothing.
• Consistency ensures the database's rules and
integrity are respected.
• Isolation is managed through transactions to avoid
conflicts between concurrent transactions.
• Durability ensures that once committed, the data
persists even after crashes, which can be
implemented by using JPA or Spring Data
repositories.
Common ones:
15 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Syntax:
SELECT
MIN(col), MAX(col), COUNT(*), SUM(num_col), AVG(num_col)
FROM table_name;
Eg-
Facebook-style use case:
– Count posts per user:
2. GROUP BY
Concept:
Syntax:
SELECT col1, col2, AGG(col3)
FROM table
GROUP BY col1, col2;
3. HAVING
Concept:
Syntax:
SELECT col, AGG(col2)
FROM table
GROUP BY col
HAVING AGG(col2) > value;
16 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
1. SQL JOINs
Appearance Add new Edit this post Nitesh Synergy
Concept (Point by Point)
Combines rows from two or more tables based on related
columns.
Types of JOIN:
Syntax
SELECT a.column1, b.column2
FROM table1 a
JOIN table2 b ON a.common_column = b.common_column;
eg-
-- Tables
Users(user_id, name)
Posts(post_id, user_id, content)
eg-Fetch all comments along with the user names who posted
them.
2. SQL GROUP BY
Concept (Point by Point)
Aggregates data based on one or more columns.
Syntax:
SELECT column, COUNT(*)
FROM table
GROUP BY column;
17 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
3. SQL INDEX
Concept (Point by Point)
Improves query performance (esp. SELECT).
🧪 Syntax
-- Create index
CREATE INDEX idx_user_name ON Users(name);
-- Drop index
DROP INDEX idx_user_name;
eg-
-- Index on email to speed up login lookup
CREATE INDEX idx_user_email ON Users(email);
1⃣ WHERE vs HAVING
🔹 WHERE: filters rows before aggregation
🔹 HAVING: filters groups after GROUP BY
📌 Use Case: Show only users who made more than 5 posts.
18 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
2⃣ Subqueries
Appearance Add new Edit this post Nitesh Synergy
🔹 Query inside another query
🔹 Can be used in SELECT, WHERE, or FROM
🔹 Types: scalar, correlated, nested
3⃣ Window Functions
🔹 Perform ranking, running totals, etc.
🔹 Do not collapse rows like GROUP BY
📌 Use Case: Get latest post per user (or Nth salary-type
problems)
5⃣ CASE WHEN
🔹 Conditional logic in SQL
🔹 Like if-else
SELECT name,
CASE
WHEN gender = 'M' THEN 'Male'
WHEN gender = 'F' THEN 'Female'
ELSE 'Other'
END AS gender_text
FROM Users;
6⃣ Views
🔹 Saved SQL query (virtual table)
19 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
WITH PostCounts AS (
SELECT user_id, COUNT(*) AS total_posts
FROM Posts GROUP BY user_id
)
SELECT [Link], pc.total_posts
FROM Users u
JOIN PostCounts pc ON u.user_id = pc.user_id;
8⃣ Constraints
🔹 Enforce rules at DB level
🔹 Types:
SQL Assignment
Visit:→ [Link]
main/sqlpractice
Follow
📘 Section-wise Breakdown
(with ~1000 practice
questions)
No.
Level Focus Area of Example
Qs
20 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
SELECT * FROM
SELECT, WHERE,
users WHERE
✅ Beginner ORDER, LIMIT, 100
full_name LIKE
LIKE
'A%';
JOINs,
Get users with
✅ Aggregates,
150 more than 5
Intermediate GROUP BY,
posts.
HAVING
Add a trigger
CREATE, ALTER,
✅ Admin/DDL 100 to log deleted
DROP, TRIGGERS
comments.
COMMIT,
Simulate
✅ ROLLBACK,
50 transfer
Transactions Isolation
between users.
Levels
Fetch posts
JSON fields,
with images
✅ JSON/Date time-based 50
added in last
logic
30 days.
21 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Donate Now
MongoDB
1. Document-Oriented Storage
• MongoDB stores data as documents within
collections, with each document containing key-
value pairs (like JSON objects). This model is
highly flexible and can accommodate a variety of
data types without a fixed schema.
2. Schema-Less Design
• MongoDB doesn’t require a predefined schema. This
means you can store different fields in each
document of a collection, allowing for more
flexible data structures. This is especially
useful for applications that need to evolve over
time or store unstructured data.
4. Indexing
• MongoDB allows indexing on any field in a
document, which significantly improves the
22 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
6. Horizontal Scalability
• MongoDB supports sharding, which allows data to be
distributed across multiple servers. This enables
horizontal scaling to handle large datasets and
high-throughput applications without compromising
performance.
8. High Performance
• MongoDB is optimized for high performance,
supporting fast reads and writes. It can handle
large volumes of data and scale efficiently across
multiple machines, making it ideal for high-
traffic applications.
23 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance
• MongoDB
Add new
is relatively easy to administer,
Edit this post Nitesh Synergy
especially in case of failures. With its built-in
replication and automatic failover mechanisms,
database administrators can manage MongoDB without
worrying about complex recovery processes.
24 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
NoSQL Database
NoSQL Database is used to refer a non-SQL or non relational database.
It provides a mechanism for storage and retrieval of data other than tabular
relations model used in relational databases. NoSQL database doesn't use tables
for storing data. It is generally used to store big data and real-time web
applications.
Advantages of NoSQL
◦ It supports query language.
1. String
• Concept: Strings in MongoDB are used to store
text. They are UTF-8 encoded.
• Use Case: Storing names, addresses, or other
textual information.
• Real-Time Example: In a blogging application,
storing the title or body of a blog post.
Code Snippet:
25 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
2. Integer
• Concept: Integer values are used to store whole
numbers (positive or negative). MongoDB uses 32-
bit or 64-bit integers based on the value range.
• Use Case: Storing age, quantity, or other numeric
values.
• Real-Time Example: In an e-commerce platform,
storing the number of products in stock.
Code Snippet:
[Link]({
name: "Laptop",
stock: 50
});
3. Boolean
• Concept: Booleans represent a true/false value.
• Use Case: To flag or mark statuses like whether an
account is active or whether a task is completed.
• Real-Time Example: In a task management
application, marking whether a task is completed.
Code Snippet:
[Link]({
task: "Complete MongoDB tutorial",
completed: false
});
4. Date
• Concept: The Data type is used to store date and
time in ISODate format.
• Use Case: Storing timestamps for records such as
user registration, login times, or order dates.
• Real-Time Example: Storing the date of an order
placed in an online shopping platform.
Code Snippet:
26 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
5. ObjectId
• Concept: MongoDB automatically generates a unique
identifier for each document, which is of type
ObjectId. It is a 12-byte identifier.
• Use Case: Unique identification for each document
in a collection. Primarily used for primary keys.
• Real-Time Example: Identifying each user in a user
management system.
Code Snippet:
6. Array
• Concept: Arrays are used to store multiple values
within a single field. MongoDB arrays can store
different data types, such as strings, integers,
and even objects.
• Use Case: Storing multiple values like a list of
tags, categories, or items in an order.
• Real-Time Example: In an e-commerce application,
storing a list of product tags (e.g., size, color,
material).
Code Snippet:
[Link]({
name: "T-shirt",
tags: ["cotton", "red", "medium"]
});
27 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Code Snippet:
[Link]({
name: "Jane Smith",
address: {
street: "123 Elm St",
city: "Springfield",
postalCode: "12345"
}
});
8. Null
• Concept: The Null type is used to represent a null
or missing value.
• Use Case: Representing data that is missing,
unknown, or explicitly set to null.
• Real-Time Example: In a product catalog, setting
the "discounted price" to null for products that
aren't on sale.
Code Snippet:
[Link]({
name: "Smartphone",
discountedPrice: null
});
9. Binary Data
• Concept: MongoDB supports binary data for storing
files, images, or any other binary objects.
• Use Case: Storing user profile pictures or
document attachments.
• Real-Time Example: Storing an image file uploaded
by a user in a photo-sharing application.
Code Snippet:
28 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
10. Decimal128
• Concept: This is a high-precision decimal type
used to store precise floating-point values.
• Use Case: Storing financial data, currency values,
or other data that requires high precision.
• Real-Time Example: Storing the price of a product
in an e-commerce application.
Code Snippet:
11. Timestamp
• Concept: This data type is used to store a 64-bit
value representing the timestamp of an event.
• Use Case: Storing event timestamps such as when a
document was created or updated.
• Real-Time Example: Tracking the last login
timestamp for a user.
Code Snippet:
[Link]({
name: "Alice",
lastLogin: new Timestamp()
});
___________________________________________________________________________________
🖥 3. Install
29 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance
MongoDB on Your
Add new Edit this post Nitesh Synergy
Machine
✅ Option A: Local Installation
Step-by-step:
1. Go to [Link]
community
2. Download MongoDB Community Edition
3. Install using default settings.
4. Also download MongoDB Compass (GUI for MongoDB).
To test:
In a new terminal:
bash
mongo # opens the shell (MongoDB CLI)
✅ 4. First MongoDB
Commands (Try in
shell or Compass)
📂 Create a database and collection
✅ 4. First MongoDB
30 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance
Commands (Try in
Add new Edit this post Nitesh Synergy
shell or Compass)
📂 Create a database and collection
➕ Insert a document
[Link]({
_id: "u101",
name: "Nitesh",
age: 29,
country: "India"
})
🔍 View documents
[Link]().pretty()
🧪 Quick Practice
Quiz
1. What does MongoDB use instead of tables?
2. What format are documents stored in MongoDB?
3. How do you insert a document in MongoDB shell?
4. What is MongoDB Compass used for?
✅ Assignment for
Today
1. Install MongoDB + Compass (or setup Atlas)
2. Create a DB named practiceDB
3. Create a collection students
4. Insert 3 student documents:
{
"rollNo": 1,
"name": "Amit",
"marks": 75
}
31 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
🎯 Learning Goals:
• Learn how to Create, Read, Update, and Delete
documents using MongoDB shell or Compass.
📘 MongoDB CRUD
Breakdown
📥 1. Create
// Insert one document
[Link]({
rollNo: 1,
name: "Amit",
marks: 75
})
🔍 2. Read
// Find all documents
[Link]()
// Pretty print
[Link]().pretty()
// Find one
[Link]({ rollNo: 2 })
✏ 3. Update
// Update one document
[Link](
{ rollNo: 2 },
{ $set: { marks: 90 } }
)
32 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
)
Appearance Add new Edit this post Nitesh Synergy
❌ 4. Delete
// Delete one document
[Link]({ rollNo: 3 })
🛠 Hands-On Exercise
Try these steps in MongoDB shell or Compass:
use practiceDB
🎯 Learning Goals:
• Use MongoDB operators to filter, search, and
query data.
• Understand how conditions like $gt , $lt , $in ,
$and , and $or work.
📘 Basic MongoDB
Query Operators
Assume your collection has these student documents:
33 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance 🔍 Comparison
Add new Edit this post Operators Nitesh Synergy
Greater than or
$gte { marks: { $gte: 88 } }
equal
Less than or
$lte { marks: { $lte: 75 } }
equal
🧠 Logical Operators
34 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance ⛓ Nested
Add new Edit thisFields
post & Arrays Nitesh Synergy
{
"rollNo": 5,
"name": "Anjali",
"marks": 85,
"skills": ["Java", "MongoDB", "Spring Boot"]
}
✅ Module 4:
MongoDB Data
Modeling
(Embedded Documents, Referencing, and
Schema Design)
🎯 Learning Goals:
• Understand how to structure MongoDB collections
using:
◦ Embedded documents
◦ Referenced documents
• Design optimal schemas for real-world use cases
(e.g., e-commerce, billing, etc.)
📘 1. Embedded
Documents
Embed when you have one-to-few relationships or data
that's always read together.
35 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
✅ Pros:
• Fewer joins
• Faster read for nested data
❌ Cons:
• Redundant if reused across documents
• Not ideal for one-to-many (e.g., hundreds of
comments)
📘 2. Referenced
Documents
Reference when you have one-to-many or many-to-many
relationships.
customers collection
{
"_id": "cust101",
"name": "Amit Kumar"
}
orders collection
{
"_id": "order789",
"custId": "cust101",
"amount": 450.0,
"items": ["item1", "item2"]
}
36 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
📌 3. Data Modeling
Guidelines
Case Best Approach
🎯 Learning Goals:
• Understand how to perform complex data
transformations and analytics using the
aggregation pipeline.
• Learn stages like $match , $group , $project ,
$sort , $lookup , etc.
📘 What is
Aggregation?
Aggregation is like SQL’s GROUP BY , JOIN , or even Excel's
Pivot Table. It lets you process and analyze large datasets
in real time.
🛠 Aggregation
37 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance
Pipeline Stages
Add new Edit this post Nitesh Synergy
[Link]([
{ stage1 },
{ stage2 },
{ stage3 }
])
[Link]([
{ $sort: { marks: -1 } } // descending
])
38 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
[Link]([
Appearance Add new Edit this post Nitesh Synergy
{
$lookup: {
from: "customers",
localField: "custId",
foreignField: "_id",
as: "customerDetails"
}
}
])
🎯 Learning Goals:
• Understand how indexing works in MongoDB.
• Learn how to create, view, and use indexes to
speed up queries.
• Analyze performance using the explain() method.
📘 1. What is an
Index?
An index in MongoDB is like an index in a book — it helps the
database find data faster, without scanning every document.
🔍 2. Creating
Indexes
[Link]({ fieldName: 1 }) // ascending
[Link]({ fieldName: -1 }) // descending
🔥 3. Compound Index
An index on multiple fields:
39 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
_____________________________________________________________________
🚫 4. Dropping an
Index
[Link]({ name: 1 })
To drop all:
[Link]()
🛠 5. Viewing Indexes
[Link]()
Look for:
💡 7. When to Use
Indexes
✅ Use indexes on:
40 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance 🎯 LeaEdit
Add new rn thisi ng Goals:
post Nitesh Synergy
2. Using Filters
📚 Use Cases:
• Real-time notifications
• Activity tracking in social apps
• Data replication
41 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance 🎯 LeaEdit
Add new rn thisi ng Goals:
post Nitesh Synergy
🎯 Learning Goals:
• Learn Role-Based Access Control (RBAC) to manage
database permissions.
• Implement user roles like Admin, Read-Write, Read-
Only in MongoDB.
📘 What is RBAC?
42 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
[Link]({
user: "myUser",
pwd: "myPassword",
roles: [ { role: "readWrite", db: "test" } ]
});
2. Built-in Roles:
🎯 Learning Goals:
• Understand sharding in MongoDB for horizontal
scalability.
• Set up a sharded cluster for high-volume data
handling.
📘 What is Sharding?
Sharding distributes your data across multiple machines (or
shards), which helps manage large datasets and high-traffic
apps.
🛠 Sharding Steps:
1. Sharded Cluster Setup:
• Shard: A replica set containing a subset of
your data.
• Mongos: Query router.
• Config Servers: Store metadata about the
cluster.
43 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
2. Shard Key:
Appearance Add new Edit this post Nitesh Synergy
Choose a field for sharding (e.g., userId ), which
evenly distributes the data.
🎯 Learning Goals:
• Learn how to store and query geospatial data
(locations, maps).
• Understand how to use 2d, 2dsphere indexes for
location-based queries.
🧪 Practice Task:
1. Store GPS coordinates ( longitude , latitude ) in a
locations collection.
2. Create a 2dsphere index.
3. Run queries like:
[Link]({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ -73.97,
40.77 ] },
$maxDistance: 5000
}
}
44 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
});
Appearance Add new Edit this post Nitesh Synergy
→ End….
Donate Now
1. Data Integrity
Data integrity refers to the accuracy, consistency, and
reliability of data throughout its lifecycle. This ensures
that data is not corrupted or lost and adheres to defined
rules and constraints.
45 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
Appearance Example
Add new Edit with
this post JPA and Bean Nitesh Synergy
Validation (Spring Boot):
import [Link].*;
import [Link];
import [Link];
@Entity
public class Product {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
import [Link];
import [Link];
@Service
public class ProductService {
2. Data Security
46 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
import
[Link];
import
[Link];
import
[Link]
@EnableWebSecurity
public class SecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws
Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin();
}
}
Encrypting Sensitive Data (e.g., passwords or credit card
numbers):
import
[Link];
import
[Link];
@Service
public class UserService {
47 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
[Link](plainPassword);
Appearance Add new Edit this post Nitesh Synergy
// Store encodedPassword in the database
}
}
import [Link];
import [Link];
3. Data Indexing
Data indexing improves the performance of database queries by
allowing fast lookups based on indexed fields.
import [Link].*;
import [Link];
48 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
@Entity
Appearance Add new Edit this post Nitesh Synergy
@Indexed
public class Product {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
@Column(nullable = false)
private double price;
@Indexed
@Column(nullable = false)
private String category;
}
In this example:
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</
artifactId>
</dependency>
import
[Link];
Summary:
• Data Integrity: Use JPA constraints and validation
annotations like @NotNull , @Positive , and @Size ,
along with transactional management for atomic
operations.
• Data Security: Use Spring Security for
authentication and authorization, and apply
49 of 50 07/11/25, 10:11 pm
SQL & NoSQL [Link]
42 min read
By Nitesh Synergy
SHARE
50 of 50 07/11/25, 10:11 pm