SQL (Structured Query Language)
SQL (Structured Query Language)
Data:
Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data.
This is also known as structured form of data which can be accessed in many ways.
3. DBMS:
A Database Management System (DBMS) is a program that controls creation, maintenance and use of a
database. DBMS can be termed as File Manager that manages data in a database rather than saving it in
file systems.
4.) RDBMS:
RDBMS stands for Relational Database Management System. RDBMS store the data into the collection of
tables, which is related by common fields between the columns of the table. It also provides relational
operators to manipulate the data stored into the tables.
A table is a set of data that are organized in Columns and Rows. Columns can be categorized as vertical,
and Rows are horizontal. A table has specified number of column called fields but can have any number of
rows which is called record.
Example:.
Table Name : Employee.
An operator is a reserved character or word which is used in a SQL statement to query our database. We use a
WHERE clause to query a database using operators.Operators are needed to specify conditions in a SQL statement.
Types Operators
1. Arithmetic Operators + , -, *, /, %
● An expression is a combination of one or more values, operators and SQL functions used to query a database to get a
specific set of data.
● These SQL EXPRESSIONS are like formulae and they are written in query language.
There are different types of SQL expressions, which are mentioned below −
1. Boolean Expression:
SQL Boolean Expressions fetch the data based on matching a single value.
Syntax: SELECT column1, column2, columnN
FROM table_name
WHERE SINGLE VALUE MATCHING EXPRESSION;
E.g: SELECT * FROM CUSTOMERS WHERE SALARY = 10000;
2. Numeric Expression:
These expressions are used to perform any mathematical operation in any query.
Syntax: SELECT numerical_expression as OPERATION_NAME
[FROM table_name
WHERE CONDITION] ;
E.g: SELECT (15 + 6) AS ADDITION
3.) Date Expression:
● Data types are used to represent the nature of the data that can be stored in the database table.
● Each column in a database table is required to have a name and a data type.
● We must decide what type of data that will be stored inside each column when creating a table.
1. Numeric:
2.) Date & Time:
3.) String:
Constraints in SQL
1. NOT NULL:
● NULL means empty, i.e., the value is not available.
● Whenever a table's column is declared as NOT NULL, then the value for that column cannot be empty
for any of the table's records.
Syntax:
CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,…., ColumnNameN datatype);
E.g:
CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20));
2.) UNIQUE:
● Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.
● The column with the unique constraint will always contain a unique value.
● This constraint can be applied to one or more than one column of a table, which means more than one unique
constraint can exist on a single table.
● Using the UNIQUE constraint, you can also modify the already created tables.
Syntax:
CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,…., ColumnNameN datatype);
E.g:
Syntax:
CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,…., ColumnNameN datatype);
E.g:
CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20));
4. FOREIGN KEY
● A FOREIGN KEY in one table points to a PRIMARY KEY in another table. It is a referential constraint
between two tables.
● When we have two tables, and one table takes reference from another table, i.e., the same column is
present in both the tables and that column acts as a primary key in one table. That particular column will
act as a foreign key in another table.
Syntax:
E.g.:
CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_Salary VARCHAR (40));
5. CHECK
● Whenever a check constraint is applied to the table's column, and the user wants to insert the value in it,
then the value will first be checked for certain conditions before inserting the value into that column.
Syntax:
E.g.:
Syntax:
CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., ColumnNameN
datatype);
E.g:
StudentID INT,
Student_FirstName VARCHAR(20),
Student_LastName VARCHAR(20),
Student_PhoneNumber VARCHAR(20),
● Data Definition Language consists of the SQL commands that can be used to define the database schema.
● It is a set of SQL commands used to create, modify, and delete database structures but not data.
Creating a Database
● Creating a database:
USE database_name;
● Removing Databases:
Syntax:
E.g:
Syntax:
ALTER TABLE table_name change COLUMN old_name new_name datatype;
Syntax:
ALTER TABLE table_name DROP column_name ;
The RENAME TABLE and ALTER TABLE syntax helps us to change the name of the table.
● A truncate SQL statement is used to remove all rows (complete data) from a table.
● It is similar to the DELETE statement without WHERE clause.
● Truncate table is faster and uses less resources than DELETE TABLE command.
● Drop table command can also be used to delete complete table but it deletes table structure too.
● TRUNCATE TABLE doesn't delete the structure of the table.
● DROP TABLE statement is used to delete a table definition and all data from a table.
Once the tables are created and database is generated using DDL commands, manipulation inside those tables and databases is done using
DML commands.
INSERT COMMAND
[WHERE condition];
WHERE ID=101;
● The DELETE statement only deletes the rows from the table based on the condition
defined by WHERE clause or delete all the rows from the table when condition is not
specified.
● But it does not free the space containing by the table.
● The TRUNCATE statement: it is used to delete all the rows from the table and free the
containing space.
DATA QUERY LANGUAGE
● Data query language consists of command over which data selection in SQL relies.
● SELECT command in combination with other SQL clauses is used to retrieve and fetch data from
database/tables on the basis of certain conditions applied by user.
● By using this command, we can also access the particular record from the particular column of the
table.
● The table which stores the record returned by the SELECT statement is called a result-set table.
Syntax:
● To Select all attributes(columns) and tuples(rows) from a table:
The SQL DISTINCT command is used with SELECT keyword to retrieve only distinct or unique data.
Syntax:
SELECT DISTINCT column_name ,column_name
FROM table_name;
E.g:
SELECT DISTINCT city
FROM students;
‘ WHERE ’ Clause
Syntax:
SELECT column1, column2,..column N
FROM table_name
WHERE condition;
E.G:
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;
Where clause with Arithmetic operators Where clause with comparison operators
Logical Operators
● Logical SQL operators are used between queries or used to join two or more conditions.
● These operators compare two conditions at a time to determine whether a row can be selected for the output.
1. AND Operator:
Logical AND compares two Booleans as expression and returns TRUE when both of the conditions are TRUE and returns FALSE
when either is FALSE.
Syntax:
For Example:
To find the names of the students between the age 10 to 15 years, the query would be like:
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
For example:
To find the names of students who are studying either Maths or Science, the query would be like,
FROM student_details
● If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT.
● NOT results in the reverse of a condition.
● That is, if a condition is satisfied, then the row is not returned.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
For example:
To find out the names of the students who do not play football, the query would be like:
FROM student_details
● This operator displays the records which fall between the given ranges.
● The results of the BETWEEN operator include begin and end values of the given range.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
E.g:
➢ NOT BETWEEN:
To display the products outside a specific range we make use of NOT BETWEEN.
E.g: SELECT * FROM employees WHERE Salary NOT BETWEEN 5000 AND 9000;
5. IN Operator
● When we want to check for one or more than one value in a single SQL query, we use IN operator.
● The IN operator allows you to determine if a value matches any value in a list of values.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
➢ NOT IN operator:
● The NOT IN operator is used when we don't want to match certain values in the list.
E.g: SELECT * FROM employees WHERE age NOT IN (25, 27, 24);
6. LIKE Operator
● LIKE Operator in SQL displays only those data from the table which matches the pattern specified in the query.
● There are two wildcards used in conjunction with the LIKE operator:
Syntax:
E.g:
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
SQL NULL Values
● A field with a NULL value is a field with no value.
● It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
● We will have to use the ISNULL and IS NOT NULL operators instead.
IS NULL Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
E.g: SELECT *
FROM student
WHERE age IS NULL;
E.g: SELECT *
FROM student
WHERE age IS NOT NULL;
LIMIT Command
Syntax:
SELECT column_list
FROM table_name
LIMIT offset, count;
E.g:
SELECT * FROM Emp_info
LIMIT 3,7;
ORDER BY Clause
● The ORDER BY clause is used to sort the result-set in ascending or descending order.
● The ORDER BY clause sorts the records in ascending order by default.
● To sort the records in descending order, use the DESC keyword.
Syntax:
E.g:
SELECT * FROM Emp_info
ORDER BY City;
● SQL aliases are used to give a table, or a column in a table, a temporary name.
● Aliases are often used to make column names more readable.
● An alias only exists for the duration of that query.
● An alias is created with the AS keyword.
Syntax:
E.g:
1. String()
2. Math()
3. Date()
4. Aggregate()
1. STRING():
String methods in SQL are useful for processing the string data type or manipulation of string values.
2. Concat:
2. Lower: This function is used to convert the upper case character into lower case.
4. Replace: This function is used to replace all occurrences of the substring in a specified string with another string value.
Syntax: REVERSE(string)
Syntax: LENGTH(string)
7. Substring() : This function extracts a substring from a string that begins at a specific position and ends at a specific length.
8. Ltrim(): This function returns a string from a given string after removing all leading spaces.
Syntax: LTRIM(string)
9. Rtrim(): This function returns a string from a given string after removing all trailing spaces.
Syntax: RTRIM(string)
3. FLOOR(X): This returns the largest integer value that is either less than X or equal to it.
E.g: SELECT FLOOR(25.75)
SELECT FLOOR(-13.5)
4. CEIL(X): This returns the smallest integer value that is either more than X or equal to it.
E.g: SELECT CEILING(25.75)
SELECT CEILING(-13.5)
5. TRUNCATE(X,D): Returns the number X, truncated to D decimal places. If D is 0, the result has no decimal point or
fractional part.
SELECT TRUNCATE(123.321,-1)
6. EXP(X): The EXP() function returns e raised to the power of a specified number.
7. POWER(X,Y) : The POWER() function returns the value of a number raised to the power of another number.
Eg:
Syntax:
SELECT NOW();
Syntax:
SELECT SYSDATE();
4. Last_day(date): Returns the last day of the corresponding month for a date or datetime value.
Syntax:
Select last_day(date);
E.g:
Select last_day(‘2022-03-12’);
5. Date_format(date, format): To format a date value to a specific format, you use the DATE_FORMAT function.
Syntax:
DATE_FORMAT(date,format)
E.g:
DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
6. DATEDIFF(): The DATEDIFF() function returns the time between two dates.
Syntax: DATEDIFF(date1,date2)
8. YEAR(date): Returns the year for date, in the range 1000 to 9999, or 0 for the
"zero" date.
E.g:
Select avg(salary) as avg_sal from emp_info;
2. Count(): The COUNT() function returns the number of rows in a database table.
Syntax:
Select count(column_name) from table_name;
E.g:
Select count(name) from emp_info;
3. Max(): The MAX() function returns the maximum value of the selected column.
4. Min(): The MIN() function returns the minimum value of the selected column.
Syntax:
SELECT MIN(column_name) FROM table_name;
E.g:
Select min(age) from emp_info;
5. Sum(): The SUM() function returns the total sum of a numeric column.
Syntax:
SELECT SUM(column_name) FROM table_name;
E.g:
Select sum(age) from emp_info;
Scalar Functions
The Scalar Functions in SQL are used to return a single value from the given input value.
Comparison Functions
E.g:
Select isnull(1+1);
select isnull(1/0);
2. GREATEST(value1,value2,...) / LEAST(value1, value2,...): With two or more arguments, returns the largest
(maximum-valued) argument. The arguments are compared using the same rules as for LEAST().
Select least(12,10,36)
3. IF(expr1,expr2,expr3): If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it
returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.
E.g:
Select if (20>10,’yes’,’no’);
‘ Group By ‘ Clause
● The Group By statement is used along with the select statement for organizing similar data into groups.
● It is a command that is used to group rows that have the same values.
● The GROUP BY clause is used in the SELECT statement. Optionally it is used in conjunction with aggregate
functions to produce summary reports from the database.
● It is used to summarize data from the database.
Points to remember:
● The SELECT statement is used with the GROUP BY clause in the SQL query.
● WHERE clause is placed before the GROUP BY clause in SQL.
● ORDER BY clause is placed after the GROUP BY clause in SQL.
Syntax:
Note: If the age is the same but the city is different, then a row is treated as a unique one .If the age and the
city is the same for more than one row, then it’s considered a duplicate and only one row is shown.
3. Group by with min() function:
The HAVING clause places the condition in the groups defined by the GROUP BY clause in the SELECT statement.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups
created by the GROUP BY clause.
Syntax:
SELECT column_Name1, column_Name2, ....., column_NameN aggregate_function_name(column_Name)
FROM table_name
GROUP BY column_Name1
HAVING condition;
Eg.
select sum(salary),city from emp_info
group by city
having sum(salary)>10000;
1. Using sum() function:
4. Using max() function:
SELECT designation, SUM(salary)
FROM emp_info SELECT designation, Max(salary)
GROUP BY designation FROM emp_info
GROUP BY designation
HAVING SUM(salary) > 10000;
HAVING Max(salary) > 5000;
2. Using Count() function:
SELECT designation, COUNT(*)
FROM emp_info
WHERE salary > 2000
GROUP BY designation
HAVING COUNT(*) > 2;
● The subquery returns only one row i.e It returns only one row from the inner select statement.
● Use single row comparison operators like =, > etc while doing comparisons.
When we want to find out the employees of an office in which GEORGE is working.
Once it returns the office code (let us say 3) you would then give
SELECT firstName, lastName FROM employees
WHERE officeCode = 3;
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES
SELECT SALARY
FROM EMPLOYEES
)
2. Write a query to find the employees who all are earning the highest salary?
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES
WHERE SALARY =
SELECT MAX(SALARY)
FROM EMPLOYEES
)
3. Write a query to find the departments in which the least salary is greater than the highest salary
in the department of id 200?
SELECT DEPARTMENT_ID,
MIN(SALARY)
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
SELECT MAX(SALARY)
FROM EMPLOYEES
)
Multiple Row Subqueries
● They are queries that return more than one row from the inner select statement.
● You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.
E.g: Display all the employees who are in same office as ‘Tom’ or ‘Martin’.
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES
WHERE SALARY IN
SELECT SALARY
FROM EMPLOYEES
)
2. Write a query to find the employees whose salary is greater than at least on employee in
department of id 500?
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES
SELECT SALARY
FROM EMPLOYEES
)
3.) Write a query to find the employees whose salary is less than the salary of all employees in
department of id 100?
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES
SELECT SALARY
FROM EMPLOYEES
)
Multiple Column Subquery
● A multiple-column subquery returns more than one column to the outer query and can be listed in the
outer query's FROM, WHERE, or HAVING clause.
For example:
Display employee details for the ones whose current salary is in range of 1000 and 2000 and working in
department 10 or 20.
SELECT first_name, job_id, salary
FROM emp_history
WHERE (salary, department_id) in (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000
AND department_id BETWEEN 10 and 20)
ORDER BY first_name;
Write a query to find the employees whose manager and department should match with the employee of id 20 or
30?
SELECT EMPLOYEE_ID,
MANAGER_ID,
DEPARTMENT_ID
FROM EMPLOYEES
WHERE (MANAGER_ID,DEPARTMENT_ID) IN
SELECT MANAGER_ID,
DEPARTMENT_ID
FROM EMPLOYEES
)
DML with Subqueries
For E.g:
● The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the Update statement, then
either single or multiple columns in a table can be updated.
UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 29);
3. Subqueries with DELETE:
● The foreign key is used to link one or more than one table together. It is also known as the
referencing key.
● In simple words you can say that, a foreign key in one table used to point primary key in another
table.
● It means a foreign key field in one table refers to the primary key field of the other table.
● It identifies each row of another table uniquely that maintains the referential integrity in MySQL.
● A foreign key makes it possible to create a parent-child relationship with the tables.
● In this relationship, the parent table holds the initial column values, and column values of child table
reference the parent column values.
● MySQL allows us to define a foreign key constraint on the child table.
[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (col_name, ...)
REFERENCES parent_tbl_name (col_name,...)
ON DELETE referenceOption
ON UPDATE referenceOption
CASCADE: It is used when we delete or update any row from the parent table, the values of the matching rows in the child table will be
deleted or updated automatically.
RESTRICT: It is used when we delete or update any row from the parent table that has a matching row in the reference(child) table, MySQL
does not allow to delete or update rows in the parent table.
SET NULL: With this ON UPDATE and ON DELETE clauses option, if the referenced values in the parent table are deleted or modified, all
related values in the child table are set to NULL value.
NO ACTION: When the ON UPDATE or ON DELETE clauses are set to NO ACTION, the performed update or delete operation in the parent
table will fail with an error.
• create database data1;
• use dh1;
• create table demo1(id int,name varchar(66),primary key(id));
• insert into demo1 values(1,'Aditi');
• insert into demo1 values(2,'simran');
• select * from demo1;
• create table emp(e_id int,name varchar(88),id int,primary key(e_id),foreign key(id)references demo1(id));
• insert into emp values(11,'xyz',1);
• insert into emp values(13,'pqr',2);
• select * from emp;
• create table stud(s_id int,s_name varchar(88),age int,id int,e_id int,primary key(s_id),foreign
key(id)references demo1(id),foreign key(e_id)references emp(e_id));
• insert into stud values(111,'amit',9,1,11);
• insert into stud values(112,'riya',9,1,11);
• select * from stud;
2. Using ALTER TABLE Statement:
ALTER TABLE Contact ADD CONSTRAINT fk_person
FOREIGN KEY ( Person_Id ) REFERENCES Person ( ID ) ON DELETE CASCADE ON UPDATE RESTRICT;
Table: Person
Table: Contact
Syntax:
ALTER TABLE table_name DROP FOREIGN KEY fk_constraint_name;
For eg:
A SQL Join statement is used to combine data or rows from two or more tables based on a common field between
them. Different types of Joins are:
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN (Using ‘UNION’ in mysql)
5. CROSS JOIN
6. SELF JOIN
create table student1(roll_no int,name varchar(20),address varchar(20),age int,primary key(roll_no));
create table course(course_id int,roll_no int,CONSTRAINT FKP FOREIGN KEY FK_C(ROLL_NO)
REFERENCES STUDENT1(ROLL_NO));
1. INNER JOIN:
The INNER JOIN keyword selects all rows from both the
tables as long as the condition satisfies. i.e value of the
common field will be same.
Syntax: SELECT
table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Select student1.roll_no,course.course_id,
student1.name,student1.age
from student1 INNER JOIN course
ON student1.roll_no=course.roll_no;
2. LEFT JOIN:
● This join returns all the rows of the table on the left side
of the join and matching rows for the table on the right
side of join.
● The rows for which there is no matching row on right
side, the result-set will contain null.
● LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.
FROM table1
LEFT JOIN table2
ON table1.matching_column =table2.matching_column;
select student1.roll_no,course.course_id,
student1.name,student1.age
from student1 LEFT JOIN course
ON student1.roll_no=course.roll_no;
3. RIGHT JOIN:
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
select student1.roll_no,course.course_id,
student1.name,student1.age
from student1 RIGHT JOIN course
ON student1.roll_no=course.roll_no;
4. FULL JOIN:
select student1.roll_no,course.course_id,
student1.name,student1.age
from student1 LEFT JOIN course
ON student1.roll_no=course.roll_no
UNION
select student1.roll_no,course.course_id,
student1.name,student1.age
from student1 RIGHT JOIN course
ON student1.roll_no=course.roll_no;
5. CROSS JOIN: select course.course_id,student1.name,
student1.age
● Join operation in SQL is used to combine multiple
from student1 CROSS JOIN course;
tables together into a single table.
● If we use the cross join to combine two different tables,
then we will get the Cartesian product of the sets of
rows from the joined table. When each row of the first
table is combined with each row from the second table,
it is known as Cartesian join or cross join.
● After performing the cross join operation, the total
number of rows present in the final table will be equal to
the product of the number of rows present in table 1
and the number of rows present in table 2.
SELECT TableName1.columnName1,
TableName2.columnName2 FROM TableName1 CROSS JOIN
TableName2 ON TableName1.ColumnName =
TableName2.ColumnName;
6. SELF JOIN:
Syntax:
SELECT s1.col_name, s2.col_name...
FROM table1 s1, table1 s2
WHERE s1.common_col_name = s2.common_col_name;
ON e1.emp_id=e2.manager_id;
VIEWS
● Views in SQL are kind of virtual tables.
● A view also has rows and columns as they are in a real table in the database.
● We can create a view by selecting fields from one or more tables present in the database.
● A View can either have all the rows of a table or specific rows based on certain condition.
Creating view:
A view can be created using the CREATE VIEW statement. We can create a view from a single table or
multiple tables.
Syntax:
update emp_view
set name='prachi'
where manager_id=4;
Deleting from a view:
Drop a View: