unit 1 sql
unit 1 sql
UNIT I
Relational Database:
A relational database is a collection of information that organizes data in predefined relationships
where data is stored in one or more tables (or "relations") of columns and rows, making it easy to
see and understand how different data structures relate to each other.
Database:
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database management
system (DBMS).
Data Table:
A data table is a document comprising columns, rows and cells that contain specific values. They
store information that people can retrieve later and update as needed. The data table title, column
headers and row headers can help a user understand the information in the table more clearly.
Data:
In computing, data is information that has been translated into a form that is efficient for movement
or processing. Data, in the context of databases, refers to all the single items that are stored in a
database, either individually or as a set. Data in a database is primarily stored in database tables,
which are organized into columns and rows.
Introduction to RDBMS:
RDBMS (Relational Database Management System)
RDBMS stands for Relational Database Management System.
All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE, My-
SQL, and Microsoft Access are based on RDBMS.
It is called Relational Database Management System (RDBMS) because it is based on the
relational model introduced by E.F. Codd. (Edgar F. Codd)
How it works :
Data is represented in terms of tuples (rows) in RDBMS.
A relational database is the most commonly used database. It contains several tables, and each
table has its primary key.
Due to a collection of an organized set of tables, data can be accessed easily in RDBMS.
12 Codd's Rules:
Every database has tables and constraints cannot be referred to as a rational database system.
And if any database has only relational data model, it cannot be a Relational Database System
(RDBMS). So, some rules define a database to be the correct RDBMS. These rules were
developed by Dr Edgar F. Codd (E.F. Codd) in 1985, who has vast research knowledge on the
Relational Model of database Systems. Codd presents his 13 rules for a database to test the
concept of DBMS against his relational model, and if a database follows the rule, it is called a true
relational database (RDBMS). These 13 rules are popular in RDBMS, known as Codd's 12 rules.
Rule 0: The Foundation Rule -The database must be in relational form. So that the system can
handle the database through its relational capabilities.
Rule 1: Information Rule -A database contains various information, and this information must be
stored in each cell of a table in the form of rows and columns.
Rule 2: Guaranteed Access Rule -Every single or precise data (atomic value) may be accessed
logically from a relational database using the combination of primary key value, table name, and
column name.
Rule 3: Systematic Treatment of Null Values -This rule defines the systematic treatment of Null
values in database records. The null value has various meanings in the database, like missing the
data, no value in a cell, inappropriate information, unknown data and the primary key should not
be null.
Rule 4: Active/Dynamic Online Catalog based on the relational model - It represents the
entire logical structure of the descriptive database that must be stored online and is known as a
database dictionary. It authorizes users to access the database and implement a similar query
language to access the database.
Rule 5: Comprehensive Data Sub Language Rule- The relational database supports various
languages, and if we want to access the database, the language must be the explicit, linear or
well-defined syntax, character strings and supports the comprehensive: data definition, view
definition, data manipulation, integrity constraints, and limit transaction management operations. If
the database allows access to the data without any language, it is considered a violation of the
database.
Rule 6: View Updating Rule - All views table can be theoretically updated and must be practically
updated by the database systems.
Rule 7: Relational Level Operation (High-Level Insert, Update and delete) Rule -A database
system should follow high-level relational operations such as insert, update, and delete in each
level or a single row. It also supports union, intersection and minus operation in the database
system.
Rule 8: Physical Data Independence Rule- All stored data in a database or an application must
be physically independent to access the database. Each data should not depend on other data or
an application. If data is updated or the physical structure of the database is changed, it will not
show any effect on external applications that are accessing the data from the database.
Rule 9: Logical Data Independence Rule-It is similar to physical data independence. It means, if
any changes occurred to the logical level (table structures), it should not affect the user's view
(application). For example, suppose a table either split into two tables, or two table joins to create
a single table, these changes should not be impacted on the user view application.
Rule 10: Integrity Independence Rule -A database must maintain integrity independence when
inserting data into table's cells using the SQL query language. All entered values should not be
changed or rely on any external factor or application to maintain integrity. It is also helpful in
making the database-independent for each front-end application.
Rule 11: Distribution Independence Rule-The distribution independence rule represents a
database that must work properly, even if it is stored in different locations and used by different
end-users. Suppose a user accesses the database through an application; in that case, they
should not be aware that another user uses particular data, and the data they always get is only
located on one site. The end users can access the database, and these access data should be
independent for every user to perform the SQL queries.
Rule 12: Non-Subversion Rule - The non-submersion rule defines RDBMS as a SQL language
to store and manipulate the data in the database. If a system has a low-level or separate language
other than SQL to access the database system, it should not subvert or bypass integrity to
transform data.
Limitations of SQL:
It is able to execute only one SQL command at a time
It is not possible to express all sorts of user queries using SQL as it does not support the full
flagged capability of procedural language.
Need of SQL:
● It is widely used in the Business Intelligence tool.
● Data Manipulation and data testing are done through SQL.
● Data Science tools depend highly on SQL. Big data tools such as Spark, Impala are
dependent on SQL.
● It is one of the demanding industrial skills.
Advantages of SQL:
SQL has many advantages which makes it popular and highly demanded. It is a reliable and
efficient language used for communicating with the database. Some advantages of SQL are as
follows:
1. Faster Query Processing: Large amount of data is retrieved quickly and efficiently.
Operations like Insertion, deletion, manipulation of data is also done in almost no time.
2. No Coding Skills: For data retrieval, large number of lines of code is not required. All basic
keywords such as SELECT, INSERT INTO, UPDATE, etc are used and also the syntactical
rules are not complex in SQL, which makes it a user-friendly language.
3. Standardized Language: Due to documentation and long establishment over years, it
provides a uniform platform worldwide to all its users.
4. Portable: It can be used in programs in PCs, server, laptops independent of any platform
(Operating System, etc). Also, it can be embedded with other applications as per
need/requirement/use.
5. Interactive Language: Easy to learn and understand, answers to complex queries can be
received in seconds.
6. Multiple data views
7. Scalability: SQL databases can handle large volumes of data and can be scaled up or down
as per the requirements of the application.
8. Security: SQL databases have built-in security features that help protect data from
unauthorized access, such as user authentication, encryption, and access control.
9. Data Integrity: SQL databases enforce data integrity by enforcing constraints such as
unique keys, primary keys, and foreign keys, which help prevent data duplication and
maintain data accuracy.
10. Backup and Recovery: SQL databases have built-in backup and recovery tools that help
recover data in case of system failures, crashes, or other disasters.
11. Data Consistency: SQL databases ensure consistency of data across multiple tables
through the use of transactions, which ensure that changes made to one table are
reflected in all related tables.
Disadvantages of SQL:
Although SQL has many advantages, still there are a few disadvantages.
Various Disadvantages of SQL are as follows:
1. Complex Interface: SQL has a difficult interface that makes few users uncomfortable while
dealing with the database.
2. Cost: Some versions are costly and hence, programmers cannot access it.
3. Partial Control: Due to hidden business rules, complete control is not given to the
database.
4. Limited Flexibility: SQL databases are less flexible than NoSQL databases when it comes
to handling unstructured or semi-structured data, as they require data to be structured into
tables and columns.
5. Lack of Real-Time Analytics: SQL databases are designed for batch processing and do not
support real-time analytics, which can be a disadvantage for applications that require real-
time data processing.
6. Limited Query Performance: SQL databases may have limited query performance when
dealing with large datasets, as queries may take longer to process than in-memory
databases.
7. Complexity: SQL databases can be complex to set up and manage, requiring skilled
database administrators to ensure optimal performance and maintain data integrity.
Elements of SQL
Following are the major elements of SQL, which we will discuss in the subsequent chapters,
1) Database Objects
2) Keywords/Reserved Words
3) Operators
4) Expression
5) Variables
6) Constants
For Ex. Consider the following query
SQL> SELECT EMPNO, ENAME, 12 * SAL FROM EMP WHERE JOB=’MANAGER’ AND
SAL>&VSAL;
Here,
EMP is a table that is a database object.
SELECT, FROM, WHERE are keywords.
*,> are operators.
12 * SAL is an Expression.
VSAL is variable.
12,’MANAGER’ are constant value.
DATABASE OBJECTS
Physical database design consists of defining database objects and their relationships.
You can create the following database objects in a DB2 database:
Tables
Constraints
Indexes
Triggers
Sequences
Views
You can use Data Definition Language (DDL) statements or tools such as IBM® Data Studio to
create these database objects. The DDL statements are generally prefixed by the keywords
CREATE or ALTER.
Understanding the features and functionality that each of these database objects provides is
important to implement a good database design that meets your current business's data storage
needs while remaining flexible enough to accommodate expansion and growth over time.
Concepts Common To Most Database Objects :
Tables: Tables are logical structures maintained by the database manager and are made up of
columns and rows. DB2 databases store persistent data in tables, but there are also tables that
are used for presenting results, summary tables and temporary tables.
Constraints Within any business, data must often adhere to certain restrictions or rules. For
example, an employee number must be unique. The database manager provides constraints as a
way to enforce such rules.
Indexes: An index is a set of pointers that are logically ordered by the values of one or more keys.
The pointers can refer to rows in a table, blocks in an MDC or ITC table, XML data in an XML
storage object, and so on.
Triggers: A trigger defines a set of actions that are performed in response to an insert, update, or
delete operation on a specified table. When such an SQL operation is executed, the trigger is said
to have been activated. Triggers are optional and are defined using the CREATE TRIGGER
statement.
Sequences: A sequence is a database object that allows the automatic generation of values, such
as cheque numbers. Sequences are ideally suited to the task of generating unique key values.
Applications can use sequences to avoid possible concurrency and performance problems
resulting from column values used to track numbers. The advantage that sequences have over
numbers created outside the database is that the database server keeps track of the numbers
generated. A crash and restart will not cause duplicate numbers from being generated.
Views: A view is an efficient way of representing data without the need to maintain it. A view is not
an actual table and requires no permanent storage. A "virtual table" is created and used.
Cursors: A cursor is used in an application program to select a set of rows and then process that
returned data one row at a time. When a SELECT statement in an embedded SQL application
returns multiple rows of data, you need a mechanism that makes this returned data or result set
available to your application program, one row after another.
Reserved words:
Microsoft SQL Server uses reserved keywords for defining, manipulating, and accessing
databases. Reserved keywords are part of the grammar of the Transact-SQL language that is
used by SQL Server to parse and understand Transact-SQL statements and batches. Although it
is syntactically possible to use SQL Server reserved keywords as identifiers and object names in
Transact-SQL scripts, you can do this only by using delimited identifiers.
The following table lists SQL Server and Azure Synapse Analytics reserved keywords.
ADD EXTERNAL PROCEDURE
ALL FETCH PUBLIC
DATA TYPES:
A data type helps the user to know what kind of data the column or field of table or cluster or
variable can hold. When we create a procedure or function. We must specify a data type for each
of its arguments. Oracle supports the following Internal Data Types.
1.NUMBER(P,S): variable length numeric having precision (P) in the range 1-38 and scale(S) in
the range -84 to 127, Specification of precision (P) and scale is optional as Oracle assumes the
maximum range of both the values. It is also used to store signed integers, Fixed point numbers ,
and the floating point numbers.
Eg. 1) empno number(2)
2) sal number(7,2)
Points to remember while working with number data type:
1) If precision and scale are not specified then it assumes a maximum range for both the values i.e
for P and S.
2) Scale (s) rounds the value after the decimal point to S digits.
3) If the scale is negative, S number of zeros are placed left of the decimal.
4) If the scale value is greater than precision value, (S-P) zeros are required after decimal.
5) If the value exceeds the precision an error is generated.
NUMBER SUBTYPES: the following subtypes can be used during defining a Number of Data
types.
INTEGER, SMALLINT, INT are used to insert integer values.
FLOAT, REAL is used to insert floating values.
2. DATE: this data type is used to store data and time information. Oracle software is the year
2000(Y2K) complaint i.e when a new row is inserted into the table for a data column , the century
information is picked up from the SYSDATE function . Oracle stores date data a number in an
internal numeric format, representing the Century, Year, Month, Day, Hours Minutes and Seconds
and store date in a fixed-length of & bytes. The default format of date is DD/MON/YY and it can be
modified by changing the NLS_DATE_FORMAT parameters in init.ora file. Using date conversion
function users can view the date in different formats.
Valid dates are between 1-JAN-4712 B.C to 31-DEC-9999 A.D
3. RAW(size): It is useful to store binary data and is used to store a graphic or digitized picture.
Maximum 2000 bytes can be allotted for the RAW type column. One must specify
The size . Only storage and retrieval of data are possible using this data type and one cannot
manipulate the data but it can be indexed
4. LONG RAW: it is the same as the RAW data type but it can store raw binary data type up to 2
Gigabytes.
5. ROWID and UROWID: It is binary representation of the physical address of a row, which is
displayed in hexadecimal format. UROWID(Universal Rowid) data type can store physical, Logical
and foreign (Non-Oracle) rowids.
7.CHAR(size): It is a fixed length character datatype of length size bytes. The Maximum size is
2000 bytes. The default and minimum size is 1 byte when size is not specified. A value ‘ram’ is not
the same as ‘RAM’ or Ram i.e data/vales are case sensitive in Oracle.
9. LOB data type: Oracle 8 onwards supports the LOB data type. It is known as large Object data
types. It is used to store un-structured information like sound clips, videos files, etc. upto 4 GB.
It stores the location of large objects, The DBMS _LOB package can be used to manipulate
LOB
bit 0 1
DATETIME A data type is used to store both the data, date, and time in the record.
SQL Constraints
A constraint refers to a condition or check that is applied on a column or a table to maintain data
integrity and helps in inserting valid values for a column. SQL constraints are used to specify rules
for data in a table.Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE statement. Constraints are
used to limit the type of data that can go into a table. This ensures the accuracy and reliability of
the data in the table. If there is any violation between the constraint and the data action, the action
is aborted. Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
If you don’t want to have a null column or a null value you need to define constraintslike NOT
NULL. NOT NULL constraints make sure that a column does not hold null values, or in other
words, NOT NULL constraints make sure that you cannot insert a new record or update a record
without entering a value to the specified column(i.e., NOT NULL column).
Unique constraint in SQL is used to check whether the sub-query has duplicate tuples in its
result. It returns a Boolean value indicating the presence/absence of duplicate tuples. Unique
construct returns true only if the subquery has no duplicate tuples, else it returns false.
Syntax:
CREATE TABLE table_name (column1 datatype UNIQUE, column2 datatype,…);
It means that in that particular column, the data should be unique.We can directly calculate the
unique data in the column without using unique data words in SQL but the UNIQUE keyword
ease the complexity.Suppose that we have one table in which we have to calculate the unique
data in the ID column.
Query:
SELECT table.IDFROMtableWHERE UNIQUE (SELECT table2.IDFROM table2WHERE table.ID
= table2.ID);
SQL Unique Constraint on ALTER Table
We can add a unique column in a table using ALTER.Suppose that we have one table with the
named instructor and we want to insert one unique column in the instructor.
Syntax:
ALTER TABLE Instructor ADD UNIQUE(ID);
To DROP a Unique Constraint
Suppose we have to DROP that column, particularly in the table.
Syntax:
ALTER TABLE InstructorDROP INDEX ID;
The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will
be added to all new records when no other value is provided.
Syntax
CREATE TABLE tablename (Columnname DEFAULT ‘defaultvalue’);
Using DEFAULT on CREATE TABLE
To set a DEFAULT value for the “Location” column when the “Geeks” table is created.
Query:
CREATE TABLE Geeks (ID int NOT NULL, Name varchar(255),Age int,Location varchar(255)
DEFAULT 'Noida');
INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi');
INSERT INTO Geeks VALUES (5, 'Hema', 27,DEFAULT);
INSERT INTO Geeks VALUES (6, 'Neha', 25, 'Delhi');
INSERT INTO Geeks VALUES (7, 'Khushi', 26,DEFAULT);
Select * from Geeks;
Output:
Foreign Key is a column that refers to the primary key/unique key of other table. So it
demonstrates relationship between tables and act as cross reference among them. Table in
which foreign key is defined is called Foreign table/Referencing table. Table that defines
primary/unique key and is referenced by foreign key is called primary table/master table/
Referenced Table. It is Defined in Create table/Alter table statement.
For the table that contains Foreign key, it should match the primary key in referenced table for
every row. This is called Referential Integrity. Foreign key ensures referential integrity.
Properties:
Parent that is being referenced has to be unique/Primary Key.
Child may have duplicates and nulls.
Parent record can be deleted if no child exists.
Master table cannot be updated if child exists.
Must reference PRIMARY KEY in primary table.
Foreign key column and constraint column should have matching data types.
Records cannot be inserted in child table if corresponding record in master table do not
exist.
Records of master table cannot be deleted if corresponding records in child table exits.
1. SQL Foreign key At column level :
Syntax –
Create table people (no int references person, Fname varchar2(20));
OR
Create table people (no int references person(id), Fname varchar2(20));
Here Person table should have primary key with type int. If there is single columnar Primary key
in table, column name in syntax can be omitted. So both the above syntax works correctly.
To check the constraint,
If Parent table doesn’t have primary key.
OUTPUT :
Error at line 1 : referenced table does not have a primary key.
If Parent table has Primary Key of different datatype.
OUTPUT :
Error at line 1 : column type incompatible with referenced column type.
2. SQL Foreign key At table level :
Syntax –
create table people(no varchar2(10),fname varchar2(20), foreign key(no) references person);
OR
create table people(no varchar2(10), fname varchar2(20), foreign key(no) references person(id));
Column name of referenced table can be ignored.
Check Constraint is used to specify a predicate that every tuple must satisfy in a given relation.
It limits the values that a column can hold in a relation.
The predicate in check constraint can hold a sub query.
Check constraint defined on an attribute restricts the range of values for that attribute.
If the value being added to an attribute of a tuple violates the check constraint, the check
constraint evaluates to false and the corresponding update is aborted.
Check constraint is generally specified with the CREATE TABLE command in SQL.
Syntax:
CREATE TABLE pets(ID INT NOT NULL,Name VARCHAR(30) NOT NULL,Breed
VARCHAR(20) NOT NULL,Age INT,GENDER VARCHAR(9),PRIMARY
KEY(ID),check(GENDER in ('Male', 'Female', 'Unknown')));
Note: The check constraint in the above SQL command restricts the GENDER to belong to only
the categories specified. If a new tuple is added or an existing tuple in the relation is updated
with a GENDER that doesn’t belong to any of the three categories mentioned, then the
corresponding database update is aborted.
Query: Constraint: Only students with age >= 17 are can enroll themselves in a
CREATE TABLE student (Student_ID INT NOT NULL,Name VARCHAR(30) NOT NULL,Age INT
NOT NULL,GENDER VARCHAR(9),PRIMARY KEY(ID),check(Age >= 17));
Student relation:
Ag
StudentID Name e Gender
1001 Ron 18 Male
1002 Sam 17 Male
1003 Georgia 17 Female
1004 Erik 19 Unknown
1005 Christine 17 Female
A primary key constraint depicts a key comprising one or more columns that will help uniquely
identify every tuple/record in a table.
Properties:
1. No duplicate values are allowed, i.e. Column assigned as primary key should have
UNIQUE values only.
2. NO NULL values are present in column with Primary key. Hence there is Mandatory value
in column having Primary key.
3. Only one primary key per table existalthough Primary key may have multiple columns.
4. No new row can be inserted with the already existing primary key.
5. Classified as: a) Simple primary key that has a Single column 2) Composite primary key
has Multiple column.
6. Defined in Create table / Alter table statement.
The primary key can be created in a table using PRIMARY KEY constraint. It can be created at
two levels.
1. Column
2. Table.
SQL PRIMARY KEY at Column Level:
If Primary key contains just one column, it should be defined at column level. The following code
creates the Primary key “ID” on the person table.
Syntax:
Create Table Person
(
Id int NOT NULL PRIMARY KEY,
Name varchar2(20),
Address varchar2(50)
);
Here NOT NULL is added to make sure ID should have unique values. SQL will automatically
set null values to the primary key if it is not specified.
Example-1:
To verify the working of Primary key:
Insert into Person values(1, 'Ajay', 'Mumbai');
Output:
1 row created
Example-2:
Let’s see if you will insert the same values again.
Insert into Person values(1, 'Ajay', 'Mumbai');
Output:
Error at line 1: unique constraint violated
Since we are inserting duplicate values, an error will be thrown since the Primary key “Id” can
contain only unique values.
Example-3:
Insert into Person values('', 'Ajay', 'Mumbai');
Output:
Error at line 1: cannot insert Null into<"user"."Person"."ID">
Primary Key cannot contain Null Values so That too will throw an error.
SQL Sub Languages: SQL commands are like instructions to a table. It is used to interact with the database
with some operations. It is also used to perform specific tasks, functions, and queries of data. SQL can
perform various tasks like creating a table, adding data to tables, dropping the table, modifying the table, set
permission for users.
These SQL commands are mainly categorized into five categories:
1. DDL – Data Definition Language
1. DQL – Data Query Language
1. DML – Data Manipulation Language
1. DCL – Data Control Language
1. TCL – Transaction Control Language
DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. It simply deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database. DDL is a set of SQL commands used to create, modify, and
delete database structures but not data. These commands are normally not used by a general user, who
should be accessing the database via an application.
ROLLBACK: Rollbacks a transaction in case of any error occurs. (To undo all DML operations up to last
save)
Syntax:
ROLLBACK;
Example: Create table blood and insert 3 records and delete one record. Set a Save point after every
insertion and deletion of a record into the table. At the end, view the result of each rollback up to Save Point.
Logical Functions:
SQL provides a set of logical functions that return a Boolean value, which can be either true or false. Some
examples of logical functions in SQL include −
AND - Returns true if both the conditions are true
OR - Returns true if at least one of the conditions is true
NOT - Negates a Boolean value
Here's an example of using the AND function to find all customers who live in a specific city and have an
account balance greater than a certain amount −
SELECT customer_name, city, account_balance
FROM customers
WHERE city ='New York' AND account_balance>1000;
SQL Clauses
o SQL clause helps us to retrieve a set or bundles of records from the table.
o SQL clause helps us to specify a condition on the columns or the records of a table.
Different clauses available in the Structured Query Language are as follows:
1. WHERE CLAUSE
2. GROUP BY CLAUSE
3. HAVING CLAUSE
4. ORDER BY CLAUSE
Let's see each clause one by one with an example.
1. WHERE CLAUSE
A WHERE clause in SQL is used with the SELECT query, which is one of the data manipulation language
commands. WHERE clauses can be used to limit the number of rows to be displayed in the result set, it
generally helps in filtering the records. It returns only those queries which fulfill the specific conditions of
the WHERE clause. WHERE clause is used in SELECT, UPDATE, DELETE statement, etc.
WHERE clause with SELECT Query
Asterisk symbol is used with a WHERE clause in a SELECT query to retrieve all the column values for
every record from a table.
Syntax of where clause with a select query to retrieve all the column values for every record from a
table:
SELECT * FROM TABLENAME WHERE CONDITION;
If according to the requirement, we only want to retrieve selective columns, then we will use below
syntax:
SELECT COLUMNNAME1, COLUMNNAME2 FROM TABLENAME WHERE CONDITION;
Consider the employee table with the following data:
Date_of_Joi
E_ID Name Salary City Designation Age
ning
1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24
As per the expected output, only those records are displayed where an employee's salary is greater than
50000. There are six records in the employee's table which satisfy the given condition.
2. GROUP BY CLAUSE
The Group By clause is used to arrange similar kinds of records into the groups in the Structured Query
Language. The Group by clause in the Structured Query Language is used with Select Statement. Group by
clause is placed after the where clause in the SQL statement. The Group By clause is specially used with the
aggregate function, i.e., max (), min (), avg (), sum (), count () to group the result based on one or more than
one column.
The syntax of Group By clause:
SELECT * FROM TABLENAME GROUP BY COLUMNNAME;
The above syntax will select all the data or records from the table, but it will arrange all those data or records
in the groups based on the column name given in the query.
The syntax of Group By clause with Aggregate Functions:
SELECT COLUMNNAME1, Aggregate_FUNCTION (COLUMNNAME) FROM TABLENAME GROUP
BY COLUMNNAME;
Let's understand the Group By clause with the help of examples.
Consider the employees table with the following data:
As per the expected output, the designation with the respective employee count is displayed.
3. HAVING CLAUSE:
When we need to place any conditions on the table's column, we use the WHERE clause in SQL. But if we
want to use any condition on a column in Group By clause at that time, we will use the HAVING clause
with the Group By clause for column conditions.
Syntax: TABLENAME GROUP BY COLUMNNAME HAVING CONDITION;
Consider the employees table with the following data:
The above output shows that the employee name, salary, and city of an employee where employee salary is
greater than 40000 grouped by designation. (Employees with a similar designation are placed in one group,
and those with other designation are placed separately).
4. ORDER BY CLAUSE
Whenever we want to sort anything in SQL, we use the ORDER BY clause. The ORDER BY clause in SQL
will help us to sort the data based on the specific column of a table. This means that all the data stored in the
specific column on which we are executing the ORDER BY clause will be sorted. The corresponding
column values will be displayed in the sequence in which we have obtained the values in the earlier step.
As we all know, sorting means either in ASCENDING ORDER or DESCENDING ORDER. In the same
way, ORDER BY CLAUSE sorts the data in ascending or descending order as per our requirement. The data
will be sorted in ascending order whenever the ASC keyword is used with ORDER by clause, and
the DESC keyword will sort the records in descending order.
By default, sorting in the SQL will be done using the ORDER BY clause in ASCENDING order if we didn't
mention the sorting order.
Before moving towards the example of the ORDER BY clause to sort the records, first, we will look at
syntax so it will be easy for us to go through the example.
Syntax of ORDER BY clause without asc and desc keyword:
SELECT COLUMN_NAME1, COLUMN_NAME2 FROM TABLE_NAME ORDER BY COLUMNAME;
Date_of_J
E_ID Name Salary City Designation Age
oining
As per the expected output, the records are displayed in ascending order of the employee's designation.
SQL Addition Operator (+): The Addition Operator in SQL performs the addition on the numerical data of
the database table. In SQL, we can easily add the numerical values of two columns of the same table by
specifying both the column names as the first and second operand. We can also add the numbers to the
existing numbers of the specific column.
Syntax of SQL Addition Operator:
1. SELECT operand1 + operand2;
Let's understand the below example which explains how to execute Addition Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Emp Monthly bonus
SQL Subtraction Operator (-): The Subtraction Operator in SQL performs the subtraction on the numerical
data of the database table. In SQL, we can easily subtract the numerical values of two columns of the same
table by specifying both the column names as the first and second operand. We can also subtract the number
from the existing number of the specific table column.
Syntax of SQL Subtraction Operator:
1. SELECT operand1 - operand2;
Let's understand the below example which explains how to execute Subtraction Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Penalty
SQL Multiplication Operator (*): The Multiplication Operator in SQL performs the Multiplication on the
numerical data of the database table. In SQL, we can easily multiply the numerical values of two columns of
the same table by specifying both the column names as the first and second operand.
Syntax of SQL Multiplication Operator:
1. SELECT operand1 * operand2;
Let's understand the below example which explains how to execute Multiplication Operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Penalty
SQL Modulus Operator (%): The Modulus Operator in SQL provides the remainder when the operand on
the left side is divided by the operand on the right side.
Syntax of SQL Modulus Operator:
1. SELECT operand1 % operand2;
Let's understand the below example which explains how to execute Modulus Operator in SQL query:
This example consists of a Division table, which has three columns Number, First_operand, and
Second_operand.
Number First operand Second operand
1 56 4
2 32 8
3 89 9
4 18 10
5 10 5
o If we want to get the remainder by dividing the numbers of First_operand column by the numbers of
Second_operand column, then we have to write the following query in SQL:
1. SELECT First_operand % Second_operand as Remainder FROM Employee_details;
SQL Equal Operator (=): This operator is highly used in SQL queries. The Equal Operator in SQL shows
only data that matches the specified value in the query.
This operator returns TRUE records from the database table if the value of both operands specified in the
query is matched.
Let's understand the below example which explains how to execute Equal Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
SQL Equal Not Operator (!=): The Equal Not Operator in SQL shows only those data that do not match the
query's specified value.
This operator returns those records or rows from the database views and tables if the value of both operands
specified in the query is not matched with each other.
Let's understand the below example which explains how to execute Equal Not Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
SQL Greater Than Operator (>): The Greater Than Operator in SQL shows only those data which are greater
than the value of the right-hand operand.
Let's understand the below example which explains how to execute Greater ThanOperator (>) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
SQL Greater Than Equals to Operator (>=): The Greater Than Equals to Operator in SQL shows those data
from the table which are greater than and equal to the value of the right-hand operand.
Let's understand the below example which explains how to execute greater than equals to the operator (>=)
in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
SQL Less Than Operator (<): The Less Than Operator in SQL shows only those data from the database
tables which are less than the value of the right-side operand.
This comparison operator checks that the left side operand is lesser than the right-side operand. If the
condition becomes true, then this operator in SQL displays the data which is less than the value of the right-
side operand.
Let's understand the below example which explains how to execute less than operator (<) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
201 Abhay 45000
SQL Less Than Equals to Operator (<=): The Less Than Equals to Operator in SQL shows those data from
the table which are lesser and equal to the value of the right-side operand.
This comparison operator checks that the left side operand is lesser and equal to the right side operand.
Let's understand the below example which explains how to execute less than equals to the operator (<=) in
SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name, and
Emp_Salary.
Emp Id Emp Name Emp Salary
SQL ALL Operator: The ALL operator in SQL compares the specified value to all the values of a column
from the sub-query in the SQL database.
This operator is always used with the following statement:
1. SELECT,
2. HAVING, and
3. WHERE.
Syntax of ALL operator:
1.
SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salary > ALL ( SELECT E
mp_Salary FROM Employee_details WHERE Emp_City = Jaipur)
Here, we used the SQL ALL operator with greater than the operator.
SQL AND Operator: The AND operator in SQL would show the record from the database table if all the
conditions separated by the AND operator evaluated to True. It is also known as the conjunctive operator
and is used with the WHERE clause.
Syntax of AND operator:
1.
SELECT column1, ...., columnN FROM table_Name WHERE condition1 AND condition2 AND co
ndition3 AND ....... AND conditionN;
Let's understand the below example which explains how to execute AND logical operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL OR Operator: The OR operator in SQL shows the record from the table if any of the conditions
separated by the OR operator evaluates to True. It is also known as the conjunctive operator and is used with
the WHERE clause.
Syntax of OR operator:
1.
SELECT column1, ...., columnN FROM table_Name WHERE condition1 OR condition2 OR conditi
on3 OR ....... OR conditionN;
Let's understand the below example which explains how to execute OR logical operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL BETWEEN Operator: The BETWEEN operator in SQL shows the record within the range mentioned
in the SQL query. This operator operates on the numbers, characters, and date/time operands.
If there is no value in the given range, then this operator shows NULL value.
Syntax of BETWEEN operator:
1.
SQL IN Operator: The IN operator in SQL allows database users to specify two or more values in a
WHERE clause. This logical operator minimizes the requirement of multiple OR conditions.
This operator makes the query easier to learn and understand. This operator returns those rows whose values
match with any value of the given list.
Syntax of IN operator:
1.
SQL NOT Operator: The NOT operator in SQL shows the record from the table if the condition evaluates to
false. It is always used with the WHERE clause.
Syntax of NOT operator:
1. SELECT column1, column2 ...., columnN FROM table_Name WHERE NOT condition;
Let's understand the below example which explains how to execute NOT logical operator in SQL query:
This example consists of an Employee_details table, which has four columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' AND NOT Emp_City = 'Ch
andigarh';
In this example, we used the SQL NOT operator with the Emp_City column.
SQL ANY Operator: The ANY operator in SQL shows the records when any of the values returned by the
sub-query meet the condition.
The ANY logical operator must match at least one record in the inner query and must be preceded by any
SQL comparison operator.
Syntax of ANY operator:
1.
SELECT column1, column2 ...., columnN FROM table_Name WHERE column_name comparison_
operator ANY (SELECT column_name FROM table_name WHERE condition(s)) ;
SQL LIKE Operator: The LIKE operator in SQL shows those records from the table which match with the
given pattern specified in the sub-query.
The percentage (%) sign is a wildcard which is used in conjunction with this logical operator.
This operator is used in the WHERE clause with the following three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement
Syntax of LIKE operator:
1.
SQL Union ALL Operator: The SQL Union Operator is the same as the UNION operator, but the only
difference is that it also shows the same record.
Syntax of UNION ALL Set operator:
1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
2. UNION ALL
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute Union ALL operator in Structured
Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary, and
Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL Intersect Operator: The SQL Intersect Operator shows the common record from two or more SELECT
statements. The data type and the number of columns must be the same for each SELECT statement used
with the INTERSECT operator.
Syntax of INTERSECT Set operator:
1. SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
2. INTERSECT
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute INTERSECT operator in Structured
Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary,
and Emp_City.
SQL Minus Operator: The SQL Minus Operator combines the result of two or more SELECT statements
and shows only the results from the first data set.
Syntax of MINUS operator:
1. SELECT column1, column2 ...., columnN FROM First_tablename [WHERE conditions]
2. MINUS
3. SELECT column1, column2 ...., columnN FROM Second_tablename [WHERE conditions];
Let's understand the below example which explains how to execute INTERSECT operator in Structured
Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id, Emp_Name, Emp_Salary, and
Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL Joins
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 as follows:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
NATURAL JOIN
Consider the two tables below as follows:
Student
StudentCourse
A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This
keyword will create the result-set by combining all rows from both the tables where the condition satisfies
i.e. value of the common field will be the same.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the table on the
right side of the join. For the rows for which there is no matching row on the 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;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join
and matching rows for the table on the left side of the join. For the rows for which there is no matching row
on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Example Queries (FULL JOIN):
SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
E. Natural join (?)
Natural join can join tables based on the common columns in the tables being joined. A natural join returns
all rows by matching values in common columns having same name and data type of columns and that
column should be present in both tables.
Both tables must have at list one common column with same column name and same data type.
The two table are joined using Cross join.
DBMS will look for a common column with same name and data type Tuples having exactly same values in
common columns are kept in result.
Example:
Department
Employee
Dept_id
Emp_id Dept_name
Emp_name Dept_id
1 10 Ram IT 10
2 30 Jon HR 30
3 40 Bob TIS 50
1 Ram 10 10 IT
2 Jon 30 30 HR
SQL Subqueries
An SQL Subquery, is a SELECT query within another query. It is also known as Inner query or Nested
query and the query containing it is the outer query. The outer query can contain the SELECT, INSERT,
UPDATE, and DELETE statements. We can use the subquery as a column expression, as a condition in
SQL clauses, and with operators like =, >, <, >=, <=, IN, BETWEEN, etc.
Rules to be followed: Following are the rules to be followed while writing subqueries −
Subqueries must be enclosed within parentheses.
Subqueries can be nested within another subquery.
A subquery must contain the SELECT query and the FROM clause always.
A subquery consists of all the clauses an ordinary SELECT clause can contain: GROUP BY,
WHERE, HAVING, DISTINCT, TOP/LIMIT, etc. However, an ORDER BY clause is only used
when a TOP clause is specified. It can't include COMPUTE or FOR BROWSE clause.
A subquery can return a single value, a single row, a single column, or a whole table. They are called
scalar subqueries.
Subqueries with the SELECT Statement: Subqueries are most frequently used with the SELECT
statement. The basic syntax is as follows −
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ] [WHERE]);
Example: In the following query, we are creating a table named CUSTOMERS −
CREATETABLE CUSTOMERS (
ID INT NOTNULL,
NAME VARCHAR (20) NOTNULL,
AGE INT NOTNULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Here, we are inserting records into the above-created table using INSERT INTO statement −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00),
(4, 'Chaitali', 25, 'Mumbai', 6500.00),
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);
Select * from customers;
ID NAME AGE ADDRESS SALARY
Subqueries with the INSERT Statement: We can also use the subqueries along with the INSERT
statements. The data returned by the subquery is inserted into another table. In the following example, we
are creating another table CUSTOMERS_BKP with similar structure as CUSTOMERS table −
CREATETABLE CUSTOMERS_BKP (
ID INT NOTNULL,
NAME VARCHAR (20) NOTNULL,
AGE INT NOTNULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now to copy the complete records of CUSTOMERS table into the CUSTOMERS_BKP table, we can use
the following query −
INSERTINTO CUSTOMERS_BKP
SELECT*FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);
Subqueries with the UPDATE Statement: A subquery can also be used with the UPDATE statement. You
can update single or multiple columns in a table using a subquery.
Example: We have the CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The
following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose
AGE is greater than or equal to 27.
UPDATE CUSTOMERS
SET SALARY = SALARY *0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 );
Subqueries with the DELETE Statement: The subquery can be used with the DELETE statement as well;
like with any other statements mentioned above.
Example: We have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The
following example deletes the records from the CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27.
DELETEFROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 );