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
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…
Most relevant Q&A
Chapter contents
The NCERT structure, section by section. Open a section to see its questions, then read the concept-first solution.
Introduction
We have already seen that a Relational Database Management System (RDBMS) is the software that manages data organised into relations (tables).
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.
+−Activities1 question
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.
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…
Data Type of Attribute
A database table is made up of attributes (columns), and every attribute must be of a specific data type.
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…
+−Think & Reflect1 question
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.
CREATE Database
To create a new database in MySQL, you use the CREATE DATABASE statement. The syntax is straightforward:
CREATE Table
3 QOnce a database has been created, the next step is to define the relations (tables) that will store the data.
+−Worked Examples1 question
+−Activities1 question
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…
ALTER Table
3 QAfter 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.
+−Activities1 question
+−Think & Reflect1 question
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.
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…
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.
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.
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.
Insertion of Records
3 QThe 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:
+−Activities1 question
+−Activities1 question
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.
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.
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.
SELECT Statement
2 QThe 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.
+−Worked Examples1 question
Querying using Database OFFICE
19 QOrganisations 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
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Activities1 question
+−Activities1 question
+−Think & Reflect1 question
Modify constraint of an attribute
By default, MySQL allows every attribute to hold NULL — except whichever attribute is the primary key.
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…
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.
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…
Remove an attribute
Just as you can add a column, you can also remove one that's no longer needed, using ALTER TABLE ... DROP.
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.
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.
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.
Single Row Functions
10 QSingle 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
+−Worked Examples1 question
+−Worked Examples1 question
+−Worked Examples1 question
+−Activities1 question
+−Activities1 question
+−Activities1 question
+−Activities1 question
+−Activities1 question
+−Think & Reflect1 question
Aggregate Functions
2 QAggregate 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…
+−Worked Examples1 question
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.
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.
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.
Retrieve selected columns
The most basic use of SELECT is to retrieve only the columns you need, instead of every column in the table.
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 ∩.
Renaming of columns
In case we want to rename any column while displaying the output, it can be done by using the alias AS.
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).
Distinct Clause
By default, SQL shows all the data retrieved through a query as output. However, there can be duplicate values.
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.
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…
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.
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'…
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…
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.
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.
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.
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.
Math Functions
Three commonly used math functions are POWER(), ROUND(), and MOD().
String Functions
String functions perform operations on alphanumeric data stored in tables. They can change case, extract substrings, calculate string length, and more.
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
+−Show 8 questionsHide questions8 questions
- Q1Answer the following questions: a) Define RDBMS. Name any two RDBMS software. b) What is the purpose of the following clauses in a select st…Free
- Q2Write the output produced by the following SQL statements: a) SELECT POW(2,3); b) SELECT ROUND(342.9234,-1); c) SELECT LENGTH("Informatics P…Free
- Q3Consider the following MOVIE table and write the SQL queries based on it. | MovieID | MovieName | Category | ReleaseDate | ProductionCost |…Free
- Q4Suppose your school management has decided to conduct cricket matches between students of Class XI and Class XII. Students of each class are…Preview
- Q5Using the sports database containing two relations (TEAM, MATCH_DETAILS) and write the queries for the following: a) Display the MatchID of…Preview
- Q6A shop called Wonderful Garments who sells school uniforms maintains a database SCHOOLUNIFORM as shown below. It consisted of two relations…Preview
- Q7Consider the following table named "Product", showing details of products being sold in a grocery shop. | PCode | PName | UPrice | Manufactu…Preview
- Q8Using the CARSHOWROOM database given in the chapter, write the SQL queries for the following: a) Add a new column Discount in the INVENTORY…Preview
CBSE Sample Papers
Questions from official CBSE sample papers.
+−Show 38 questionsHide questions38 questions
- 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
- Q2Which of the following is a DML command in SQL ? (A) UPDATE (B) CREATE (C) ALTER (D) DROPPreview
- 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
- Q4In MYSQL, which type of value should not be enclosed within quotation marks ? (A) DATE (B) VARCHAR (C) FLOAT (D) CHARPreview
- 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
- 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
- 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
- Q8Which aggregate function in SQL returns the smallest value from a column in a table ? (A) MIN() (B) MAX() (C) SMALL() (D) LOWER()Preview
- 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
- 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
- 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
- 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
- Q13The SELECT statement when combined with ____ clause, returns records without repetition. (A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULLPreview
- Q14In SQL, the aggregate function which will display the cardinality of the table is ____. (A) sum() (B) count(*) (C) avg() (D) sum(*)Preview
- Q15Which of the following is not a DDL command in SQL? (A) DROP (B) CREATE (C) UPDATE (D) ALTERPreview
- 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
- Q17Consider the table Projects given below: Table: Projects P_id Pname Language Startdate Enddate P001 School Management System Python 2023-01-…Preview
- 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
- 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
- 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
- Q21Differentiate between Candidate Key and Primary Key in the context of Relational Database Model. OR Consider the following table PLAYER: Tab…Preview
- 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
- Q23Rohan is learning to work upon Relational Database Management System (RDBMS) application. Help him to perform the following tasks: (a) To op…Preview
- 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
- Q25Fill in the blank: .............. clause is used with SELECT statement to display data in a sorted form with respect to a specified column.…Preview
- 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
- 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
- Q28Fill in the blank : _________ statement of SQL is used to insert new records in a table. (a) ALTER (b) UPDATE (c) INSERT (d) CREATEPreview
- Q29Explain the usage of HAVING clause in GROUP BY command in RDBMS with the help of an example.Preview
- 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
- 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
- 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
- Q33Which SQL command is used to add a new attribute in a table?Preview
- Q34Which SQL aggregate function is used to count all records of a table?Preview
- Q35Write the full form of the following abbreviations: (i) DDL (ii) DMLPreview
- Q36Write outputs for SQL queries (i) to (iii), which are based on the following tables, CUSTOMERS and PURCHASES: Table : CUSTOMERS CNO CNAME CI…Preview
- 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
- 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