Skip to main content

3 posts tagged with "sql"

View All Tags

· 10 min read

Introduction to SQL

SQL is a standard language designed for managing data in relational databases. It's commonly used to query, insert, update, and modify data. Most RDBMS (Relational Database Management System) like MySQL, SQLite, Oracle, and PostgreSQL use SQL.

As a data analyst, you'll often work with large volumes of data stored in these databases. SQL becomes an essential tool to retrieve, manipulate, and analyze this data.

1.1 RDBMS and Tables

In SQL, data is stored in tables, just like an Excel spreadsheet. A table is made up of rows (records) and columns (fields). Here's an example of a table, Employees:

EmployeeIDFirstNameLastNamePosition
1JohnDoeAnalyst
2JaneDoeEngineer
3MaryJohnsonManager

2. Basic SQL Syntax

Let's look at the fundamental SQL commands: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.

2.1 SELECT and FROM

The SELECT statement is used to select data from a database, and the FROMstatement specifies which table to get the data from.

SELECT FirstName, LastName 
FROM Employees;

This query retrieves all first and last names from the Employees table. If you want to select all columns, use the * symbol:

SELECT * FROM Employees; 

2.2 WHERE

The WHERE clause is used to filter records:

SELECT * 
FROM Employees
WHERE Position = 'Analyst';

This query retrieves all data for employees who are analysts.

2.3 GROUP BY and HAVING

GROUP BY groups rows that have the same values in specified columns into aggregated data. HAVING is used instead of WHERE with aggregated data.

SELECT Position, COUNT(*) 
FROM Employees
GROUP BY Position
HAVING COUNT(*) > 1;

This query shows positions held by more than one employee.

2.4 ORDER BY

ORDER BY is used to sort the data in ascending or descending order:

SELECT * 
FROM Employees
ORDER BY LastName ASC;

This query sorts employees by their last name in ascending order.

3. Querying Data

The SELECT statement is not just for selecting simple rows. We can use it to perform calculations, concatenations, and more.

SELECT FirstName || ' ' || LastName as FullName, Position
FROM Employees;
This query concatenates the first and last names, separated by a space, and displays it as FullName.

4. Filtering and Sorting Data

Apart from WHERE and ORDER BY, SQL offers BETWEEN, LIKE, and IN to filter data.

4.1 BETWEEN

BETWEEN is used to filter by a range:

SELECT * 
FROM Orders
WHERE OrderDate BETWEEN '2023-01-01' AND '2023-12-31';

This query selects all orders placed in the year 2023.

4.2 LIKE and ILIKE

LIKE is used in a WHERE clause to search for a specified pattern in a column. The "%" sign is used to define wildcards (missing letters) both before and after the pattern. Also, note that LIKE is case sensitive. ILIKE can be used for case-insensitive search.

SELECT * 
FROM Employees
WHERE FirstName LIKE 'J%';

This query selects all employees with a first name starting with 'J'.

4.3 IN

IN allows you to specify multiple values in a WHERE clause:

SELECT * 
FROM Employees
WHERE Position IN ('Analyst', 'Engineer');

This query selects all analysts and engineers.

5. Joining Tables

JOIN statements are used to combine rows from two or more tables based on a related column. The different types of joins include INNER JOIN, LEFT (OUTER) JOIN, RIGHT (OUTER) JOIN, and FULL (OUTER) JOIN. Consider this additional table, Departments:

DepartmentIDDepartmentName
1IT
2Sales
3HR

And suppose we add a DepartmentID field to the Employees table. Here's how we can use different types of joins:

5.1 INNER JOIN

SELECT Employees.LastName, Employees.FirstName, Departments.DepartmentName 
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

This query retrieves the list of employees along with their respective department names.

  • 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.

5.2 LEFT (OUTER) JOIN

SELECT Employees.LastName, Employees.FirstName, Departments.DepartmentName FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

This query retrieves all employees and their departments, including employees with no department (the DepartmentName for them will be NULL).

5.3 RIGHT (OUTER) JOIN

SELECT Employees.LastName, Employees.FirstName, Departments.DepartmentName FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

This query retrieves all departments and their employees, including departments with no employees.

5.4 FULL (OUTER) JOIN

SELECT Employees.LastName, Employees.FirstName, Departments.DepartmentName FROM Employees
FULL JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

This query retrieves all combinations of employees and departments, including employees with no department and departments with no employees.

6. Aggregation Functions

SQL provides several functions to perform calculations on data, such as COUNT(), SUM(), AVG(), MIN(), MAX(), and GROUP_CONCAT().

SELECT COUNT(*) 
FROM Orders
WHERE OrderDate BETWEEN '2023-01-01' AND '2023-12-31';

This query returns the total number of orders placed in the year 2023.

7. Subqueries and Nested Queries

A subquery is a SQL query nested inside a larger query. A subquery may occur in:

  • A SELECT clause
  • A FROM clause
  • A WHERE clause The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.
SELECT EmployeeID, FirstName, Position 
FROM Employees
WHERE EmployeeID IN (SELECT EmployeeID FROM Orders WHERE OrderTotal > 1000);

This query selects all employees who have made orders totaling more than 1000.

8. Modifying Database Information

SQL allows you to insert, update, and delete data with INSERT, UPDATE, and DELETE commands respectively. Be careful when using these commands as you can change your data permanently.

8.1 INSERT

INSERT INTO Employees (EmployeeID, FirstName, LastName, Position) VALUES (4, 'Mark', 'Anderson', 'Analyst'); 

This query adds a new row to the Employees table.

8.2 UPDATE

UPDATE Employees 
SET Position = 'Senior Analyst'
WHERE EmployeeID = 4;

This query changes Mark Anderson's position to Senior Analyst.

8.3 DELETE

DELETE FROM Employees WHERE EmployeeID = 4; 

This query deletes Mark Anderson's record from the Employees table.

9. Advanced SQL Techniques

Let's delve into more complex techniques with the help of examples.

9.1 Handling NULL values

NULL value in SQL means no or zero value. Here's how you can use IS NULL and IS NOT NULL:

SELECT * 
FROM Employees
WHERE DepartmentID IS NULL;

This query selects all employees who don't belong to any department.

SELECT * 
FROM Employees
WHERE DepartmentID IS NOT NULL;

This query selects all employees who belong to a department.

9.2 String Functions

SQL offers several functions to manipulate strings. Some examples include:

  • CONCAT(): Concatenates two or more strings.
  • TRIM(): Removes leading and trailing spaces of a string.
  • LENGTH(): Returns the length of a string.
SELECT CONCAT(FirstName, ' ', LastName) as FullName, TRIM(Position), LENGTH(FirstName) as NameLength 
FROM Employees;

This query retrieves a full name by combining first and last names, the position after removing leading and trailing spaces, and the length of the first name.

9.3 Date and Time Functions

SQL provides many functions to work with date and time. Some examples include:

  • NOW(): Returns the current date and time.
  • CURDATE(): Returns the current date.
  • CURTIME(): Returns the current time.
SELECT OrderID, OrderTotal, NOW() as QueryTime 
FROM Orders
WHERE OrderDate = CURDATE();

This query retrieves today's orders along with the query execution time.

9.4 Case Statements

Case statements help in implementing conditional logic in SQL:

SELECT FirstName, Position, 
CASE
WHEN Position = 'Analyst' THEN 'Junior Level'
WHEN Position = 'Engineer' THEN 'Mid Level'
ELSE 'Senior Level'
END as JobLevel
FROM Employees;

This query categorizes employees into job levels based on their positions.

9.5 Window Functions

Window functions perform calculations across a set of table rows that are related to the current row:

SELECT FirstName, Position, Salary, 
RANK() OVER (PARTITION BY Position ORDER BY Salary DESC) as Rank FROM Employees;

This query ranks employees within their respective positions based on their salaries.

Optimization and Performance Tuning

Here are some examples demonstrating SQL optimization techniques:

10.1 EXPLAIN

Most SQL databases support the EXPLAIN command, which shows the execution plan of an SQL statement. This can help you understand how your SQL query will be executed and where you can optimize it.

EXPLAIN SELECT * FROM Employees; 

10.2 Avoid SELECT

Rather than using SELECT *, specify the columns you need. This reduces the amount of data that needs to be read from the disk.

SELECT FirstName, LastName FROM Employees; 

10.3 Use LIMIT

If you only need a specific number of rows, use LIMIT to prevent reading unnecessary data.

SELECT * FROM Employees ORDER BY Salary DESC LIMIT 10; 

This query gets the top 10 employees with the highest salaries. 10.4 Index your data Indexing your data can significantly speed up data retrieval times. Here's how you can add an index:

CREATE INDEX idx_employees_position ON Employees(Position); 

What's Next?

  1. Practice, practice, practice: The best way to reinforce your SQL skills is by practicing. Websites like LeetCode, HackerRank, and SQLZoo provide hundreds of SQL problems that you can practice with.
  2. Learn Database Design: Understanding how databases are structured and designed will help you write better and more efficient SQL queries. Look into topics such as normalization, entity-relationship models, and data integrity.
  3. Explore Advanced SQL Topics: This tutorial covered the basics, but there's still a lot to learn. Delve into more advanced topics like stored procedures, triggers, views, and transaction control.
  4. Learn About Database Administration: Although not typically part of a Data Analyst's role, understanding how a database is administered can provide useful context. This can also open up new opportunities in the realm of database management.
  5. Understand SQL in the context of a programming language: If you are familiar with a programming language like Python or R, try to use SQL commands within these languages. This often gives you more flexibility and allows you to perform more complex operations with your data.
  6. Learn About Different SQL Databases: There are many different SQL databases, such as MySQL, SQLite, PostgreSQL, and Oracle. Each has its own unique features and syntax nuances. Familiarize yourself with the one that's most relevant to your work or interests.
  7. Apply SQL in Your Projects: The ultimate test of your skills will be applying SQL in your projects. Whether it's for cleaning data, data wrangling, or analysis, the practical application of SQL will solidify your learning and give you valuable experience. Remember, becoming proficient in SQL is a journey, not a destination. Enjoy the process of learning and experimenting. Happy querying!

· 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