Skip to content
← Computer Science

Computer Science · Class 12 Optional

Ch 9Structured Query Language (SQL) — Class 12 Computer Science, concept-first.

We have already seen that a Relational Database Management System (RDBMS) is the software that manages data organised into relations (tables). The previous chapter explained the purpose of an RDBMS — to store data securely, maintain relationships between tables, and allow efficient retrieval.

95

Q&A

29

Concepts

20m

Section weightage

Database Management · across all 2 lessons

Start learning — read this chapter →

Key concepts

Hover a concept to preview it and jump to its most relevant Q&A.

Table Creation

Think of the last time you tried to find a specific contact in your phone. If all your contacts were just listed in one long, unbroken list — no groups, no alphabetical order, no search — you would have to scroll through…

Start with this concept →

Chapter contents

The NCERT structure, section by section. Open a section to see its questions, then read the concept-first solution.

9.1

Introduction

We have already seen that a Relational Database Management System (RDBMS) is the software that manages data organised into relations (tables).

9.2

Structured Query Language (SQL)

In a file system, you have to write full application programs just to get at your data. That is a lot of work.

9.2.1

Installing MySQL

MySQL is an open-source RDBMS (Relational Database Management System). To use it, you first need to download it from the official website: https://dev.mysql.com/downloads.

9.3

Data Types and Constraints in MySQL

A database is made up of tables, and each table is made up of columns (also called attributes). Every column stores a specific kind of information — for example, a student's name is text, their date o…

9.3.1

Data Type of Attribute

A database table is made up of attributes (columns), and every attribute must be of a specific data type.

9.3.2

Constraints

Constraints are rules that restrict what data values can be stored in a column. They exist to protect the correctness and reliability of your data — for example, preventing a blank entry where a value…

9.4

SQL for Data Definition

Before you can store any data, you must first decide how that data will be organised. This is the core idea behind data definition.

9.4.1

CREATE Database

To create a new database in MySQL, you use the CREATE DATABASE statement. The syntax is straightforward:

9.4.2

CREATE Table

3 Q

Once a database has been created, the next step is to define the relations (tables) that will store the data.

9.4.3

Describe Table

Before you can work with a table — insert data, query it, or modify it — you need to know its structure: what columns exist, what type of data each column holds, whether a column can be empty, and so…

9.4.4

ALTER Table

3 Q

After you've created a table, you'll often find you need to adjust its structure — perhaps you forgot to declare a key, need a new column, or want to tighten up the rules on an existing one.

9.4.5

DROP Statement

The DROP statement is SQL's way of permanently removing a database object — either a table or the entire database itself — from the system.

(A)

Add primary key to a relation

Sometimes a table is created without declaring a primary key up front — this is exactly what happened with the GUARDIAN and ATTENDANCE tables in Activity 9.4, where you were asked to create them witho…

(B)

Add foreign key to a relation

Once a relation's primary key is in place, the next step is to wire up any foreign keys it needs — the links that connect it to other relations.

9.5

SQL for Data Manipulation

Once a table is created with CREATE TABLE, only its structure exists — the table itself holds no data. To populate a table with records, we use the INSERT statement.

(C)

Add constraint UNIQUE to an existing attribute

A UNIQUE constraint stops two rows from ever sharing the same value in a given column. You can add it to a column after the table already exists.

9.5.1

Insertion of Records

3 Q

The INSERT INTO command is how you add new rows of data to a table. You must always specify the table name, and then provide the values you want to store. The simplest form is:

(D)

Add an attribute to an existing table

Sometimes the original design of a table turns out to be incomplete, and you need to add a column that was never there in the first place. ALTER TABLE ... ADD handles this.

9.6

SQL for Data Query

The whole point of storing data in a database is to be able to retrieve it later, in whatever way it is needed.

(E)

Modify datatype of an attribute

If a column's data type turns out to be too restrictive — for instance, a VARCHAR length that's too short for real data — you can change it using MODIFY.

9.6.1

SELECT Statement

2 Q

The SELECT statement is the most important command in SQL — it is how you retrieve data from a table. The result of a SELECT query is always displayed in tabular form, just like the original table.

9.6.2

Querying using Database OFFICE

19 Q

Organisations keep their data in a database made up of several related tables — for example, an OFFICE database might hold an EMPLOYEE table, a DEPARTMENT table, and others besides.

+Worked Examples1 question
  1. Example 9.3Select names of all employees along with their annual income (calculated as Salary*12). While displaying the query result, rename the column…Preview
+Worked Examples1 question
  1. Example 9.4Display all the details of those employees of D04 department who earn more than 5000.Preview
+Worked Examples1 question
  1. Example 9.5The following query selects records of all the employees except Aaliya.Preview
+Worked Examples1 question
  1. Example 9.6The following query selects the name and department number of all those employees who are earning salary between 20000 and 50000 (both value…Preview
+Worked Examples1 question
  1. Example 9.7The following query selects details of all the employees who work in the departments having deptid D01, D02 or D04.Preview
+Worked Examples1 question
  1. Example 9.8The following query selects details of all the employees except those working in department number D01 or D02.Preview
+Worked Examples1 question
  1. Example 9.9The following query selects details of all the employees in ascending order of their salaries.Preview
+Worked Examples1 question
  1. Example 9.10Select details of all the employees in descending order of their salaries.Preview
+Worked Examples1 question
  1. Example 9.11The following query selects details of all those employees who have not been given a bonus. This implies that the bonus column will be blank…Preview
+Worked Examples1 question
  1. Example 9.12The following query selects names of all employees who have been given a bonus (i.e., Bonus is not null) and works in the department D01.Preview
+Worked Examples1 question
  1. Example 9.13The following query selects details of all those employees whose name starts with 'K'.Preview
+Worked Examples1 question
  1. Example 9.14The following query selects details of all those employees whose name ends with 'a', and gets a salary more than 45000.Preview
+Worked Examples1 question
  1. Example 9.15The following query selects details of all those employees whose name consists of exactly 5 letters and starts with any letter but has 'ANYA…Preview
+Worked Examples1 question
  1. Example 9.16The following query selects names of all employees containing 'se' as a substring in name.Preview
+Worked Examples1 question
  1. Example 9.17The following query selects names of all employees containing 'a' as the second character.Preview
+Activities1 question
  1. Activity 9.8Compare the output produced by the query in Example 9.6 and the output of the following query and differentiate between the OR and AND opera…Preview
+Activities1 question
  1. Activity 9.9Execute the following 2 queries and find out what will happen if we specify two columns in the ORDER BY clause: SELECT * FROM EMPLOYEE ORDER…Preview
+Think & Reflect1 question
  1. Q7What will happen if in the above query we write “Aaliya” as “AALIYA” or “aaliya” or “AaLIYA”? Will the query generate the same output or an…Preview
+Think & Reflect1 question
  1. Q8When we type first letter of a contact name in our contact list in our mobile phones all the names containing that character are displayed.…Preview
(F)

Modify constraint of an attribute

By default, MySQL allows every attribute to hold NULL — except whichever attribute is the primary key.

9.7

Data Updation and Deletion

Updation and deletion of data are also part of SQL's Data Manipulation Language (DML). In this section, we apply these two data manipulation methods — UPDATE and DELETE — on the STUDENT and GUARDIAN t…

(G)

Add default value to an attribute

A DEFAULT value is what MySQL fills in automatically for a column when a row is inserted without specifying that column's value. You can add this to an existing attribute with MODIFY.

9.7.1

Data Updation

The UPDATE statement is the tool for modifying existing data in a table. You use it when a value in one or more columns of a record needs to be changed — for example, correcting a spelling, updating a…

(H)

Remove an attribute

Just as you can add a column, you can also remove one that's no longer needed, using ALTER TABLE ... DROP.

(I)

Remove primary key from the table

If a table's primary key needs to be redefined — say, changed to a different attribute, or made composite — you first have to remove the existing one.

9.7.2

Data Deletion

The DELETE statement removes one or more entire records (rows) from a table. It does not remove the table structure itself — only the data inside it.

9.8

Functions in SQL

A function in SQL is a pre-written block of code that performs a specific task and returns a value (or values) as a result.

9.8.1

Single Row Functions

10 Q

Single row functions, also called scalar functions, work on a single value at a time and return a single value as output. They are applied to each row individually when used in a query.

+Worked Examples1 question
  1. Example 9.18In order to increase sales, suppose the car dealer decides to offer his customers to pay the total amount in 10 easy EMIs (equal monthly ins…Preview
+Worked Examples1 question
  1. Example 9.19a) Let us now add a new column Commission to the SALE table. The column Commission should have a total length of 7 in which 2 decimal places…Preview
+Worked Examples1 question
  1. Example 9.20Let us use Customer relation shown in Table 9.10 to understand the working of string functions. a) Display customer name in lower case and c…Preview
+Worked Examples1 question
  1. Example 9.21Let us use the EMPLOYEE table of CARSHOWROOM database to illustrate the working of some of the date and time functions. a) Select the day, m…Preview
+Activities1 question
  1. Activity 9.10Using the table SALE of CARSHOWROOM database, write SQL queries for the following: a) Display the InvoiceNo and commission value rounded off…Preview
+Activities1 question
  1. Activity 9.11Using the table INVENTORY from CARSHOWROOM database, write sql queries for the following: a) Convert the CarMake to uppercase if its value s…Preview
+Activities1 question
  1. Activity 9.12Using the table EMPLOYEE from CARSHOWROOM database, write SQL queries for the following: a) Display employee name and the last 2 characters…Preview
+Activities1 question
  1. Activity 9.13Using the table EMPLOYEE of CARSHOWROOM database, list the day of birth for all employees whose salary is more than 25000.Preview
+Activities1 question
  1. Activity 9.14a) Find sum of Sale Price of the cars purchased by the customer having ID C0001 from table SALE. b) Find the maximum and minimum commission…Preview
+Think & Reflect1 question
  1. Q9Can we use arithmetic operators (+, -. *, or /) on date functions?Preview
9.8.2

Aggregate Functions

2 Q

Aggregate functions are also called multiple row functions. Unlike single row functions that work on one row at a time, these functions operate on a set of records as a whole and return a single value…

9.9

GROUP BY Clause in SQL

The GROUP BY clause is used when you need to work with groups of rows that share the same value in a particular column, rather than with individual rows.

9.10

Operations on Relations

Operations on relations let us combine or compare data from two tables. The textbook introduces three such operations: Union, Intersection, and Set Difference.

9.10.1

Union (∪)

The UNION operation combines the selected rows from two tables into a single result set. When you apply UNION, every row that appears in either of the two tables is included in the output.

(A)

Retrieve selected columns

The most basic use of SELECT is to retrieve only the columns you need, instead of every column in the table.

9.10.2

Intersect (∩)

The INTERSECT operation in SQL is used to find common rows between two tables. It corresponds to the mathematical intersection of sets, represented by the symbol ∩.

(B)

Renaming of columns

In case we want to rename any column while displaying the output, it can be done by using the alias AS.

9.10.3

Minus (−)

The MINUS operation (also called set difference) is used to find rows that exist in the first table but not in the second table. It is represented by the symbol − (minus).

(C)

Distinct Clause

By default, SQL shows all the data retrieved through a query as output. However, there can be duplicate values.

9.10.4

Cartesian Product (X)

The Cartesian product (also called the cross product) is a relational algebra operation that combines every row from one table with every row from another table. It is denoted by the symbol X.

9.11

Using Two Relations in a Query

Till now, every query in this chapter has worked with data from a single relation at a time. This section introduces writing queries that use two relations together — the foundation for combining rela…

(D)

WHERE Clause

The WHERE clause is used to retrieve data that meet some specified conditions. In the OFFICE database, more than one employee can have the same salary.

(E)

Membership operator IN

Example 9.7 The following query selects details of all the employees who work in the departments having deptid D01, D02 or D04: sql mysql SELECT FROM EMPLOYEE - WHERE DeptId = 'D01' OR DeptId = 'D02'…

9.11.1

Cartesian Product on Two Tables

The Cartesian product is the operation that sits underneath every multi-table query in SQL. When you list more than one table in the FROM clause, separated by commas, the database engine first combine…

9.11.2

Join on Two Tables

A database is useful because it stores related data across multiple tables. But to answer real questions, you often need to bring that data back together.

(F)

ORDER BY Clause

ORDER BY clause is used to display data in an ordered form with respect to a specified column. By default, ORDER BY displays records in ascending order of the specified column's values.

(G)

Handling NULL Values

SQL supports a special value called NULL to represent a missing or unknown value. It is important to note that NULL is different from 0 (zero).

Summary

- A database is a collection of related tables; MySQL is a 'relational' DBMS. - DDL (Data Definition Language) includes SQL statements such as CREATE TABLE, ALTER TABLE, and DROP TABLE.

(H)

Substring pattern matching

Many a times we come across situations where we do not want to query by matching exact text or value. Rather, we are interested to find matching of only a few characters or values in column values.

(A)

Math Functions

Three commonly used math functions are POWER(), ROUND(), and MOD().

(B)

String Functions

String functions perform operations on alphanumeric data stored in tables. They can change case, extract substrings, calculate string length, and more.

(C)

Date and Time Functions

Date and time functions perform operations on date and time data. They can display the current date, extract elements of a date (day, month, year), and show the day of the week.

Exercises

CBSE Sample Papers

Questions from official CBSE sample papers.

+Show 38 questions38 questions
  1. Q1While creating a table, which constraint does not allow insertion of duplicate values in the table ? (A) UNIQUE (B) DISTINCT (C) NOT NULL (D…Preview
  2. Q2Which of the following is a DML command in SQL ? (A) UPDATE (B) CREATE (C) ALTER (D) DROPPreview
  3. Q3Which aggregate function in SQL displays the number of values in the specified column ignoring the NULL values ? (A) len() (B) count() (C) n…Preview
  4. Q4In MYSQL, which type of value should not be enclosed within quotation marks ? (A) DATE (B) VARCHAR (C) FLOAT (D) CHARPreview
  5. Q5Suman has created a table named WORKER with a set of records to maintain the data of the construction sites, which consists of WID, WNAME, W…Preview
  6. Q6Assume that you are working in the IT Department of a Creative Art Gallery (CAG), which sells different forms of art creations like Painting…Preview
  7. Q7Which of the following SQL command can change the degree of the existing relation ? (A) DROP TABLE (B) ALTER TABLE (C) UPDATE…SET (D) DELETEPreview
  8. Q8Which aggregate function in SQL returns the smallest value from a column in a table ? (A) MIN() (B) MAX() (C) SMALL() (D) LOWER()Preview
  9. Q9Assertion (A) : The PRIMARY KEY constraint in SQL ensures that each value in the column(s) is unique and cannot be NULL. Reason (R) : Candid…Preview
  10. Q10Ms. Zoya is a Production Manager in a factory which packages mineral water. She decides to create a table in a database to keep track of the…Preview
  11. Q11Abhishek has created a table, named STOCK, with a set of records to maintain the data of packaged milk in his shop. After creating the table…Preview
  12. Q12Assume that you are the Manager of the Loans department of a Finance House. To keep track of the loans you have created two tables : CUSTOME…Preview
  13. Q13The SELECT statement when combined with ____ clause, returns records without repetition. (A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULLPreview
  14. Q14In SQL, the aggregate function which will display the cardinality of the table is ____. (A) sum() (B) count(*) (C) avg() (D) sum(*)Preview
  15. Q15Which of the following is not a DDL command in SQL? (A) DROP (B) CREATE (C) UPDATE (D) ALTERPreview
  16. Q16Consider the table ORDERS given below and write the output of the SQL queries that follow: ORDNO ITEM QTY RATE ORDATE 1001 RICE 23 120 2023-…Preview
  17. Q17Consider the table Projects given below: Table: Projects P_id Pname Language Startdate Enddate P001 School Management System Python 2023-01-…Preview
  18. Q18Consider the tables Admin and Transport given below: Table: Admin S_id S_name Address S_type S001 Sandhya Rohini Day Boarder S002 Vedanshi R…Preview
  19. Q19Write the output of SQL queries (a) to (d) based on the table VACCINATION_DATA given below: Table: VACCINATION_DATA VID Name Age Dose1 Dose2…Preview
  20. Q20Write the output of SQL queries (a) and (b) based on the following two tables DOCTOR and PATIENT belonging to the same database: Table: DOCT…Preview
  21. Q21Differentiate between Candidate Key and Primary Key in the context of Relational Database Model. OR Consider the following table PLAYER: Tab…Preview
  22. Q22(i) A SQL table ITEMS contains the following columns: INO, INAME, QUANTITY, PRICE, DISCOUNT Write the SQL command to remove the column DISCO…Preview
  23. Q23Rohan is learning to work upon Relational Database Management System (RDBMS) application. Help him to perform the following tasks: (a) To op…Preview
  24. Q24Write SQL queries for (a) to (d) based on the tables PASSENGER and FLIGHT given below: Table: PASSENGER PNO NAME GENDER FNO 1001 Suresh Male…Preview
  25. Q25Fill in the blank: .............. clause is used with SELECT statement to display data in a sorted form with respect to a specified column.…Preview
  26. Q26(a) Differentiate between CHAR and VARCHAR data types in SQL with appropriate example. OR (b) Name any two DDL and any two DML commands.Preview
  27. Q27(a) Write the outputs of the SQL queries (i) to (iv) based on the relations COMPUTER and SALES given below: Table: COMPUTER PROD_ID PROD_NAM…Preview
  28. Q28Fill in the blank : _________ statement of SQL is used to insert new records in a table. (a) ALTER (b) UPDATE (c) INSERT (d) CREATEPreview
  29. Q29Explain the usage of HAVING clause in GROUP BY command in RDBMS with the help of an example.Preview
  30. Q30(a) Differentiate between IN and BETWEEN operators in SQL with appropriate examples. OR (b) Which of the following is NOT a DML command. DEL…Preview
  31. Q31(a) Consider the following tables Student and Sport : Table : Student ADMNO NAME CLASS 1100 MEENA X 1101 VANI XI Table : Sport ADMNO GAME 11…Preview
  32. Q32Write the output of any three SQL queries (i) to (iv) based on the tables COMPANY and CUSTOMER given below : Table : COMPANY CID C_NAME CITY…Preview
  33. Q33Which SQL command is used to add a new attribute in a table?Preview
  34. Q34Which SQL aggregate function is used to count all records of a table?Preview
  35. Q35Write the full form of the following abbreviations: (i) DDL (ii) DMLPreview
  36. Q36Write outputs for SQL queries (i) to (iii), which are based on the following tables, CUSTOMERS and PURCHASES: Table : CUSTOMERS CNO CNAME CI…Preview
  37. Q37Write SQL queries for (i) to (iv), which are based on the tables: CUSTOMERS and PURCHASES given in the question 4(g): (i) To display details…Preview
  38. Q38Write SQL queries for (i) to (iv) and write outputs for SQL queries (v) to (viii), which are based on the table given below: Table : TRAINS…Preview