Structured Query Language (SQL)
Last Updated :
04 Feb, 2024
Structured Query Language is a standard Database language that is used to create, maintain, and retrieve the relational database. In this article, we will discuss this in detail about SQL. Following are some interesting facts about SQL. Let’s focus on that.
SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT, UPDATE, CREATE, etc.) in capital letters and use user-defined things (like table name, column name, etc.) in small letters.
We can write comments in SQL using “–” (double hyphen) at the beginning of any line. SQL is the programming language for relational databases (explained below) like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-relational databases (also called NoSQL) databases like MongoDB, DynamoDB, etc. do not use SQL.
Although there is an ISO standard for SQL, most of the implementations slightly vary in syntax. So we may encounter queries that work in SQL Server but do not work in MySQL.
What is Relational Database?
A relational database means the data is stored as well as retrieved in the form of relations (tables). Table 1 shows the relational database with only one relation called STUDENT which stores ROLL_NO, NAME, ADDRESS, PHONE, and AGE of students.
STUDENT Table
| 1 |
RAM |
DELHI |
9455123451 |
18 |
| 2 |
RAMESH |
GURGAON |
9652431543 |
18 |
| 3 |
SUJIT |
ROHTAK |
9156253131 |
20 |
| 4 |
SURESH |
DELHI |
9156768971 |
18 |
Important Terminologies
These are some important terminologies that are used in terms of relation.
- Attribute:Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME etc.
- Tuple:Each row in the relation is known as tuple. The above relation contains 4 tuples, one of which is shown as:
- Degree:The number of attributes in the relation is known as degree of the relation. The STUDENT relation defined above has degree 5.
- Cardinality:The number of tuples in a relation is known as cardinality. The STUDENTrelation defined above has cardinality 4.
- Column:Column represents the set of values for a particular attribute. The column ROLL_NO is extracted from relation STUDENT.
How Queries can be Categorized in Relational Database?
The queries to deal with relational database can be categorized as:
- Data Definition Language:It is used to define the structure of the database. e.g; CREATE TABLE, ADD COLUMN, DROP COLUMN and so on.
- Data Manipulation Language:It is used to manipulate data in the relations. e.g.; INSERT, DELETE, UPDATE and so on.
- Data Query Language:It is used to extract the data from the relations. e.g.; SELECT So first we will consider the Data Query Language. A generic query to retrieve data from a relational database is:
- SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
- [WHERE condition]
- [GROUP BY (Attributes)[HAVING condition]]
- [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to retrieve from a relational database. The statements written inside [] are optional. We will look at the possible query combination on relation shown in Table 1.
Different Query Combinations
Case 1: If we want to retrieve attributes ROLL_NO and NAMEof all students, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT;
| ROLL_NO |
NAME |
| 1 |
RAM |
| 2 |
RAMESH |
| 3 |
SUJIT |
| 4 |
SURESH |
Case 2: If we want to retrieve ROLL_NO and NAME of the students whose ROLL_NO is greater than 2, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT
WHERE ROLL_NO>2;
| ROLL_NO |
NAME |
| 3 |
SUJIT |
| 4 |
SURESH |
CASE 3: If we want to retrieve all attributes of students, we can write * in place of writing all attributes as:
SELECT * FROM STUDENT
WHERE ROLL_NO>2;
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
AGE |
| 3 |
SUJIT |
ROHTAK |
9156253131 |
20 |
| 4 |
SURESH |
DELHI |
9156768971 |
18 |
CASE 4: If we want to represent the relation in ascending order by AGE, we can use ORDER BY clause as:
SELECT * FROM STUDENT ORDER BY AGE;
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
AGE |
| 1 |
RAM |
DELHI |
9455123451 |
18 |
| 2 |
RAMESH |
GURGAON |
9652431543 |
18 |
| 4 |
SURESH |
DELHI |
9156768971 |
18 |
| 3 |
SUJIT |
ROHTAK |
9156253131 |
20 |
Note:
ORDER BY AGEis equivalent to ORDER BY AGE ASC.
If we want to retrieve the results in descending order of AGE, we can use ORDER BY AGE DESC.
CASE 5: If we want to retrieve distinct values of an attribute or group of attribute, DISTINCT is used as in:
SELECT DISTINCT ADDRESS FROM STUDENT;
| ADDRESS |
| DELHI |
| GURGAON |
| ROHTAK |
If DISTINCT is not used, DELHI will be repeated twice in result set. Before understanding GROUP BY and HAVING, we need to understand aggregations functions in SQL.
Aggregation Functions
Aggregation functions are used to perform mathematical operations on data values of a relation. Some of the common aggregation functions used in SQL are:
- COUNT: Count function is used to count the number of rows in a relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;
- SUM: SUM function is used to add the values of an attribute in a relation. e.g;
SELECT SUM(AGE) FROM STUDENT;
In the same way, MIN, MAX and AVG can be used. As we have seen above, all aggregation functions return only 1 row. AVERAGE: It gives the average values of the tupples. It is also defined as sum divided by count values.
Syntax:
AVG(attributename)
OR
SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
- MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:
MAX(attributename)
- MINIMUM:It extracts the minimum value amongst the set of all the tupples.
Syntax:
MIN(attributename)
- GROUP BY:Group by is used to group the tuples of a relation based on an attribute or group of attribute. It is always combined with aggregation function which is computed on group. e.g.;
SELECT ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
In this query, SUM(AGE) will be computed but not for entire table but for each address. i.e.; sum of AGE for address DELHI(18+18=36) and similarly for other address as well. The output is:
| ADDRESS |
SUM(AGE) |
| DELHI |
36 |
| GURGAON |
18 |
| ROHTAK |
20 |
If we try to execute the query given below, it will result in error because although we have computed SUM(AGE) for each address, there are more than 1 ROLL_NO for each address we have grouped. So it can’t be displayed in result set. We need to use aggregate functions on columns after SELECT statement to make sense of the resulting set whenever we are using GROUP BY.
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
NOTE:
An attribute which is not a part of GROUP BY clause can’t be used for selection.
Any attribute which is part of GROUP BY CLAUSE can be used for selection but it is not mandatory.
But we could use attributes which are not a part of the GROUP BY clause in an aggregate function.
Conclusion
SQL is a standard language used to manage data in relational databases. SQL is mainly divided into four main categories: Data definition language, data manipulation language, transaction control language, and data query language and SQL is a powerful language that can be used to carry out a wide range of operations like insert ,delete and update.
Similar Reads
Types of Keys in Relational Model (Candidate, Super, Primary, Alternate and Foreign)
Keys are one of the basic requirements of a relational database model. It is widely used to identify the tuples(rows) uniquely in the table. We also use keys to set up relations amongst various columns and tables of a relational database. Different Types of Database Keys Candidate KeyPrimary KeySupe
6 min read
Basic Operators in Relational Algebra
The Relational Model is a way of structuring data using relations, which are a collection of tuples that have the same attributes. Relational Algebra is a procedural query language that takes relations as input and returns relations as output. It uses a set of operators to manipulate and retrieve da
4 min read
Extended Operators in Relational Algebra
Basic idea about relational model and basic operators in Relational Algebra: Relational Model Basic Operators in Relational Algebra Extended operators are those operators which can be derived from basic operators. There are mainly three types of extended operators in Relational Algebra: JoinIntersec
6 min read
Tuple Relational Calculus (TRC) in DBMS
Tuple Relational Calculus (TRC) is a non-procedural query language used in relational database management systems (RDBMS) to retrieve data from tables. TRC is based on the concept of tuples, which are ordered sets of attribute values that represent a single row or record in a database table. TRC is
4 min read
Introduction of Database Normalization
Normalization is an important process in database design that helps improve the database's efficiency, consistency, and accuracy. It makes it easier to manage and maintain the data and ensures that the database is adaptable to changing business needs. What is Database Normalization?Database normaliz
7 min read
Normal Forms in DBMS
Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables. Nor
12 min read
Functional Dependency and Attribute Closure
Fundamental ideas in database management and design are functional dependency and attribute closure. They are essential to maintaining data integrity and building effective, organized, and normalized databases. Functional DependencyA functional dependency A->B in a relation holds if two tuples ha
6 min read
Lossless Decomposition in DBMS
The original relation and relation reconstructed from joining decomposed relations must contain the same number of tuples if the number is increased or decreased then it is Lossy Join decomposition. Lossless join decomposition ensures that never get the situation where spurious tuples are generated
5 min read
Database Management System | Dependency Preserving Decomposition
Dependency Preservation: A Decomposition D = { R1, R2, R3...Rn } of R is dependency preserving wrt a set F of Functional dependency if (F1 ? F2 ? … ? Fm)+ = F+. Consider a relation R R ---> F{...with some functional dependency(FD)....} R is decomposed or divided into R1 with FD { f1 } and R2 with
4 min read
Lossless Join and Dependency Preserving Decomposition
Decomposition of a relation is done when a relation in a relational model is not in appropriate normal form. Relation R is decomposed into two or more relations if decomposition is lossless join as well as dependency preserving. Lossless Join DecompositionIf we decompose a relation R into relations
4 min read
How to find the highest normal form of a relation
To understand this topic, you should have a basic idea about Functional Dependency & Candidate keys and Normal forms .Steps to find the highest normal form of relation: Find all possible candidate keys of the relation.Divide all attributes into two categories: prime attributes and non-prime attr
5 min read
Equivalence of Functional Dependencies
Pre-Requisite: Functional Dependency, Finding Attribute Closure, and Candidate Keys using Functional Dependency For understanding the equivalence of Functional Dependencies Sets (FD sets), the basic idea about Attribute Closure is given in this article Given a Relation with different FD sets for tha
5 min read
Canonical Cover of Functional Dependencies in DBMS
Whenever a user updates the database, the system must check whether any functional dependencies are violated in this process. If there is a violation of dependencies in the new database state, the system must roll back. Working with a huge set of functional dependencies can cause unnecessary added c
8 min read
Structured Query Language (SQL)
Structured Query Language is a standard Database language that is used to create, maintain, and retrieve the relational database. In this article, we will discuss this in detail about SQL. Following are some interesting facts about SQL. Let's focus on that. SQL is case insensitive. But it is a recom
6 min read
Inner Join vs Outer Join
Inner Join and Outer Join are the types of join. The inner join has the work to return the common rows between the two tables, whereas the Outer Join has the work of returning the work of the inner join in addition to the rows that are not matched. Let's discuss both of them in detail in this artic
9 min read
Having vs Where Clause in SQL
In SQL, filtering data is important for extracting meaningful insights from large datasets. While both the WHERE and HAVING clauses allow us to filter data, they serve distinct purposes and operate at different stages of the query execution process. Understanding the difference between these clauses
4 min read
Concurrency Control in DBMS
Concurrency control is a very important concept of DBMS which ensures the simultaneous execution or manipulation of data by several processes or user without resulting in data inconsistency. Concurrency Control deals with interleaved execution of more than one transaction. What is Transaction? A tra
13 min read
Database Recovery Techniques in DBMS
Database Systems like any other computer system, are subject to failures but the data stored in them must be available as and when required. When a database fails it must possess the facilities for fast recovery. It must also have atomicity i.e. either transactions are completed successfully and com
11 min read
ACID Properties in DBMS
This article is based on the concept of ACID properties in DBMS that are necessary for maintaining data consistency, integrity, and reliability while performing transactions in the database. Let's explore them. A transaction is a single logical unit of work that accesses and possibly modifies the co
7 min read
Why recovery is needed in DBMS
Basically, whenever a transaction is submitted to a DBMS for execution, the operating system is responsible for making sure or to be confirmed that all the operations which need to be performed in the transaction have been completed successfully and their effect is either recorded in the database or
6 min read
Types of Schedules in DBMS
Schedule, as the name suggests, is a process of lining the transactions and executing them one by one. When there are multiple transactions that are running in a concurrent manner and the order of operation is needed to be set so that the operations do not overlap each other, Scheduling is brought i
7 min read
Conflict Serializability in DBMS
As discussed in Concurrency control, serial schedules have less resource utilization and low throughput. To improve it, two or more transactions are run concurrently. However, concurrency of transactions may lead to inconsistency in the database. To avoid this, we need to check whether these concurr
5 min read
Precedence Graph for Testing Conflict Serializability in DBMS
A Precedence Graph or Serialization Graph is used commonly to test the Conflict Serializability of a schedule. It is a directed Graph (V, E) consisting of a set of nodes V = {T1, T2, T3..........Tn} and a set of directed edges E = {e1, e2, e3..................em}. The graph contains one node for eac
6 min read
Recoverability in DBMS
Recoverability is a property of database systems that ensures that, in the event of a failure or error, the system can recover the database to a consistent state. Recoverability guarantees that all committed transactions are durable and that their effects are permanently stored in the database, whil
6 min read
Deadlock in DBMS
In database management systems (DBMS) a deadlock occurs when two or more transactions are unable to the proceed because each transaction is waiting for the other to the release locks on resources. This situation creates a cycle of the dependencies where no transaction can continue leading to the sta
10 min read