Skip to main content

4 posts tagged with "database"

View All Tags

· 3 min read

Introduction

  • Entity Framework Core is an ORM framework, open-source, lightweight and cross-platform developed by Microsoft.
  • It enables developers to work with databases using .NET object and EF Core is built on top of ADO.NET

Relationship

One-to-One Relationship

modelBuilder.Entity<Author>()
.HasOne(a => a.Book) // Author has one Book
.WithOne(b => b.Author) // Book has one Author
.HasForeignKey<Book>(b => b.AuthorId); // Foreign key in Book referencing AuthorId

One-to-Many Relationship

modelBuilder.Entity<Author>()
.HasMany(a => a.Books) // Author has many Books
.WithOne(b => b.Author) // Book has one Author
.HasForeignKey(b => b.AuthorId); // Foreign key in Book referencing AuthorId

Many-to-Many Relationship

modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new { sc.StudentId, sc.CourseId }); // Define composite primary key for the join table

modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Student)
.WithMany(s => s.Courses)
.HasForeignKey(sc => sc.StudentId); // Foreign key in join table referencing StudentId

modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Course)
.WithMany(c => c.Students)
.HasForeignKey(sc => sc.CourseId); // Foreign key in join table referencing CourseId

DeleteBehavior

The DeleteBehavior enum in EF Core includes the following options:

  1. Cascade: Deleting the principal/parent entity will cause the dependent/child entities to be deleted as well. OnDelete(DeleteBehavior.Cascade)

  2. SetNull: Deleting the principal/parent entity will set the foreign key properties in the dependent/child entities to null. OnDelete(DeleteBehavior.SetNull)

  3. SetDefault: Deleting the principal/parent entity will set the foreign key properties in the dependent/child entities to their default values. OnDelete(DeleteBehavior.SetDefault)

  4. Restrict: Prevents the deletion of the principal/parent entity if there are dependent/child entities. OnDelete(DeleteBehavior.Restrict) . An exception will be thrown.

  5. NoAction: Similar to Restrict, it is used to specify no action on delete. OnDelete(DeleteBehavior.NoAction) and you'll need to handle constraints in your application logic.

For example:

modelBuilder.Entity<ParentEntity>()
.HasMany(p => p.ChildEntities)
.WithOne(c => c.ParentEntity)
.OnDelete(DeleteBehavior.Restrict);

This configuration would set the delete behavior for the relationship between ParentEntity and ChildEntity to Restrict.

Best pratices

  1. Indexing: Creating indexes on frequently accessed columns can improve query performance.

  2. Proper data modeling: Designing tables and relationships properly can improve query performance and prevent performance issues.

  3. Caching: Storing frequently accessed data in a cache can reduce database calls and improve application performance.

  4. Query optimization: Writing efficient queries can improve performance. Techniques such as avoiding unnecessary joins and reducing the number of returned columns can help.

  5. Connection pooling: Reusing database connections instead of creating new ones can improve performance.

  6. Batch processing: Performing multiple operations in a single database call can improve performance and reduce overhead.

  7. Asynchronous programming: Using asynchronous programming techniques can improve performance by allowing the application to continue executing while waiting for database calls to complete.

· 6 min read

Are you ready to dive into the world of MongoDB and its powerful shell, mongosh? Let's begin our journey by learning how to install mongosh.

MongoDB Node.js Driver - Connection String Options

MongoDB supports various connection string options, including:

  • MaxPoolSize
  • MinPoolSize
  • maxIdleTimeMS

MongoDB Data Types - BSON Types

MongoDB uses BSON types to represent data. Here are some key BSON types:

  • Double: MongoDB uses Double; there is no Float.
  • String
  • Object
  • 32-Integer
  • 64-Integer
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Decimal128
  • Array

Data types ObjectId init from timestamp, increment, machineId, randomNumber

Querying MongoDB

MongoDB provides powerful querying capabilities. Let's explore some query operations:

  1. Collection.findOne(query, options)

  2. Collection.find().project().sort().skip().limit().count()

  • Comparison: The following operators can be used in queries to compare values: {field:{operator:value}}
    • $eq: Values are equal
    • $ne: Values are not equal
    • $gt: Value is greater than another value
    • $gte: Value is greater than or equal to another value
    • $lt: Value is less than another value
    • $lte: Value is less than or equal to another value
    • $in: Value is matched within an array {"salary":{$in:[5,10]}}
    • $nin: Value not in
    • $all: find in an array all elements matching in finding ['Smartphones', 'iOS']

Eg: db.trips.find({"id":{$in:[1,20]}})

  • Logical: The following operators can logically compare multiple queries. operator:[{condition1},{condition2},..]
    • $and: Returns documents where both queries match
    • $or: Returns documents where either query matches
    • $nor: Returns documents where both queries fail to match
    • $not: Returns documents where the query does not match

Eg: db.trips.find({$or:["id":{$gt:10},"price":{$lt:19}]})

Evaluation: The following operators assist in evaluating documents.

  • $regex: Allows the use of regular expressions when evaluating field values

  • $text: Performs a text search

  • $where: Uses a JavaScript expression to match documents

  • $expr: $expr: {operator:[field, value]}

  • $elemMatch: find an object in an array of objects only, cannot find in a field ot an array

  • $size: find the number of elements in an array {$scores: {$size: 6}}

  1. Collection.find().count()

  2. Collection.countDocuments()

  3. Collection.aggregate()

    1. [{$match:{}}, {$group:{}}, {$sort: {}}, {$skip: 10}, {$limit}]
    2. Group: total, average
    3. Var pipeline = [state1, state2, state3]
    4. {$count: "total"}
  4. Collection.listIndexes()

  5. Collection.countDocuments(query)

  6. FindAndModify(query:{}, update: {}, {new: true}): new = true: return a modified document

  7. Expression: db.movies.find({$expr:{$gt: ["$idbm.votes", "$year"]}})

  8. Db.products.find("name":"Smartphone").count();

{
"customer.gender": "M",
items: {
$elemMatch: {
name: 'printer paper'
}
}
}

Working with Documents - Insert, Update, and Delete

  • Inserting Documents

  • Collection.insertOne(document, option): Option = { writeConcern: { w : "majority", wtimeout : 100 } }

  • Db.insert({}, {returnId: true})

  • Db.insert([])

  • Collection.insertMany()

  • Updating Documents

  • Collection.updateOne(filter, update, option)

    • Filter = query
    • Update = {$set: {}} or {$inc: {balance: 1000}}
    • Update = {$push: {readings: {v: 10, t: new Date()}}}
    • Option = {upsert: true} upsert not $upsert
  • Collection.update()

  • Collection.updateMany()

  • await salesCollection.updateMany({items: {$elemMatch: {name: "printer paper"}}},{$set: {"items.$.price": 20 }});

  • Deleting Documents

  • deleteMany(query): If the query = {} delete all documents in the collection

  • deleteOne(): return ({acknowledge:true, deleteCount: 1})

  • deleteMany().deletedCount

MongoDB Indexing

MongoDB offers various indexing options to optimize query performance:

  • Single Index

  • Compound Index

  • MultiKey Index

  • Unique Index vs Non-Unique Index

  • Sparse Index vs Non-Sparse Index

  • Geography index: createIndex({locationField:'2dsphere'})

    • Example Query: You can perform geospatial queries using operators like $near, $geoWithin, $geoIntersects, and others to find documents based on their geographical proximity or containment.

MongoDB Aggregation Framework

MongoDB's Aggregation Framework is a powerful tool for data transformation and analysis. Let's explore some aggregation stages:

  • $match
  • $addFields
  • $group
  • $sample: {size: 10} get random 10 documents
  • $project: {total_avg: $round {number, place}}
  • $sortByCount: "$city" => descending = $group $sort descending
  • $lookup:{from: , localField:, foreignField, as:}
  • $out: to another collection must be in the same database => Last stage only
  • $bucketAuto :{groupBy: "$tripduration", buckets:5, output: {}}
  • $bucket: {groupBy:"$tripduration",boundaries: [10,100,1000,1000,100000], default: "other", output}

Full Text Search in MongoDB

MongoDB supports full-text search with various options for tokenization and fuzzy searching.

{
"mappings": {
"dynamic": false,
"fields": {
"company": {
"type": "string"
},
"title": {
"type": "string"
}
}
}
}

Tokenization and Fuzzy Options

  • EdgeGram beginning of the word
  • rightEdgeGram
  • nGram

Fuzzy option:

  • maxEdits
  • MaxExpansions
  • prefixLength

MongoDB Transactions

MongoDB provides support for transactions, ensuring data consistency in complex operations.

// Transaction
Session startSession()
UpdateOne({}, {$inc: {balance: -30}})
CommitTransaction
AbortTransaction

MongoDB Sharding and Replica Set

Sharding and Replica Set are essential concepts for scaling and ensuring high availability in MongoDB.

Sharding

Sharding distributes data across multiple servers to improve read and write scalability.

Replica Set

A Replica Set consists of multiple nodes with one primary node and two replicate nodes.

MongoDB Best Practices

MongoDB offers various best practices and considerations for efficient data modeling and management.

Data Model Patterns

There are 12 data model patterns, including Computed Pattern, Attribute Pattern, Polymorphic pattern, Bucket, Outline, and others.

Capped Collection

db.createCollection("", {capped: true, size: 10, max: 3})

Capped collection has a Limit size.

Read and Write Concern

  • Read Concern: Available, Majority, Local
  • Write Concern: Majority

MongoDB Views

Creating and working with views in MongoDB:

Db.createView("view_name","source_collection",[pipeline],collation)
Db.createView("name", "source", [])

Cannot update to view.

MongoDB Administration and Tools

MongoDB provides tools and commands for administrative tasks, backup, and restore.

mongorestore

Use mongorestore to restore a dump file to MongoDB.

Cursor Method and Indexing

Choose the appropriate cursor method, like Cursor.hint(), to force MongoDB to use a specific index for a query.

MongoDB Security

Ensure the security of your MongoDB instance by understanding the importance of the "admin" database and controlling user access.

Conclusion

In conclusion, MongoDB offers a robust and flexible database solution with a wide range of features for efficient data management and querying. Understanding the various concepts and best practices will empower you to make the most out of MongoDB in your projects. Happy coding!

· 6 min read

SQL Clauses

  • WHERE, ORDER BY, GROUP BY, and HAVING: Crafting strategic queries.
  • Today's exploration: INNER JOIN, OUTER JOIN, EXCLUDING JOIN, SELF JOIN, CROSS JOIN, UNION, and UNION ALL.

Why Do We Need JOIN?

  • Combining data from multiple tables based on matching conditions for comprehensive analysis.

INNER JOIN: A Deeper Dive

-- Example of INNER JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
INNER JOIN CustomerOrder o ON c.CustomerID = o.CustomerID;

In this practice, we retrieve customer information along with their corresponding orders using INNER JOIN.

JOIN More Than 2 Tables

-- Example of INNER JOIN with 3 tables
SELECT c.CustomerID, c.FullName, o.FoodName, d.FullAddress
FROM Customer c
INNER JOIN CustomerOrder o ON c.CustomerID = o.CustomerID
INNER JOIN DeliveryAddress d ON d.ID = o.DeliveryAddressID;

Extending the concept of INNER JOIN to involve three tables for a more comprehensive result set.

LEFT JOIN: Embracing Incompleteness

-- Example of LEFT JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
LEFT JOIN CustomerOrder o ON c.CustomerID = o.CustomerID;

Incorporating LEFT JOIN to include all customers, even those without orders.

RIGHT JOIN: Balancing the Equation

-- Example of RIGHT JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
RIGHT JOIN CustomerOrder o ON c.CustomerID = o.CustomerID;

Implementing RIGHT JOIN to include all orders, even those without customers.

FULL JOIN: Embracing Completeness

-- Example of FULL JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
FULL JOIN CustomerOrder o ON c.CustomerID = o.CustomerID;

Utilizing FULL JOIN to encompass all customers and orders, regardless of matches.

LEFT EXCLUDING JOIN: Seeking the Unique

-- Example of LEFT EXCLUDING JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
LEFT JOIN CustomerOrder o ON c.CustomerID = o.CustomerID
WHERE o.CustomerID IS NULL;

Applying LEFT EXCLUDING JOIN to identify customers without orders.

RIGHT EXCLUDING JOIN: Excluding to the Right

-- Example of RIGHT EXCLUDING JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
RIGHT JOIN CustomerOrder o ON c.CustomerID = o.CustomerID
WHERE c.CustomerID IS NULL;

Implementing RIGHT EXCLUDING JOIN to identify orders without customers.

OUTER EXCLUDING JOIN: Excluding in Unison

-- Example of OUTER EXCLUDING JOIN
SELECT c.CustomerID, c.FullName, o.FoodName
FROM Customer c
FULL JOIN CustomerOrder o ON c.CustomerID = o.CustomerID
WHERE c.CustomerID IS NULL OR o.CustomerID IS NULL;

Integrating OUTER EXCLUDING JOIN to identify unmatched records from both tables.

SELF JOIN: Connecting Within

-- Example of SELF JOIN
SELECT emp.ID, emp.FullName, manager.FullName AS Manager
FROM Employee emp
INNER JOIN Employee manager ON emp.ManagerID = manager.ID;

Demonstrating the concept of SELF JOIN to connect records within the same table.

CROSS JOIN: Expanding Horizons

-- Example of CROSS JOIN
SELECT *
FROM A
CROSS JOIN B;

Expanding horizons with CROSS JOIN to combine each row from one table with each row from another.

UNION: Merging Similarities

-- Example of UNION
SELECT FromColumnTableA FROM A
UNION
SELECT FromColumnTableB FROM B;

Merging similarities with UNION to combine result-sets from two tables.

UNION ALL: Embracing All

-- Example of UNION ALL
SELECT FromColumnTableA FROM A
UNION ALL
SELECT FromColumnTableB FROM B;

Embracing all with UNION ALL, including duplicates in the result set.

Sub Queries and Advanced Operators

  • Exploring the power of subqueries.
  • Advanced operators: EXISTS, ALL, IN, ANY.

What We Will Explore Today?

  • Sub queries, advanced operators, rules of subqueries, and practical exercises.

Subquery Basics

  • A sub-query, or inner query, nested inside a larger query.
  • Works independently within the outer query.
  • Execution sequence: Inner query executes first, results stored, and outer query runs on stored results.
  • Exception: Correlated subqueries reference outer query columns.

Example 1: Subquery for Average

-- Example of Subquery
USE LECTURE4_FUNCTION
SELECT LastName, Physic, (SELECT AVG(Physic * 1.0) FROM Student) AS 'AVG OF Physic'
FROM Student;

Example 2: Subquery in WHERE Clause

-- Example of Subquery in WHERE
USE LECTURE5_JOIN_DEMO
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID IN (SELECT CustomerID FROM CustomerOrder);

Types of Subqueries

  • Single-row subquery.
  • Multiple-row subquery.
  • Multiple-column subquery.
  • Correlated subquery.
  • Nested subquery.

Single-Row Subquery

-- Example of Single-Row Subquery
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID = (SELECT CustomerID
FROM CustomerOrder
WHERE FoodName = 'Heo Quay');

Exercise: Single-Row Subquery

Query CustomerID, OrderID, FoodName from CustomerOrder with Delivery FullAddress = 'TP. HCM' using a single-row subquery.

Multiple-Row Subquery

-- Example of Multiple-Row Subquery
USE LECTURE5_JOIN_DEMO
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID IN (SELECT CustomerID FROM CustomerOrder);

Exercise: Multiple-Row Subquery

Query CustomerID, OrderID, FoodName from CustomerOrder with Delivery FullAddress = 'TP. HCM' or 'TP. HA NOI' using a multiple-row subquery.

Multiple-Column Subquery

-- Example of Multiple-Column Subquery
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE EXISTS
(SELECT CustomerID, OrderID, FoodName
FROM CustomerOrder
WHERE CustomerOrder.CustomerID = Customer.CustomerID);

Exercise: Multiple-Column Subquery

Create a database, perform a self-join on the Employee table, and query managers with at least 1 employee.

Correlated Subquery

  • Normal subquery executes first and provides a value to the outer query.
  • Correlated subquery references a column in the outer query and executes the subquery once for each row in the outer query.
-- Example of Correlated Subquery
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE EXISTS
(SELECT CustomerID, OrderID, FoodName
FROM CustomerOrder
WHERE CustomerOrder.CustomerID = Customer.CustomerID);

Exercise: Correlated Subquery

Create a database, perform a self-join on the Employee table, and query managers with at least 1 employee.

Nested Subquery

-- Example of Nested Subquery
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID IN (SELECT CustomerID
FROM CustomerOrder
WHERE DeliveryAddressID = (SELECT ID
FROM DeliveryAddress
WHERE FullAddress = 'TP. HA NOI'));

Rules of Subqueries

  • Enclose a subquery in parentheses.
  • Must include a SELECT clause and a FROM clause.
  • Subqueries that return more than one row can only be used with multiple-value operators.
  • Can include WHERE, GROUP BY, and HAVING clauses.
  • Can include an ORDER BY clause only with a TOP clause.
  • Can nest subqueries up to 32 levels.

Advanced Operators: EXISTS

  • Used to test for the existence of any record in a subquery.
-- Example of EXISTS
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE EXISTS
(SELECT CustomerID, OrderID, FoodName
FROM CustomerOrder
WHERE CustomerOrder.CustomerID = Customer.CustomerID);

Advanced Operators: ALL

  • Returns TRUE if ALL of the subquery values meet the condition.
-- Example of ALL
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID = ALL (SELECT CustomerID FROM CustomerOrder);

Advanced Operators: IN

  • Allows specifying multiple values in a WHERE clause.
-- Example of IN
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID IN (SELECT CustomerID FROM CustomerOrder);

Advanced Operators: ANY

  • Allows performing a comparison between a single column value and a range of other values.
-- Example of ANY
USE LECTURE5_JOIN_DEMO;
SELECT CustomerID, FullName
FROM Customer
WHERE CustomerID = ANY (SELECT CustomerID FROM CustomerOrder);

· 9 min read

Data Manipulation Language (DML) Operations:

DML operations involve the manipulation of data within a database.

INSERT Data:

-- Single Record
INSERT INTO Student(ID, FullName, Email, PhoneNumber, Math)
VALUES(5, 'HUY', 'HUY@gmail.com', '0123456789', 5);

-- Multiple Records
INSERT INTO Student(ID, FullName, Email, PhoneNumber, DateOfBirth, Math)
VALUES
(4, 'LAN', 'LAN@gmail.com', '0123456789', '1/30/1999', 7),
(3, 'HAO', 'HAO@gmail.com', '0123456789', '12/15/2000', 8);

The INSERT statement adds new records to a table.

UPDATE Data:

-- Update Single Record
UPDATE Student
SET FullName = 'I AM A GOOD BOY'
WHERE ID = 3;

-- Update Multiple Records
UPDATE Student
SET FullName = 'Updated Name'
WHERE Math > 5;

The UPDATE statement modifies existing records in a table.

DELETE Data:

-- Delete Single Record
DELETE FROM Student
WHERE ID = 3;

-- Delete All Records with a Condition
DELETE FROM Student
WHERE Math > 5;

-- Truncate Table (Remove all records)
TRUNCATE TABLE Parent;

The DELETE statement removes records from a table.


Operators:

Operators perform various operations in SQL.

Arithmetic Operators:

SELECT 30 + 20 AS 'ADDITION';
SELECT 30 - 20 AS 'SUBTRACTION';
SELECT 30 * 20 AS 'MULTIPLICATION';
SELECT 30 / 20 AS 'DIVISION';
SELECT 30 % 20 AS 'MODULO';

Arithmetic operators perform mathematical operations.

Comparison Operators:

-- Equal To
SELECT ID, FullName
FROM Student
WHERE FullName = 'Lan Anh';

-- Greater Than
SELECT ID, FullName, Math
FROM Student
WHERE Math > 5;

Comparison operators compare values for equality, inequality, etc.

Logical Operators:

-- AND Operator
SELECT ID, FullName
FROM Student
WHERE FullName = 'Lan Anh' AND ID = 1010;

-- OR Operator
SELECT ID, FullName
FROM Student
WHERE FullName = 'Lan Anh' OR ID = 1005;

-- NOT Operator
SELECT ID, FullName, Math
FROM Student
WHERE NOT Math > 5;

Logical operators combine conditions using AND, OR, and NOT.

BETWEEN - AND:

-- Values within a Range
SELECT ID, FullName
FROM Student
WHERE ID BETWEEN 1003 AND 1005;

The BETWEEN - AND operator selects values within a specified range.

LIKE Operator:

-- Pattern Matching
SELECT FullName, Math
FROM Student
WHERE FullName LIKE '%U%';

The LIKE operator searches for a specified pattern in a column.

IS NULL:

-- Check for NULL Values
SELECT ID, FullName, Math
FROM Student
WHERE Math IS NULL;

The IS NULL operator checks for NULL values in a column.


SELECT Statement:

The SELECT statement retrieves data from one or more tables.

ORDER BY Clause:

-- Ascending Order
SELECT *
FROM Student
ORDER BY FullName ASC;

-- Descending Order
SELECT *
FROM Student
ORDER BY FullName DESC;

-- Order by Multiple Columns
SELECT *
FROM Student
ORDER BY FullName ASC, Math ASC;

The ORDER BY clause sorts query results in ascending or descending order.

TOP, PERCENT, and WITH TIES:

-- SELECT TOP N Rows
SELECT TOP 3 *
FROM Student;

-- SELECT TOP N Percent of Rows
SELECT TOP 50 PERCENT ID, FullName
FROM Student;

TOP limits the number of rows returned, and PERCENT filters by a percentage.

DISTINCT Keyword:

-- Select Distinct Values
SELECT DISTINCT FullName
FROM Student;

-- Select Distinct Values for Multiple Columns
SELECT DISTINCT ID, FullName
FROM Student;

The DISTINCT keyword removes duplicate rows from query results.

SELECT INTO Statement:

-- Create a New Table from SELECT Query
SELECT ID, FullName
INTO NewTable
FROM Student;

-- Select Data from Newly Created Table
SELECT *
FROM NewTable;

The SELECT INTO statement creates a new table from the result of a query.


VIEW:

A view is a virtual table based on the result of a SELECT statement.

CREATE VIEW:

-- Create a View
CREATE VIEW HelloView AS
SELECT FullName, Math
FROM Student
WHERE Math > 5;

-- Select Data from the View
SELECT *
FROM HelloView;

Use CREATE VIEW to define a view.

SQL Operators (Continued):

Additional SQL operators and their applications.

NOT NULL and IS NOT NULL:

-- Records with NULL Values
SELECT ID, FullName, Math
FROM Student
WHERE Math IS NULL;

-- Records with Non-NULL Values
SELECT ID, FullName, Math
FROM Student
WHERE Math IS NOT NULL;

Check for NULL or non-NULL values using IS NULL and IS NOT NULL .

Wildcards in LIKE Operator:

Utilize % and _ for pattern matching in the LIKE operator.

Wildcards in LIKE Operator:

-- Pattern Matching with Wildcards
SELECT FullName, Math
FROM Student
WHERE FullName LIKE '%U%';

% represents zero or more characters, and _ represents a single character in pattern matching.


JOIN Operation:

The JOIN operation combines rows from two or more tables based on related columns.

JOIN Operation:

-- Combine Rows from Two Tables
SELECT Student.ID, Student.FullName, Course.CourseName
FROM Student
JOIN Course ON Student.CourseID = Course.CourseID;

Use the JOIN keyword with specified conditions for combining rows.


GROUP BY and HAVING:

The GROUP BY clause groups rows that have the same values in specified columns, and HAVING applies conditions to grouped data.

GROUP BY and HAVING:

-- Group by CourseID and Calculate Average Math Score
SELECT CourseID, AVG(Math) AS AvgMathScore
FROM Student
GROUP BY CourseID
HAVING AVG(Math) > 7;

Use the GROUP BY clause for grouping and apply conditions with HAVING.


Authentic Operators:

Arithmetic:

-- Mathematical Wonders
SELECT 5 + 3 AS 'Addition', 10 - 4 AS 'Subtraction', 6 * 2 AS 'Multiplication', 16 / 4 AS 'Division', 17 % 5 AS 'Modulo';

In this example, we perform basic arithmetic operations on numerical values, showcasing the versatility of SQL in handling mathematical tasks.

Comparison:

-- Unveiling Equality and More
SELECT ID, FullName
FROM Students
WHERE Age = 25 OR Age > 30;

Here, we retrieve student records based on age, utilizing comparison operators to filter results for specific age criteria.

Logical:

-- Crafting Conditions with AND, OR, and NOT
SELECT ID, FullName
FROM Students
WHERE Age > 25 AND Department = 'Engineering';

Crafting a query that combines logical operators to filter students who are older than 25 and belong to the Engineering department.

Selecting Wisely:

SELECT Syntax:

-- Crafting the Perfect SELECT Statement
SELECT FirstName, LastName, Age
FROM Employees;

In this example, we select specific columns from the Employees table, demonstrating the fundamental syntax of the SELECT statement.

TOP & PERCENT:

-- Limiting and Filtering Rows
SELECT TOP 5 ID, ProductName, Price
FROM Products
ORDER BY Price DESC;

Limiting query results to the top 5 rows, showcasing the use of TOP in conjunction with ORDER BY to filter and sort data effectively.

ALIAS & DISTINCT:

-- Bringing Clarity to Your Results
SELECT AVG(Salary) AS 'Average Salary'
FROM Employees;

Calculating the average salary and assigning it an alias for clarity, highlighting the use of aliases in result sets.

FROM, WHERE, VIEW, SELECT INTO:

-- Mastering the Essentials
SELECT EmployeeID, FirstName, LastName
INTO NewEmployeeTable
FROM Employees
WHERE Department = 'IT';

Creating a new table named NewEmployeeTable by selecting specific columns from the Employees table and filtering results based on the IT department.


SQL Built-in Functions: A Symphony of Capabilities

String Functions Showcase:

LOWER & UPPER:

-- Transforming Case with Flair
SELECT LOWER('Hello') AS 'lower function', UPPER('Hi there') AS 'UPPER FUNCTION';

Applying the LOWER and UPPER functions to manipulate text case, showcasing the versatility of string functions.

LEN & REVERSE:

-- Revealing Lengths and Reversing Strings
SELECT LEN('Database') AS 'Length', REVERSE('SQL') AS 'Reversed';

Using LEN to find the length of a string and REVERSE to reverse the characters, demonstrating string manipulation capabilities.

CONCAT & SUBSTRING:

-- Crafting and Extracting Strings
SELECT CONCAT('Hello', ' ', 'World') AS 'CONCAT FUNCTION', SUBSTRING('123456789', 3, 4) AS 'SUBSTRING FUNCTION';

Combining strings with CONCAT and extracting a substring, exemplifying the power of string functions in SQL.

LTRIM & RTRIM:

-- Trimming with Finesse
SELECT '|' + LTRIM(' Hi') + '|' AS 'LTRIM FUNCTION', '|' + RTRIM('Hi ') + '|' AS 'RTRIM FUNCTION';

Trimming leading and trailing spaces using LTRIM and RTRIM, showcasing string manipulation for cleaner outputs.

Datetime Functions: Unraveling Time's Mysteries:

MONTH, DAY, YEAR:

-- Extracting Temporal Insights
SELECT MONTH('11/13/2022') AS 'MONTH FUNCTION', DAY('11/13/2022') AS 'DAY FUNCTION', YEAR('11/13/2022') AS 'YEAR FUNCTION';

Extracting month, day, and year components from a date, unraveling temporal insights using datetime functions.

GETDATE & ISDATE:

-- Unleashing the Power of Time
SELECT GETDATE() AS 'GETDATE FUNCTION', ISDATE('11/13/2022') AS 'ISDATE FUNCTION';

Utilizing GETDATE to retrieve the current date and time, along with ISDATE to validate a date string.

DATEPART:

-- Precision in Date and Time
SELECT DATEPART(HOUR, '11/13/2022 19:20') AS 'DATEPART HOUR', DATEPART(MINUTE, '11/13/2022 19:20') AS 'DATEPART MINUTE';

Extracting specific components like hour and minute using DATEPART, providing precision in date and time manipulation.

Date Manipulation with DATEDIFF:

-- Exploring the Gap Between Dates
SELECT DATEDIFF(MONTH, '10/15/2020', '11/25/2022') AS 'DATEDIFF MONTHS';

Calculating the difference in months between two dates using DATEDIFF, demonstrating date manipulation capabilities.

Aggregate Functions: Bringing Data Together

SUM & AVG:

-- Summing Up and Finding Averages
SELECT SUM(Sales) AS 'Total Sales', AVG(Price) AS 'Average Price'
FROM Products;

Aggregating data with SUM and AVG, showcasing their roles in summarizing numeric values.

MIN & MAX:

-- Uncovering Extremes
SELECT MIN(Age) AS 'Minimum Age', MAX(Age) AS 'Maximum Age'
FROM Employees;

Identifying the minimum and maximum values within a dataset using MIN and MAX aggregate functions.

COUNT:

-- Counting Rows Strategically
SELECT COUNT(*) AS 'Total Records'
FROM Customers;

Counting the total number of records in the Customers table, emphasizing the strategic use of COUNT.

Counting the COUNTs: Strategies Unveiled

COUNT(*) vs COUNT(1):

-- Decoding the Mystery
SELECT COUNT(*) AS 'Total Records', COUNT(1) AS 'Another Count'
FROM Orders;

Comparing COUNT(*) and COUNT(1) to decode the mystery of counting rows effectively.

COUNT with DISTINCT:

-- Navigating Unique Territories
SELECT COUNT(DISTINCT Department) AS 'Distinct Departments'
FROM Employees;

Counting the distinct departments within the Employees table, illustrating the usage of COUNT with DISTINCT.

Ceiling & Floor: Elevating and Lowering Numbers

CEILING & FLOOR:


-- Rounding Up and Down