Chapter 09: Structured Query language
1. What is an SQL? Mention the important points while using SQL.
SQL (Structured Query Language) is a special-purpose language used to access and manipulate data
in a database. It is used instead of writing application programs, especially in the context of Database
Management Systems (DBMS).
Following are some important points to be kept in mind while using SQL:
• SQL is case insensitive.
• Always end SQL statements with a semicolon (;).
• To enter multiline SQL statements, we don’t write “;” after the first line. We press the Enter key to
continue on the next line. The prompt mysql> then changes to “->”, indicating that statement is
continued to the next line. After the last line, put “;” and press enter.
2. Write a note on data types available in MySql.
Data type of an attribute indicates the type of data value that an attribute can have. It also decides the
operations that can be performed on the data of that attribute.
CHAR(n)
Fixed-length character string. - Length n can be from 0 to 255.
e.g., CHAR(10) stores exactly 10 characters; unused space is padded with spaces.
VARCHAR(n)
Variable-length character string.Length n up to 65535. Only actual input length occupies space.
INT
Integer values. - Occupies 4 bytes. - Use BIGINT (8 bytes) for larger numbers.
FLOAT
Decimal (floating-point) numbers. - Occupies 4 bytes.
DATE Stores dates in 'YYYY-MM-DD' format. - Range: '1000-01-01' to '9999-12-31'.
3. What are constraints? Explain different constraints available in MySql.
Constraints are rules or restrictions placed on data in a table to ensure accuracy and reliability.
NOT NULL - Value must be provided; cannot be left empty (NULL).
UNIQUE – Ensures that all the values in the column must be different.
DEFAULT - Assigns a default value if no value is entered.
PRIMARY KEY - Uniquely identifies each row in a table. Must be unique and not null.
FOREIGN KEY - Refers to a primary key in another table. Used to create relationships.
4. Explain DDL commands with syntax and example.
SQL allows us to write statements for defining, modifying and deleting relation schemas. These are
part of Data Definition Language (DDL).
CREATE Database
To create a database, we use the CREATE DATABASE statement.
Syntax: CREATE DATABASE databasename;
Eg : mysql> CREATE DATABASE Student;
CREATE Table
To define relations in this database and specify attributes for each relation along with data type and
constraint (if any) for each attribute. This is done using the CREATE TABLE statement.
Syntax:
CREATE TABLE tablename
( attributename1 datatype constraint,
attributename2 datatype constraint,
:
attributenameN datatype constraint);
Example: mysql> CREATE TABLE STUDENT(
-> RollNumber INT,
-> SName VARCHAR(20),
-> SDateofBirth DATE,
-> GUID CHAR (12),
-> PRIMARY KEY (RollNumber));
Describe Table
To view the structure of an already created table using the DESCRIBE statement or DESC statement.
Syntax:
DESCRIBE tablename;
Example:
mysql> DESCRIBE STUDENT;
ALTER Table
To add/remove an attribute or to modify the data type of an existing attribute or to add constraint in
attributes. In all such cases, we need to change or alter the structure (schema) of the table by using
the alter statement.
Syntax: ALTER TABLE table_name ADD attribute name DATATYPE;
Example: > ALTER TABLE STUDENTS ADD MARKS INT;
DROP Statement
We can use a DROP statement to remove a database or a table permanently from the system.
However, one should be very cautious while using this statement as it cannot be undone.
Syntax to drop a table: DROP TABLE table_name;
Syntax to drop a database: DROP DATABASE database_name;
5. Explain DML Commands with syntax and example.
To populate records in the table, INSERT statement is used. Also, table records can be deleted or
updated using DELETE and UPDATE statements. These SQL statements are part of Data
Manipulation Language (DML).
Data Manipulation using a database means either insertion of new data, removal of existing data or
modification of existing data in the database.
INSERTION of Records INSERT INTO statement is used to insert new records in a table.
syntax : INSERT INTO tablename VALUES(value 1, value 2,....);
Example:
INSERT INTO student VALUES (4444, 'Ashok Kumar',’2008-02-24,540214587126);
Data Updation:
To make changes in the value(s) of one or more columns of existing records in a table, The
UPDATE statement is used to make such modifications in existing data.
Syntax: UPDATE table_name
SET attribute1 = value1, attribute2 = value2, ...
WHERE condition;
Example: UPDATE student
marks= 555
-> WHERE rollNumber = 4444;
Data Deletion
DELETE statement is used to delete/remove one or more records from a table.
Syntax: DELETE FROM table_name WHERE condition;
Example: mysql> DELETE FROM STUDENT WHERE RollNumber = 2222;
6. Write the syntax and example of select command.
The SQL statement
SELECT is used to retrieve data from the tables in a database and the output is also displayed in
tabular form. Syntax:
1) SELECT attribute1, attribute2, ... FROM table_name WHERE condition;
Example: SELECT SName, SDateofBirth -> FROM STUDENT -> WHERE RollNumber = 1;
2) SELECT * FROM table_name;
SELECT * FROM student;
7. Show the different ways of using select statement with different clauses/operators.
(A) Retrieve selected columns The following query selects employee numbers of all the employees:
mysql> SELECT RollNumber FROM Student;
(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'. mysql> SELECT SName as Name FROM STUDENT;
(C) Distinct Clause
The SELECT statement when combined with DISTINCT clause, returns records without repetition.
mysql> SELECT DISTINCT comb FROM STUDENT;
(D) WHERE Clause
The WHERE clause is used to retrieve data that meet some specified conditions.
SELECT sname FROM STUDENT
WHERE MARKS > 500;
(E) Membership operator IN
The IN operator compares a value with a set of values and returns true if the value belongs to that set.
mysql> SELECT * FROM STUDENT
-> WHERE Comb IN ('PCMB', 'PCMCs' );
mysql> SELECT * FROM STUDENT
-> WHERE Comb NOT IN ('PCMB');
(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. To
display the records in descending order, the DESC (means descending) keyword needs to be
written with that column.
mysql> SELECT * FROM STUDENT
-> ORDER BY Name;
mysql> SELECT * FROM STUDENT
-> ORDER BY Name DESC ;
(G) Handling NULL Values
SQL supports a special value called NULL to represent a missing or unknown value
mysql> SELECT * FROM STUDENT WHERE Marks IS NULL;
(H) Substring pattern matching
SQL provides a LIKE operator that can be used with the WHERE clause to search for a specified
pattern in a column.
The LIKE operator makes use of the following two wild card characters:
% (per cent)- used to represent zero, one, or multiple characters
The following query selects details of all those STUDENTS whose name starts with 'K'.
mysql> SELECT * FROM STUDENT
-> WHERE Sname like ‘K%’ ;
_ (underscore)- used to represent exactly a single character
The following query selects details of all those students whose name consists of exactly 5
letters and starts with any letter but has ‘ANYA’ after that.
mysql> SELECT * FROM STUDENT -> WHERE Sname like '_ANYA';
8. Explain the different ways of using Alter command.
(A) Add primary key to a relation
The following MySQL statement adds a primary key to the GUARDIAN relation:
mysql> ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);
(B) Add foreign key to a relation
Once primary keys are added, the next step is to add foreign keys to the relation (if any).
Following points need to be observed while adding foreign key to a relation:
• The referenced relation must be already created.
• The referenced attribute(s) must be part of the primary key of the referenced relation.
• Data types and size of referenced and referencing attributes must be the same.
Syntax: ALTER TABLE table_name ADD FOREIGN KEY(attribute name)
REFERENCES referenced_table_name (attribute name);
mysql> ALTER TABLE STUDENT
-> ADD FOREIGN KEY(GUID) REFERENCES GUARDIAN(GUID);
(C) Add constraint UNIQUE to an existing attribute
Syntax: ALTER TABLE table_name ADD UNIQUE (attribute name);
mysql> ALTER TABLE GUARDIAN ADD UNIQUE(GPhone);
(D) Add an attribute to an existing table
we may need to add an additional attribute in a table. It can be done using the ADD attribute
statement as shown in the following
Syntax: ALTER TABLE table_name ADD attribute name DATATYPE;
mysql> ALTER TABLE GUARDIAN ADD income INT;
(E) Modify datatype of an attribute
We can change data types of the existing attributes of a table using the following ALTER
statement. Syntax: ALTER TABLE table_name MODIFY attribute DATATYPE;
mysql> ALTER TABLE GUARDIAN MODIFY GAddress VARCHAR(40);
(F) Modify constraint of an attribute
When we create a table, by default each attribute takes NULL value except for the attribute
defined as primary key. We can change an attribute’s constraint from NULL to NOT NULL
using an alter statement.
Syntax: ALTER TABLE table_name MODIFY attribute DATATYPE NOT NULL;
mysql> ALTER TABLE STUDENT MODIFY SName VARCHAR(20) NOT NULL;
(G) Add default value to an attribute
If we want to specify default value for an attribute, then use the following
syntax: ALTER TABLE table_name MODIFY attribute DATATYPE DEFAULT default_value;
mysql> ALTER TABLE STUDENT MODIFY Comb char(4) DEFAULT ‘PCMB’ ;
(H) Remove an attribute Using ALTER
we can remove attributes from a table, as shown in the following
syntax: ALTER TABLE table_name DROP attribute;
To remove the attribute income from table GUARDIAN
mysql> ALTER TABLE GUARDIAN DROP income;
(I) Remove primary key from the table
Sometime there may be a requirement to remove primary key constraint from the table. In that
case, Alter table command can be used in the following way:
Syntax: ALTER TABLE table_name DROP PRIMARY KEY;
To remove primary key of table GUARDIAN
mysql> ALTER TABLE GUARDIAN DROP PRIMARY KEY;
9. Explain single row functions in MySql.
Single Row Functions
These are also known as Scalar functions. Single row functions are applied on a single value and
return a single value. Different single row functions under three categories — Numeric (Math),
String, Date and Time.
Numeric(Math) functions
Math Functions accept numeric value as input and return a numeric value as a result.
1. POWER(X,Y) / POW(X , Y)
Calculates X to the power Y.
mysql> SELECT POWER(2,3);
Output: 8
2. ROUND(N,D)
Rounds off number N to D number of decimal places.
Note: If D=0, then it rounds off the number to the nearest integer.
mysql>SELECT ROUND(2912.564, 1);
Output: 2912.6
mysql> SELECT ROUND(283.2);
Output: 283
3. MOD(A, B)
Returns the remainder after dividing number A by number B.
mysql> SELECT MOD(21, 2);
Output: 1
String Functions
String functions can perform various operations on alphanumeric data which are stored in a table.
They can be used to change the case (uppercase to lowercase or vice-versa), extract a substring,
calculate the length of a string and so on.
1) UCASE(string) OR UPPER(string)
Converts string into uppercase.
mysql> SELECT UCASE(“Informatics Practices”);
Output: INFORMATICS PRACTICES
2) LOWER(string) OR LCASE(string)
converts string into lowercase.
mysql> SELECT LOWER(“Informatics Practices”);
Output: informatics practices
3) MID(string, pos, n) OR SUBSTRING(string, pos, n) OR SUBSTR(string, pos, n)
Returns a substring of size n starting from the specified position (pos) of the string. If
n is not specified, it returns the substring from the position pos till end of the string.
mysql> SELECT MID(“Informatics”, 3, 4);
Output: form
mysql> SELECT MID(‘Informatics’,7);
Output: atics
4) LENGTH(string)
Return the number of characters in the specified string.
mysql> SELECT LENGTH(“Informatics”);
Output: 11
5) LEFT(string, N)
Returns N number of characters from the left side of the string.
mysql> SELECT LEFT(“Computer”, 4);
Output: Comp
6) RIGHT(string, N)
Returns N number of characters from the right side of the string.
mysql> SELECT RIGHT(“SCIENCE”, 3);
Output: NCE
7) INSTR(string, substring)
Returns the position of the first occurrence of the substring in the given string.
Returns 0, if the substring is not present in the string.
Mysql> SELECT INSTR(“Informatics”, “ma”);
Output: 6
8) LTRIM(string)
Returns the given string after removing leading white space characters.
Mysql> SELECT LTRIM(“ DELHI”);
Output: Delhi
9) RTRIM(string)
Returns the given string after removing trailing white space characters.
Mysql>SELECT RTRIM(“PEN “);
Output: PEN
10) TRIM(string)
Returns the given string after removing both leading and trailing white space
characters. Mysql> SELECT TRIM (“ INDIA “));
Output: INDIA
Date and Time Functions
There are various functions that are used to perform operations on date and time data.
1) NOW() It returns the current system date and time.
mysql> SELECT NOW();
Output: 2019-07-11 19:41:17
2) DATE() It returns the date part from the given date/time expression.
mysql> SELECT DATE(NOW());
Output: 2019-07-11
3) MONTH(date) It returns the month in numeric form from the date.
mysql> SELECT MONTH(NOW());
Output: 7
4) MONTHNAME(date) It returns the month name from the specified date.
mysql> SELECT MONTHNAME(“2003-11-28”);
Output: November
5) YEAR(date) It returns the year from the date.
mysql> SELECT YEAR(“2003-10- 03”);
Output: 2003
6) DAY(date) It returns the day part from the date.
mysql> SELECT DAY(“2003-03- 24”);
Output: 24
7) DAYNAME(date) It returns the name of the day from the date.
mysql> SELECT DAYNAME(“2019-07-11”);
Output: Thursday
10. Explain aggregate / multi row / group functions in MySql.
Aggregate functions are also called Multiple Row functions. These functions work on a set of
records as a whole and return a single value for each column of the records on which the function is
applied.
1) MAX(column) Returns the largest value from the specified column.
mysql> SELECT MAX(Marks) FROM Student;
Output: 551
2) MIN(column) Returns the smallest value from the specified column.
mysql> SELECT MIN(Marks) FROM Student;
Output: 250
3) AVG(column) Returns the average of the values in the specified column.
mysql> SELECT AVG(Marks) FROM Student;
Output:
4) SUM(column) Returns the sum of the values for the specified column.
mysql> SELECT SUM(Marks) FROM INVENTORY;
Output:
5) COUNT(*) Returns the number of records in a table.
Note: In order to display the number of records that matches a particular criteria in the
table, we have to use COUNT(*) with WHERE clause.
mysql> SELECT COUNT(*) from Students;
6) COUNT(column) Returns the number of values in the specified column ignoring the
NULL values. mysql> SELECT
COUNT(name) FROM Student;
11. Mention the difference between single row and multiple row functions.
Single Row Function Multiple Row function
1 Operates on a single row at a time Operates on group of rows
2 It returns one result per row It returns one result for a group of rows
3 Used with select, where, & order by clause Used with select statement only
4 Math, string & date functions are examples Max(), min(),avg(), sum(), count() are examples.
12. Explain the different operations performed on relations.
SQL allows operations that involve multiple tables (relations). These are called set operations and work when:
• Both tables have the same number of columns
• Corresponding columns have the same data types (domain compatibility)
UNION ( )∪
This operation is used to combine the selected rows of two tables at a time. If some rows are same in
both the tables, then result of the Union operation will show those rows only once.
INTERSECT ( ) ∩
Intersect operation is used to get the common tuples from two tables and is represented by symbol .∩
Minus(-)/set difference
This operation is used to get tuples/rows which are in the first table but not in the second table and
the operation is represented by the symbol - (minus).
Cartesian Product (X)
Cartesian product operation combines tuples from two relations. It results in all pairs of rows from
the two input relations, regardless of whether or not they have the same values on common attributes.
It is denoted as ‘X’. The degree of the resulting relation is calculated as the sum of the degrees of
both the relations under consideration. The cardinality of the resulting relation is calculated as the
product of the cardinality of relations on which Cartesian product is applied.
SQL Queries.
a) To view the structure of table.
b) To list the Name and Salary columns only.
c) To add a new column Department into table.
d) To Compute the total of salary.
e) To view the contents of table.