SQL Foundation
SQL Foundation
SQL Foundation
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
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)
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:- 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
❖ 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 …
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():
This will return a new column called first_three that contains the first three
characters of the first_name column.
❖ Numeric functions:
1. ROUND():
For example, to round the salary column in a table to two decimal places, you
can use the following SQL query:
This will return a new column called rounded_salary that contains the salary
column rounded to two decimal places.
2. CEILING():
(It gives the result upto 2 decimal places with Mathematical Logic)
5. SQRT():
6. TRUNCATE():
EX:-
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:
2. YEAR:
The YEAR function is used to extract the year portion of a date/time value. The
syntax is as follows:
3. MONTH:
The MONTH function is used to extract the month portion of a date/time value.
The syntax is as follows:
Select MONTHNAME(datetime_expression)
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:
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:-
NOTE:- We can write the above temporal function just like this also with the help of
EXTRACT function.
6. DATE_ADD:
The DATEADD() function adds a time/date interval to a date and then returns
the date.
7. DATEDIFF:
For Negative result we need to convert into absolute positive value. For that we
will use ABS function.
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.
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.
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.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign and the underscore can also be used in combinations!
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;
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:-
The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
❖ 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
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
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:
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.
1. Inner Join
2. Left Join
3. Right Join
4. Natural Join
5. Cross Join
6. Self-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.
❖ 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).
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);