SQL Foundation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

INTRODUCTION TO SQL

Data Base:- Organized collection of Homogeneous(Related Information) Data. It is used to


store and manage data for wide range of application. These are two types

1. Hierarchical Database:- In this data is stored in form of one or more trees. To access
these data we used Tree Traversal Algorithm. It is computationally cost effective.
2. Relational Database:- Represented as sets of table and connecting these table
effectively. Fast to access and represent any complex data.
NOTE:- How internal memory stores Data ? Internal memory is devided into pages each
page designed in such a way that it can store a fixed Data byte. Computer inderstands only
Binary Data.
DBMS:- Database Management System, used to store, retrieve and run queries on Data.
In which we can read, create, update and delete data in Database.
RDBMS:- Relational Database Management System, it is a software which supports SQL
language to work on relational database. In example way it is a collection of table, where all
are related (Homogeneous type) to each other.
The following are popular RDBMS which supports SQL
1. Oracle Database from Oracle Corp.
2. SQL Server from Microsoft
3. DB2 universal database from IBM
4. MySQL – Only Open Source RDBMS
What is Server ?
Ans:- A Computer program or device that provides a service to another computer program
and its user.

SQL (SEQUEL)
(Structured Query Language)
It is a programming language used for starting and processing information which are in a
tabular form with rows and column in a relational database.
SQL is a non-procedural language, it means the programmer has limited control of flow of
execution when compared to the procedural language like C, C++, JAVA etc.
It is case-insensitive language. We can do these operations with SQL language like
C- Create R- Read U- Update D- Delete
Many organisations take SQL and added own features then produce their own SQL
1. Oracle – PL/SQL (Best in Industry) 3. MS- SQL Server
2. EDB – Postgres 4. MySQL
IDE:- Integrated Development Environment
It is a software application that helps programmers to develop software code efiiciently.
Software editing, building, testing & packaging in an easy to use application.
Every organisations has own IDE
1. ORACLE – SQLDEV
2. EDB – PGADMIN
3. MS – SSMS
4. MySQL – MySQL Workbench
How MySQL DB works?
MySQL DB → Response with Data
MySQL Server → Parses the queries
MySQL Workbench → Queries by SQL Language
What is Query ?
It is the code used to retrieve the data from the database. Code will be written in SQL-
Language. Mostly SQL we write SQL commands in CAPITAL LETTER and remaining code
in Running Letter.
Syntax :- Grammar of Programming Language

DATA TYPES
Broadly Classified into 3 types
1. Character Data : CHAR, VARCHAR
2. Numeric Data : INT, FLOAT
3. Date (Temporal) Data : DATE, DATETIME

1. Character Data
CHAR:- It is a datatype in SQL which is used to store character string of fixed length
specified. If the length of the string is less than set or fixed-length then it is padded
with extra blank spaces. We should use this datatype when we expect the data values
in a column are of the same length.
VARCHAR:- It is a datatype in SQL which is used to store character string of
variable length but a maximum of the set length specified. If the length of the
string is less than set or fixed-length then it will store as it is without padded
with extra blank spaces. We should use this datatype when we expect the data
values in a column are of variable length.
2. Character Data
INT:- INT stands for the integer that is a whole number. An integer can be written
without a fractional component e.g., 1, 100, 4, -10, and it cannot be 1.2, 5/3, etc.
An integer can be zero, positive, and negative.
DECIMAL:-
(P,S) → P- Precision S- Scale
Range → 1 to 65 0 to 30

3. Temporal Data:-
Format Range
Date → YYYY-MM-DD 1000-01-01 to 9999-12-31
Time → HH:MM:SS -838:59:59 to 838:59:59
Date Time → YYYY-MM-DD 1000-01-01 to 9999-12-31
HH:MM:SS -838:59:59 to 838:59:59

DATA Types Example:-


Customer ID Customer Name Ph. No. Age Gender
Numeric String / Text String Numeric String
INT/DEC CHAR/VARCHAR CHAR/VAR INT/DEC CHAR/VAR

Basic Queries
(SELECT, FROM, WHERE)
SELECT:- It is used to retrieve data from a database table. It specifies the columns that you
want to retrieve.
An Asterisk (*) → to select all columns
FROM :- It specifies the table or tables from which you want to retrieve data. We can join
multiple tables using JOIN clauses.
FROM :- It is used to filter data based on certain conditions. We can use logical operators
such as AND, OR, and NOT to combine multiple conditions.
SQL SUB-LANGUAGES
• DQL:- Data Query Language (Used for SELECT)
• DDL:- Data Definition Language (Used for CREATE, DROP, ALTER, Truncate)
• DML:- Data Manipulation Language (Used for INSERT, UPDATE, DELETE)
• DCL:- Data Control Language (Used for GRANT, REVOKE)
• TCL:- Transaction Control Language (Used for COMMIT, ROLLBACK, SAVE POINT)

NOTE:- “USE Commands”


It is used to select particular Database. Syntax:- “USE <DATABASE NAME>”
Because in work-bench, there are so many databases are present for that reason we have
to use “USE” command to call database.

NOTE:- “;” Delimiter, used to show Query is end here.

OPERATORS
1. Arithmetic Operator:-
‘+’ Add Ex:- SELECT 30+20;
‘-’ Subtract Ex:- SELECT 30-20;
‘*’ Multiply Ex:- SELECT 30*20;
‘/’ Divide Ex:- SELECT 40/20;
‘%’ It is used for reminder.
2. Comparison Operator:-
‘=’ → Equal To
‘<>’ or ‘!=’ → Not Equal to
‘<’ → Less than
‘>’ → Greater than
‘<=’ → Less than Equal to
‘>=’ → Greater than Equal to
We can use these operators in string data type and date data type also. In string Data
type it works as dictionary alphabetical order. In Date (Temporal) data type it will work like
according to the equal date and time.
3. Range Operator (BETWEEN Operator):-
It is used to retrieve data within a specific range of values.
Ex:- SELECT * FROM customer WHERE customer_id BETWEEN 10 and 20;
Ex:- SELECT * FROM customer WHERE customer_id BETWEEN 20 and 10;
The above example will not work because of Higher value range to lower value
range (underlined statement).
Ex:- SELECT * FROM customer WHERE first_name BETWEEN 'S' and 'U';
It will give data of ‘S’ and ‘T’ only not ‘U’.

NOTE:- After BETWEEN operator we can’t use Parenthesis ().


SELECT * FROM customer
WHERE first_name BETWEEN ('S' and 'U');
(We can’t get any result b/c of underlined statement)
4. Membership Operator (IN - Operator):-
It is used to retrieve data that matches a list of values.
NOT IN :- It will give the information regarding excluding the given details.
Ex:- SELECT * FROM customer WHERE customer_id IN (1,5,7,25);
Ex:- SELECT * FROM customer WHERE first_name IN ('SETH');
(It will give SETH’s details only)
Ex:- SELECT * FROM customer WHERE first_name IN ('S');
SELECT * FROM customer WHERE first_name IN ('S');
(In these both cases we can’t get any result)

NOTE:- For Multiple data we use ‘IN’ operator, for one Data we will use ‘=’ operator.
5. Logical Operator:-
➢ AND:- Return True if all the conditions are True, then it will give result of the
Queries. Means, it will check for all the conditions to be satisfied then it will give
results.
➢ OR:- It will give you result if either condition is True.
➢ NOT:- Reverse the Logical state of condition.
SQL FUNCTIONS

• A stored piece of code that performs a specific task.


• It takes inputs called as parameter. Function can be of two types SCALAR and TABLE
VALUED functions.
• Function can be system defined and user defined. There are different types of Scalar
Functions, here we cover the following
❖ String Function
❖ Numeric Functions
❖ Temporal Functions

❖ String functions
String functions are used to manipulate string data. Here are some commonly
used string functions in SQL:
1. CONCAT():
The CONCAT() function is used to concatenate two or more strings into one.
For example, to concatenate the first name and last name columns in a table, you can
use the following SQL query:
EX:-
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM table1;
This will return a new column called full_name that contains the concatenated
values of the first_name and last_name columns.

NOTE:- Whenever we write a string and date SYNTAX in SQL we need to write it within
single-inverted-comma (‘ ’).
We can use single-inverted-comma for space purpose, under score also for space
purpose as well as mostly we use SPACE(Number) ; Number – 1,2,3,4,5,6 …

NOTE:- In SQL, an alias is a temporary name given to a table, column, or expression in a


query.

2. TRIM():
The TRIM() function removes the space character OR other specified characters
from the start or end of a string. By default, the TRIM() function removes leading and
trailing spaces from a string.
L-Trim & R-Trim is there for trimming of Left (Leading) and Right (Trailing) unusual
spaces.
EX:- select trim(' raghu ') Ans:- ‘raghu’
select rtrim(' raghu ') Ans:- ‘ raghu’
select LTRIM(' raghu ') Ans:- ‘raghu ’
3. UPPER() and LOWER():
The UPPER() function is used to convert a string to uppercase, while the
LOWER() function is used to convert a string to lowercase. For example, to convert
the last_name column in a customer_table to uppercase, you can use the following
SQL query:
EX:-
SELECT UPPER(last_name) AS last_name_upper FROM Customet_table;
This will return a new column called last_name_upper that contains the
last_name column in uppercase.
4. LENGTH():
The LENGTH() function is used to return the length of a string. For example, to
find the length of the first_name column in a customer_table, you can use the following
SQL query:
EX:-
SELECT LENGTH(first_name) AS name_length FROM Customet_table;
This will return a new column called name_length that contains the length of
the first_name column.
5. REPLACE():
The REPLACE() function is used to replace a portion of a string with a new
string. It takes three arguments: the string to be replaced, the string to replace it with,
and the string to search for. For example, to replace all occurrences of the string "Mr."
with the string "Sir" in the title column of a table, you can use the following SQL query:
SYNTAX:- SELECT REPLACE( ‘String’,’what to replace’,’replace with);
EX:-
SELECT REPLACE(title, 'Mr.', 'Sir') AS new_title FROM table1;
This will return a new column called new_title that contains the title column with
all occurrences of "Mr." replaced with "Sir".
6. POSITION():
It will give exact location of particular character in string. It will give first
occurrence not the repetition.
EX:-
SELECT position('D' IN 'ODIN SCHOOL') Ans:- 2
SELECT position('O' IN 'ODIN SCHOOL') Ans:- 1 (Only first occurence)
7. SUBSTRING():

The SUBSTRING() function is used to extract a portion of a string. It takes three


arguments: the string to be extracted, the starting position of the substring, and the
length of the substring. For example, to extract the first three characters of the
first_name column in a table, you can use the following SQL query:

SYNTAX:- SELECT SUBSTRING (String to be searched, Position of the String to be


extracted, Length of the String to be Extracted)

Ex:- SELECT SUBSTRING(first_name, 1, 3) AS first_three FROM


customer_table;

This will return a new column called first_three that contains the first three
characters of the first_name column.

❖ Numeric functions:

Numeric functions are used to perform mathematical operations on numeric


data. Here are some commonly used numeric functions in SQL:

1. ROUND():

The ROUND() function is used to round a number to a specified number of


decimal places.

EX:- SELECT ROUND (4.5) Ans:- 5

SELECT ROUND (4.4) Ans:- 4

For example, to round the salary column in a table to two decimal places, you
can use the following SQL query:

SELECT ROUND(salary, 2) AS rounded_salary FROM table1;

This will return a new column called rounded_salary that contains the salary
column rounded to two decimal places.

Select ROUND(17.36782,2) Ans:- 17.37 (Not 17.36)

Select ROUND(17.3625,2) Ans:- 17.36 (Not 17.37)

2. CEILING():

It will give Higher next value for any decimal.

EX:- Select CEIL(4.5) Ans:- 5

Select CEIL(4.4) Ans:- 5


3. FLOOR():

It will give Higher next value for any decimal.

EX:- Select FLOOR(4.4) Ans:- 4

Select FLOOR(4.8) Ans:- 4

4. POWER / POW ():

Square, Cubes … Etc…

SYNTAX:- Select POWER (Base, Power_Value)

EX:- Select POWER(2,3) Ans:- 8

Select POWER(12.5,5) Ans:- 305175.78125

Select ROUND(POWER(12.5,5),2) Ans:- 305175.78

(It gives the result upto 2 decimal places with Mathematical Logic)

5. SQRT():

It will give a square root of a number.

EX:- Select SQRT(64) Ans:- 8

6. TRUNCATE():

The TRUNCATE() function truncates a number to the specified number of


decimal places.

EX:- Select TRUNCATE (4.536748, 2) Ans:- 4.53

7. ABS(): It is used to get a absolute positive value number.

EX:- Select TRUNCATE (150 - 450) Ans:- -(-300) = 300

EX:-

Select ROUND(ABS(TRUNCATE(POWER(Amount,2),3) - (Amount/0.22)),3)


From Payment Ans:-
Limit 5; 4.651
3.52
8.653
3.52
54.391
❖ Temporal functions:

Temporal functions are used to manipulate date and time data. Here are some
commonly used temporal functions in SQL

1. DATE / DAY:

The DATE function is used to extract the date portion of a date/time value. The
syntax is as follows:

SYNTAX:- Select DATE(datetime_expression)

EX:- Select DATE(payment_date) as date_only FROM Payment

2. YEAR:

The YEAR function is used to extract the year portion of a date/time value. The
syntax is as follows:

SYNTAX:- Select YEAR(datetime_expression)

EX:- Select YEAR(payment_date) as Year_Only FROM Payment

3. MONTH:

The MONTH function is used to extract the month portion of a date/time value.
The syntax is as follows:

SYNTAX:- Select MONTH(datetime_expression)

EX:- Select MONTH(payment_date) as Month_Only FROM Payment

4. DAY NAME / MONTH NAME:

The DAYNAME / MONTHNAME function is used to extract the day / month


portion of a date/time value. The syntax is as follows:

SYNTAX:- Select DAYNAME(datetime_expression)

Select MONTHNAME(datetime_expression)

EX:- Select DAYNAME(payment_date) as DayName_Only FROM Payment

Select MONTHNAME(payment_date) as MonthName_Only FROM Payment

5. NOW (For Today’s Date):

The NOW function is used to retrieve the current date and time. The syntax is
as follows: NOW() / SYSDATE()
For example, if you want to retrieve the current date and time in a query, you
can use the NOW function like this:

EX:- Select NOW() as Current_Time

Select SYSDATE() as Current_Time

These are just a few examples of the temporal functions available in SQL. Other
functions include HOUR, MINUTE, SECOND, and TIMESTAMPDIFF, which can be
used to calculate the difference between two timestamps.

EX:-

HOUR:- Select payment_date, HOUR(payment_date) as Hour_Only FROM Payment;

MINUTE:- Select payment_date, MINUTE(payment_date) as Minute_Only FROM


Payment;

SECOND:- Select payment_date, SECOND(payment_date) as Second_Only FROM


Payment;

NOTE:- We can write the above temporal function just like this also with the help of
EXTRACT function.

select EXTRACT(MONTH FROM '2022-05-15');

select EXTRACT(DAY FROM '2022-05-15');

select EXTRACT(YEAR FROM '2022-05-15');

6. DATE_ADD:

The DATEADD() function adds a time/date interval to a date and then returns
the date.

SYNTAX:- Select DATE_ADD(SYSDATE(), INTERVAL YEAR/MONTH/DAY)

EX:- SELECT DATE_ADD(sysdate(), INTERVAL 2 YEAR);

(It will give 2 years ahead of today’s date)

SELECT DATE_ADD(sysdate(), INTERVAL 2 MONTH);

SELECT DATE_ADD(sysdate(), INTERVAL 2 DAY);

7. DATEDIFF:

The DATEDIFF() function returns the difference between two dates.


EX:- Select (ROUND(DATEDIFF('2023-01-01','2022-01-01'))); Ans:- 365 Days

Select (ROUND(DATEDIFF('2023-01-01','2022-01-01')/30)); Ans:- 12 Months

Select (ROUND(DATEDIFF('2023-01-01','2022-01-01')/7)); Ans:- 52 W

select (Round(datediff('2022-01-01','2023-01-01')/30)); Ans:- -12 Months

For Negative result we need to convert into absolute positive value. For that we
will use ABS function.

select ABS(Round(datediff('2022-01-01','2023-01-01')/30)); Ans:- 12 Months

DISTINCT and LIMIT


❖ Distinct:

It is used to retrieve unique values from a column. Inside a table, a column often
contains many duplicate values; and sometimes you only want to list the different
(distinct) values.

Distinct is not a clause, it is a statement.

EX:- If there is a payment table where it contains 1500 transaction details of 325
customer. Here 325 customers are Distinct but the transactions are not Distinct.

Select DISTINCT Customer_Id From Payment;

NOTE:-
➢ Select DISTINCT Customer_Id, Amount, Payment_Date From Payment;
(Here DISTINCT is applied to all combinaton of Customer_Id, Amount,
Payment_Date.)
➢ Select DISTINCT (Customer_Id), Amount, Payment_Date From Payment;
(After Writing Customer_Id within parentheses, still it will be applied to
combination.)
➢ Select DISTINCT ( * ) From Payment
(We can’t write just like this, ERROR)
➢ Select DISTINCT * From Payment
(We can write but in actual scenario it will cost a lot because at this moment
Compiler can’t compile this actual.)
➢ Select Amount, DISTINCt Customer_Id, Payment_Date From Payment;
(We can’t write DISTINCT within the middle of statement, DISTINCT should be
write only after SELECT SYNTAX.)
➢ Don’t use DISTINCT every time, try to avoid.
❖ Limit:

The LIMIT clause is used to specify the number of records to return as follows.

EX:- Select * From Payment


Limit 5; (Which will give only first 5 payment details)

Select * From Payment


Limit 10,10; (Which will give payment details of From Sl. No. 11 to 20)

WILDCARDS (Like Operator)


The LIKE operator is used in a WHERE clause to search for a specified pattern (Pattern
Matching) in a column. It is only used with CHARACTER data type, doesn’t work with INT
data type.

There are two wildcards often used in conjunction with the LIKE operator:

• The percent sign (%) represents zero, one, or multiple characters


• The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

Syntax:- SELECT column1,column2,...


FROM table_name
WHERE columnN LIKE pattern;

ORDER BY
It is used for sorting the data in Ascending or Descending order.
SYNTAX:- SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

EX:- Select DISTINCT First_Name From customer Ans:- AARON


Where first_name Like 'A%' ADAM
order by first_name ADRIAN
Limit 5; AGNES
ALAN

AUSTIN
Select DISTINCT First_Name From customer Ans:- AUDREY
Where first_name Like 'A%' ASHLEY
order by first_name DESC ARTHUR
Limit 5;
ARNOLD

NOTE:- Use “Order By” up to maximum 5 columns not more than this otherwise compiler
get destroyed or it will take more time.

NOTE:-

ORDER OF THE CLAUSE ORDER OF THE EXECUTION

Select <Columns> From <Table>

From <Table> Where <Condition>

Where <Condition> Group By <Columns>

Group By <Columns> Having <Condition>

Having <Condition> Select <Columns>

Order By <Sorting Columns> Order By <Sorting Columns>

Limit <Number> Limit <Number>


PRIMARY KEY & FOREIGN KEY
❖ Primary Key:

The PRIMARY KEY constraint uniquely identifies each record in a table.


Primary keys must contain UNIQUE values, and cannot contain NULL values. A
table can have only ONE primary key; and in the table, this primary key can consist
of single or multiple columns (fields).

The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY


KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

❖ Foreign Key:

The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables. A FOREIGN KEY is a field (or collection of fields) in one table,
that refers to the PRIMARY KEY in another table. The table with the foreign key is
called the child table, and the table with the primary key is called the referenced or
parent table. Look at the following two tables:

Persons Table

PersonID LastName FirstName Age

1 Hansen Ola 30
2 Svendson Tove 23

3 Pettersen Kari 20

Orders Table

OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table. The "PersonID" column in the "Persons"
table is the PRIMARY KEY in the "Persons" table. The "PersonID" column in the
"Orders" table is a FOREIGN KEY in the "Orders" table.

NOTE:- The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the parent table.

The following SQL creates a FOREIGN KEY on the "PersonID" column when
the "Orders" table is created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
JOINS IN MySQL
Introduction to Joins in MySQL

Joins are a powerful feature of SQL that allows you to combine data from two or more
tables in a database. With joins, you can retrieve data from related tables and combine it into
a single result set. SQL supports different types of joins, each of which is used for specific
scenarios.

Types of Joins in MySQL:

1. Inner Join
2. Left Join
3. Right Join

4. Natural Join
5. Cross Join

6. Self-Join

7. Full Outer Join

❖ Inner Join
The inner join is the most commonly used type of join in SQL. It returns only the
matching rows between two tables based on the join condition. The syntax for an inner
join is as follows:
The INNER JOIN keyword selects records that have matching values in both tables.

SYNTAX:- SELECT column_name(s)


FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
In this syntax, the INNER JOIN keyword is used to join two tables based on the
join condition specified by the ON clause. The result set will only contain the rows
where the join condition is true for both tables.

❖ Left Join

A left join returns all the rows from the left table and the matching rows from the
right table. If there is no matching row in the right table, the result set will contain null
values. The syntax for a left join is as follows:

The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records (if any) from the right table (table2).

SYNTAX:- SELECT column_name(s)


FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

In this syntax, the LEFT JOIN keyword is used to join two tables based on the
join condition specified by the ON clause. The result set will contain all the rows from
the left table and the matching rows from the right table. If there is no matching row in
the right table, the result set will contain null values.

❖ Right Join

A right join returns all the rows from the right table and the matching rows from
the left table. If there is no matching row in the left table, the result set will contain null
values. The syntax for a right join is as follows:
The RIGHT JOIN keyword returns all records from the right table (table2), and
the matching records (if any) from the left table (table1).

SYNTAX:-
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

❖ Natural Join

A natural join is a join that is performed based on the common column names
between two tables. It automatically matches the columns with the same name and
returns the result set.

SYNTAX:-

SELECT column_name(s)
FROM table1
NATURAL JOIN table2;

A natural join can be useful when you have two tables with similar data and you
want to combine them based on the common column names. However, it is important
to be careful with natural joins, as they can sometimes produce unexpected results if
the column names are not unique or if there are columns with the same name but
different data types.

❖ Cross Join

The CROSS JOIN keyword returns all records from both tables (table1 and table2).


SYNTAX:- SELECT column_name(s)
FROM table1
CROSS JOIN table2;
❖ Self Join
A self-join is a join that is performed on a single table. It is useful when you
want to combine data from the same table based on a join condition.
SYNTAX:- SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

The table is given different aliases "t1" and "t2" to differentiate between the two
instances of the table. The join condition is specified by the ON clause.

A self-join can be used to find relationships between data in the same table,
such as finding all employees who have the same manager, or finding all orders where
the billing and shipping addresses are the same.

❖ Full-Outer Join
AGGREGATE FUNCTIONS
❖ COUNT():- The COUNT() function returns the number of rows that matches a
specified criterion.
SELECT COUNT(*)
FROM Products;
❖ SUM:- The SUM() function returns the total sum of a numeric column.
SELECT SUM(column_name)
FROM table_name
WHERE condition;
❖ AVG():- The AVG() function returns the average value of a numeric column.
SELECT AVG(Column_Name)
FROM Table_Name
WHERE Condition;
❖ MAX() & MIN():- The MIN() function returns the smallest value of the selected
column. The MAX() function returns the largest value of the selected column.
SELECT MIN / MAX(Column_Name)
FROM Table_Name
WHERE Condition;
ORDER BY AND HAVING CLAUSE
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
SYNTAX:- SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

GROUP BY CLAUSE

The GROUP BY statement is used to group rows that have the same values into summary
rows, like "find the number of customers in each country". The GROUP BY statement is often
used with aggregate functions such as COUNT(), MAX(), MIN(), SUM(), AVG() to group the
result-set by one or more columns.

SELECT column_name(1),aggregate_functions(Column_Name(2))
FROM table_name
WHERE condition
GROUP BY column_name(1)
ORDER BY column_name(s);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy