GATE DA SQL_piyushwairale
GATE DA SQL_piyushwairale
GATE
Data Science & AI
SQL
For GATE DA Course & Test
Series
Piyush Wairale
www.piyushwairale.com
Preparing for GATE DA 2025???
www.piyushwairale.com
Database Management System
by Piyush Wairale
Instructions:
• Kindly go through the lectures/videos on our website www.piyushwairale.com
• Read this study material carefully and make your own handwritten short notes. (Short notes must not be
more than 5-6 pages)
1
Contents
1 Datatypes 4
1.1 1. Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 2. Character Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 3. Date and Time Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 4. Binary Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 5. Other Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Constraints 6
2.1 NOT NULL Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 UNIQUE Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 PRIMARY KEY Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 FOREIGN KEY Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 CHECK Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.6 DEFAULT Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.6.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 SQL Sub-Languages 8
3.1 Data Manipulation Language (DML) Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Data Definition Language (DDL) Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Data Control Language (DCL) Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Querying Data Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.5 Joining Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6 Subqueries in SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.7 Aggregate Functions Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.8 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.9 Transaction Control Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5 Subqueries 15
5.1 Single-Row Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 Multiple-Row Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3 Correlated Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.4 Nested Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.5 Scalar Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6 Views 17
7 Triggers 18
7.1 Creating a Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.2 Trigger Example Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.3 Dropping a Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
8 Cursors 19
8.1 Declaring a Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.2 Cursor Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.3 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.4 Calling the Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2
9 Stored Procedures 20
9.1 Creating a Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
9.2 Calling the Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
10 SQL Practice 21
Youtube Channel
Telegram Group
1 Datatypes
Data types in SQL define the type of data that can be stored in a column of a table. Each column in a table must
have a data type specified, and this data type dictates the kind of data that can be stored and the operations that
can be performed on that data.
Types of Constraints
The main types of constraints in SQL are as follows:
2.1.1 Example
CREATE TABLE employees (
employee_id INT NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50),
hire_date DATE
);
In this example, the employee id and first name columns cannot contain NULL values.
2.2.1 Example
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
phone_number VARCHAR(15) UNIQUE
);
Here, both email and phone number columns must contain unique values.
2.3.1 Example
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL(10, 2)
);
In this example, product id serves as the primary key for the products table.
Here, customer id in the orders table references the customer id in the customers table.
2.5.1 Example
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
age INT CHECK (age >= 18)
);
In this case, the age column must have a value greater than or equal to 18.
2.6.1 Example
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
stock INT DEFAULT 0
);
Here, if no stock value is provided when inserting a new product, it will default to 0.
3 SQL Sub-Languages
SQL is divided into several sub-languages, each serving different purposes:
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE EXISTS (subquery);
Example
Suppose you have two tables: employees and departments. You want to find all employees who belong to a
department that has more than 10 employees.
In this example, the outer query selects employee names only if there exists at least one department (in the
subquery) with more than 10 employees.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT EXISTS (subquery);
Example
Using the same employees and departments tables, suppose you want to find all employees who do not belong to
any department.
In this case, the outer query selects employee names only if there does not exist a corresponding department in
the departments table for that employee.
Key Points
• EXISTS is used to determine if a subquery returns any results, while NOT EXISTS is used to determine if a
subquery returns no results.
• Both operators are often used in correlated subqueries, where the subquery references columns from the outer
query.
• Using EXISTS and NOT EXISTS can improve the readability of SQL queries, especially when dealing with
complex conditions involving multiple tables.
5 Subqueries
A subquery, also known as an inner query or nested query, is a query within another SQL query. Subqueries can
return a single value, a single row, or a set of rows and can be used in various clauses of the main query.
Types of Subqueries
Subqueries can be classified into several types based on their structure and the context in which they are used:
Example
SELECT employee_id, first_name
FROM employees
WHERE department_id = (
SELECT department_id
FROM departments
WHERE department_name = ’Sales’
);
In this example, the subquery returns the department ID of the Sales department, and the outer query retrieves
employees from that department.
Example
SELECT first_name, last_name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location_id = 1000
);
Here, the subquery retrieves department IDs for locations with ID 1000, and the outer query retrieves employee
names from those departments.
Example
SELECT employee_id, first_name
FROM employees e
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id
);
In this case, the subquery calculates the average salary for the department of each employee in the outer query.
Example
SELECT first_name, last_name
FROM employees
WHERE department_id = (
SELECT department_id
FROM departments
WHERE location_id = (
SELECT location_id
FROM locations
WHERE city = ’San Francisco’
)
);
Here, the inner subquery retrieves the location ID for San Francisco, which is then used in the second subquery to
find the department ID, allowing the outer query to retrieve the employees from that department.
Example
SELECT first_name, last_name,
(SELECT MAX(salary) FROM employees) AS max_salary
FROM employees;
In this example, the scalar subquery retrieves the maximum salary from the employees table and includes it in the
result set of the outer query.
6 Views
A View is a virtual table based on the result-set of an SQL statement. Views simplify complex queries, enhance
security by restricting access to certain data, and can present aggregated data.
Creating a View
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE VIEW HighEarners AS
SELECT Name, Salary
FROM Employee
WHERE Salary > 70000;
Using a View
Updating a View
Some views are updatable, allowing DML operations on them.
Example:
UPDATE HighEarners
SET Salary = Salary + 5000
WHERE Name = ’Alice’;
Dropping a View
7 Triggers
A Trigger is a stored procedure in the database that automatically invokes (fires) in response to certain events
on a particular table or view. Triggers can be used for enforcing complex business rules, auditing changes, and
maintaining derived data.
OPEN cur;
read_loop: LOOP
FETCH cur INTO empName, empSalary;
IF done THEN
LEAVE read_loop;
END IF;
-- Process each employee
SELECT CONCAT(’Processing ’, empName, ’ with salary ’, empSalary);
END LOOP;
CLOSE cur;
END //
DELIMITER ;
8.3 Explanation
- DECLARE cur CURSOR FOR: Defines the cursor with a SELECT statement. - OPEN cur;: Opens the
cursor. - FETCH cur INTO: Retrieves the next row and stores it into variables. - LOOP: A loop to process
each row fetched. - LEAVE: Exits the loop when there are no more rows. - CLOSE cur;: Closes the cursor after
processing.
CALL ProcessEmployees();
9 Stored Procedures
A Stored Procedure is a set of SQL statements that can be stored in the database and executed repeatedly.
DELIMITER ;
CALL GetEmployeeByDept(’HR’);
10 SQL Practice
Consider the schema given below:
1. Find the titles of courses in the Comp. Sci. department that have 3 credits.
SELECT title
FROM course
WHERE dept_name = ’Comp. Sci.’
AND credits = 3;
2. Find the IDs of all students who were taught by an instructor named Einstein; make sure there are no
duplicates in the result. This query can be answered in several different ways. One way is as follows:
As an alternative to the JOIN ... USING syntax above, the query can be written by enumerating relations
in the FROM clause and adding the corresponding join predicates on ID, course.id, section.id, semester,
and year to the WHERE clause. Note that using natural join in place of JOIN ... USING would result in
equating student ID with instructor ID, which is incorrect.
3. Find the highest salary of any instructor.
SELECT MAX(salary)
FROM instructor;
4. Find all instructors earning the highest salary (there may be more than one with the same salary).
Note that if a section does not have any students taking it, it would not appear in the result. One way of
ensuring such a section appears with a count of 0 is to replace natural join by the natural left outer join
operation, covered later in Chapter 4. Another way is to use a subquery in the SELECT clause, as follows.
6. Find the maximum enrollment, across all sections, in Autumn 2009. One way of writing this query is as
follows:
SELECT max(enrollment)
FROM (SELECT count(ID) AS enrollment
FROM section NATURAL JOIN takes
WHERE semester = ’Autumn’
AND year = 2009
GROUP BY course.id, sec.id);
As an alternative to using a nested subquery in the FROM clause, it is possible to use a WITH clause, as
illustrated in the answer to the next part of this question. A subtle issue in the above query is that if no
section had any enrollment, the answer would be empty, not 0. We can use the alternative using a subquery,
from the previous part of this question, to ensure the count is 0 in this case.
7. Find the sections that had the maximum enrollment in Autumn 2009. The following answer uses a WITH
clause to create a temporary view, simplifying the query.
WITH sec_enrollment AS (
SELECT course.id, sec.id, count(ID) AS enrollment
FROM section NATURAL JOIN takes
WHERE semester = ’Autumn’
AND year = 2009
GROUP BY course.id, sec.id
)
SELECT course.id, sec.id
FROM sec_enrollment
WHERE enrollment = (SELECT max(enrollment) FROM sec_enrollment);
It is also possible to write the query without the with clause, but the subquery to find enrollment would get
repeated twice in the query.
11 GATE CSE PYQs
(Note: Solve the below questions, and you can discuss the answers in our course discussion group.)
Q1
[MCQ] [GATE-2008 : 2M]
Consider the following relational schema:
Options
(a) for each school with more than 200 students appearing in exams, the name of the school and the number of
100s scored by its students.
(b) for each school with more than 200 students in it, the name of the school and the number of 100s scored by
its students.
(c) for each school with more than 200 students in it, the name of the school and the number of its students
scoring 100 in at least one exam.
(d) nothing; the query has a syntax error.
Q2. [MCQ]
Consider the following relational schema:
• Suppliers(sid: integer, sname: string, city: string, street: string)
• Parts(pid: integer, pname: string, color: string)
• Catalog(sid: integer, pid: integer, cost: real)
Consider the following relational query on the above database:
SELECT S.sname
FROM Suppliers S
WHERE S.sid NOT IN (
SELECT C.sid
FROM Catalog C
WHERE C.pid NOT IN (
SELECT P.pid
FROM Parts P
WHERE P.color <> ’blue’
)
);
Assume that relations corresponding to the above schema are not empty. Which one of the following is the correct
interpretation of the above query?
(a) Find the names of all suppliers who have supplied a non-blue part.
(b) Find the names of all suppliers who have not supplied a non-blue part.
(c) Find the names of all suppliers who have supplied only blue parts.
(d) Find the names of all suppliers who have not supplied only blue parts.
Q3
[MCQ] [GATE-2011 : 2M]
Database table by name Loan Records is given below:
Borrower Bank Manager Loan Amount
Ramesh Sunderajan 10000.00
Suresh Ramgopal 5000.00
Mahesh Sunderajan 7000.00
Q4
[MCQ] [GATE-2011 : 2M]
Consider a database table T containing two columns X and Y each of type integer. After the creation of the table,
one record (X=1, Y=1) is inserted in the table. Let MX and MY denote the respective maximum values of X and Y
among all records in the table at any point in time. Using MX and MY, new records are inserted in the table 128
times with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion,
values of MX and MY change.
What will be the output of the following SQL query after the steps mentioned above are carried out?
SELECT Y FROM T WHERE X = 7;
Options:
(a) 127
(b) 255
(c) 129
(d) 257
Q5
[MCQ] [GATE-2012 : 1M]
Which of the following statements are TRUE about an SQL query?
P: An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause.
Q: An SQL query can contain a HAVING clause only if it has a GROUP BY clause.
R: All attributes used in the GROUP BY clause must appear in the SELECT clause.
S: Not all attributes used in the GROUP BY clause need to appear in the SELECT clause.
Options:
(a) P and R
(b) P and S
(c) Q and R
(d) Q and S
Q6
[MCQ] [GATE-2012 : 2M]
Consider the following relations A, B, and C:
A
Id Name Age
12 Arun 60
15 Shreya 24
99 Rohit 11
B
Id Name Age
15 Shreya 24
25 Hari 40
98 Rohit 20
99 Rohit 11
C
Id Phone Area
10 2200 02
99 2100 01
How many tuples does the result of the following SQL query contain?
SELECT A.Id
FROM A
WHERE A.Age > ALL (SELECT B.Age
FROM B
WHERE B.Name = ’Arun’);
Options:
(a) 4
(b) 0
(c) 1
(d) 3
Q7
[MCQ] [GATE-2014 : 2M]
SQL allows duplicate tuples in relations, and correspondingly defines the multiplicity of tuples in the result of joins.
Which one of the following queries always gives the same answer as the nested query shown below:
Options:
(a) select R.* from R, S where R.a = S.a
Q8
[MCQ] [GATE-2014 : 2M]
Given the following schema:
• employees(emp-id, first-name, last-name, hire-date, dept-id, salary)
Q9
[NAT] GATE-2015 : 2M
Consider the following relations:
Q10
[MCQ] [GATE-2014 : 2M]
Consider the following relational schema:
(b) Names of all the employees who at most one of their customers having a ’GOOD’ rating.
(c) Names of all the employees with none of their customers having a ’GOOD’ rating.
(d) Names of all the employees with all their customers having a ’GOOD’ rating