Database and SQL-2020
Database and SQL-2020
Database and SQL-2020
Value Points
1. A database (DB) is a collection of data describing the activities of one or more related
organization.
2. A Database Management System (DBMS) is software designed to assist in
maintaining & utilizing large collection of data.
Example:
Oracle, Microsoft, Sybase, MySQL,PostgreSQL, SQLite
3. SQL(Structured Query language) is a non procedural language used for querying
upon relational data bases(eg- Oracle , Sybase, SQL server , MYSQL etc).
4. DDL(Data definition language) is a part of SQL that facilitates defining/creating and
modifying the structure of table or view.
5. DML(Data manipulation language) is a part of SQL that facilitates insertion /
deletion/modification of data residing in the tables.
6. The fact about the data is stored in form of a table and is termed as Metadata.
5. A file containing metadata is called Data Dictionary.
6. Some of the useful data types supported by ANSI SQL are -
char (n): Fixed-length character data (string), n characters long. The
maximum size forn is 255 bytes (2000 in Oracle8). Note that a string of type
char is always padded on right with blanks to full length of n.
varchar2(n): Variable-length character string. The maximum size for n is
2000 (4000 inOracle8). Only the bytes used for a string require storage.
Example: varchar2(80).
number(n, d): Numeric data type for integers and reals. n- overall number of
digits, d- number of digits to the right of the decimal point. Data types
derived
from number are int[eger], dec[imal], smallint and real.
date: Date data type for storing date and time. The default format for a date
is: DD-MM-YY. Examples: ’13-OCT-94’, ’07-JAN-98’.
7. Constraints are used to enforce rules at table level when ever row is inserted,
updated/deleted from table. Some useful constraints are NOT NULL, UNIQUE ,
PRIMARY KEY and DEFAULT.
8. In many cases heading of columns may not be descriptive and hence it difficult to
understand. In such case we use columns alias. It will display column heading with
column alias.
9. In a table the order of row and column is not relevant. It has all unique tuples.
1
10.The SQL command for creating an empty table has the following form:
.........
[<table constraint(s)>]
);
12. In order to retrieve the information stored in the database, the SQL query language is
used.
from <table>
[ where<condition> ]
[ group by <column(s) ]
[ having<condition>]
13. To set conditions some special operators - between and , like ,is null , is not null , in
14. Aggregate functions are statistical functions such as count, min, max, sum ,avg etc. They
are used to compute a single value from a set of attribute values of a column:
15.For modifying attribute values of (some) tuples in a table, we use the update statement:
update<table> set <column i> = <expression i>, . . . ,<column j> = <expression j>
[where <condition>];
2
16.All or selected tuples can be deleted from a table using the delete command:
17. To Join Relations name both relations in from clause and set a comparisons in the where
18. having is a sub clause of group by and can not be used independently
19. Where clause imposes condition on entire table where as having imposes condition on
groups.
● Select all rows that satisfy the condition specified in the where clause.
● From these rows form groups according to the group by clause.
● Discard all groups that do not satisfy the condition in the having clause.
● Apply aggregate functions to each group.
● Retrieve values for the columns and aggregations listed in the select clause.
22. SQL is a Structured Query Language is based on a relational model. "A Relational Model
of Data for Large Shared Data Banks. SQL is often pronounced like "sequel". SQL
became a standard of the American National Standards Institute (ANSI).
23. The Python standard for database interfaces is the Python DB-API, which is used by
Python database interfaces. The DB-API has been defined as a common interface,
which can be used to access relational databases.
24. The DB API provides a minimal standard for working with databases using Python
structures and syntax.This API includes the following:
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
3
25.To use MySQL database using Python, we need to install on our machine; then just
type the script given below to implement MySQL within your program.
import MySQLdb
26. Opening a database connection and “stud” table:
db = MySQLdb.connect ("localhost","testprog","stud","PYDB")
27. The SQL syntax for creating a table "Employee" in the database "Company”:
CREATE TABLE Employee (
staff_number INT NOT NULL AUTO_INCREMENT,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE,
birth_date DATE,
PRIMARY KEY (staff_number) );
To do this directly from Python. To be capable to send a command to "SQL"we need a
cursor object. Usually, a cursor in SQL and databases is a control structure to traverse
over the records in a database.
We can define a SQL command with a triple quoted string in Python:
sql_command = """
CREATE TABLE Employee (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE,
birth_date DATE);"""
28. To populate the table we will have to use the "INSERT" command. Example:
sql_command = """INSERT INTO Employee (staff_number, fname, lname, gender,
birth_date)VALUES (NULL, "Williams", "Shakespeare", "m", "1961-10-25");"""
cursor.execute(sql_command)
29. To define the cursor object:
4
cursor = conn.cursor
30. Benefits of Python Database Programming:
Programming in Python is considerably simple and efficient with compared to
other languages, so as the database programming.
Python database is portable, and the program is also portable so both can give
an advantage in case of portability.
Python supports SQL cursors.
It also supports Relational Database systems.
The API of Python for the database is compatible with other databases also.
It is platform independent.
1 marks Questions :
Q1.Define the following terms:
(i) DBMS (ii) RDBMS (iii) Data Security (iv) Data Integrity (v) Relation
(vi) Domain (vii) Tuple (viii) Attribute (ix) Degree (x) Cardinality
Q2. What is data redundancy? What are the problems associated with it?
(i) Primary key (ii) Candidate key (iii) Alternate key (iv) Foreign key.
5
1. To change/open a database
Q14. What is SQL? What are different categories of commands available in SQL?
Q19. Write a query on the customers table whose output will exclude all customers with a
Q20. Write a query that selects all orders except those zeros or NULLs in the amount field.
Q21. Write a query that lists customers in descending order of rating. Output the rating field
Q22. Write a command that puts the following values, in their given order, into the
salesman
table:
Q23.Using standard sample table EMP provided by Oracle, Write following queries-
Empnonumber(4)
Enamechar(20)
6
Commnumber(6) // Commision
Q24. Write SQL statement to modify table structure such that it adds a column age in the
student table?
Q25.Write a query to find the list of employee’s whose age is greater than 30 or so given a
date of birth.
Q26. A Table named “Students” which contains studentid, subjectid and marks. Where there
are 10 subjects and 50 students. what is the Query to find out the Maximum marks
Q29.What is the role of UNIQUE constraint? How is PRIMARY KEY constraint different
7
from UNIQUEconstraint?
the database?
Q 31. Which method is used to retrieve all rows and single row? Using connectivity
2 Marks Questions -
Q2. What is Data Abstraction? Draw a diagram explaining various levels of data abstraction.
Q5. How constraints ensure the validity of data? Explain various types of constraints with
example.
Q8. What is database connectivity? Which package must be imported in python to create a
database
connectivity application?
Q9.
To select tuples with some esalary, Arun has written the following erroneous SQL
statement:
SELECT eid, salary FROMempsalary WHERE esalary=something;
Write the correct SQL statement.
Q 10. What are the basic steps to connect Python with MYSQL using table Members present
in the database‘Society’?
8
Q 11. Write a MySQL-Python connectivity to retrieve data, one record at a time, from city
table for employees with id less than10.
4 to 6 Marks Questions
TABLE: GRADUATE
Table: SPORTS
9
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Atheletics C
(i) Display the names of the students who have grade ‘C’ in either Game1 or
Game2 or both.
(ii) Display the number of students getting grade ‘A’ in Cricket.
(iii.) Display the names of the students who have same game for both Game1 and
Game2.
(iv) Display the games taken up by the students, whose name starts with ‘A’.
(v) Assign a value 200 for Marks for all those who are getting grade ‘B’ or grade ‘A’ in
both Game1 and Game2.
(vi) Arrange the whole table in the alphabetical order of Name.
(vii) Add a new column named ‘Marks’.
Table: Book
Book_id Book name Author_name Publisher Price Type Quantity
William
F0001 The Tears Hopkins First Publi. 650 Fiction 20
Brain &
T0001 My First c++ Brooke FPB 350 Text 10
Table: issued
Book_Id Quantity Issued
T0001 4
C0001 5
F0001 2
10
Write SQL query for (i) to (vi)
i. To show book name, Author name and price of books of First Pub. Publisher
ii. To list the names from books of text type
iii. To Display the names and price from books in ascending order of their prices.
iv. To increase the price of all books of EPB publishers by 50.
v. To display the Book_Id, Book_name and quantity issued for all books which have
been issued
vi. To insert a new row in the table issued having the following data. ‘F0003’, 1
Give the output of the following
i. Select Count(*) from Books
ii. Select Max(Price) from books where quantity >=15
iii. Select book_name, author_name from books where publishers=’first publ.’
iv. Select count(distinct publishers) from books where Price>=400
Table: Employees
11
Table: EmpSalary
count(*) >2;
iv. Select sum(benefits) from empsalary where designation =’Clerk’;
12
MCQ:
1. 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
(A) P and R
(B) P and S
(C) Q and R
(D) Q and S
2. Which is the subset of SQL commands used to manipulate Oracle Database
structures, including tables?
A. BETWEEN operator
B. LIKE operator
C. EXISTS operator
D. None of these
A. EXISTS operator
B. NOT operator
C. IS NULL operator
D. None of these
A. ALTER TABLE
B. MODIFY TABLE
C. CHANGE TABLE
D. All of the above
A. RENAME
B. REVOKE
C. GRANT
13
D. UPDATE
7. In SQL, which command is used to SELECT only one copy of each set of duplicable
rows
A. SELECT DISTINCT
B. SELECT UNIQUE
C. SELECT DIFFERENT
D. All of the above
8. A command that lets you change one or more fields in a record is
A. Insert
B. Modify
C. Look-up
D. All of the above
A. DISTINCTIVE
B. UNIQUE
C. DISTINCT
D. DIFFERENT
A. 6789
B. 2345
C. 1234
D. 456789
A. MAX
B. COUNT
C. SUM
D. All of the above
14
13. Which of the following command makes the updates performed by the transaction
permanent in the database?
A. ROLLBACK
B. COMMIT
C. TRUNCATE
D. DELETE
14. Which command undo all the updates performed by the SQL in the transaction?
A. ROLLBACK
B. COMMIT
C. TRUNCATE
D. DELETE
16. NULL is
17. Find the names of these cities with temperature and condition whose condition is
neither sunny nor cloudy
18. ............. joins two or more tables based on a specified column value not equaling a
specified column value in another table.
A. EQUIJOIN
B. NON-EQUIJOIN
15
C. OUTER JOIN
D. NATURAL JOIN
A. Selection operation.
B. Rename operation.
C. Join operation.
D. Projection operation.
21. SQL Query to delete all rows in a table without deleting the table (structure,
attributes, and indexes)
A. DELETE FROM table_name;
B. DELETE TABLE table_name;
C. DROP TABLE table_name;
D. NONE
24. If you want to allow age of a person > 18 in the column Age of table Person, then
which constraint will be applied to AGE column.
A. Default
B. Check
C. NOT NULL
D. None
25. To give a temporary name to a table, or a column in a table for more readability,
what is used?
A. SQL Wildcards
B. SQL aliases
C. SQL LIKES
16
D. SQL Comments
27. Which clause is used to combine rows from two or more tables based on a related
column between them.
A. SQL MATCH
B. SQL JOIN
C. SQL PATTERN
D. NONE
B.FALSE
Answers MCQ:
1. Answer: (B)
2. Answer: Option A
3. Answer: Option B
4. Answer: Option C
5. Answer: Option A
6. Answer: Option D
7. Answer: Option A
8. Answer: Option B
9. Answer: Option C
10. Answer: Option B
11. Answer: Option B
Explanation
INSTR Function:- The INSTR function in SQL is used to find the starting location of a pattern
in a string. The syntax for the INSTR function is as follows:
17
INSTR (str, pattern): Find the starting location of pattern in string str.
SUBSTR Function:- The Substring function in SQL is used to grab a portion of the stored
data. The syntax for the SUBSTR function is as follows:
SUBSTR(str,pos,len): Starting with the position pos in string str select the characters upto
the length len.
In the above query,
INSTR('abcabcabc', 'b') outputs 2 as the starting location of pattern
12. Answer: Option D
13. Answer: Option B
14. Answer: Option A
15. Answer: Option D
16. Answer: Option D
17. Answer: Option A
18. Answer: Option B
19. Answer: Option B
20. Answer: B and C
21. Answer: A
22. Answer: B
If you omit the WHERE clause, ALL records will be updated.
23. Answer: C
24. Answer: B
CHECK constraint is used to limit the value range placed in a column
25. Answer: B
26. Answer: A
27. Answer: B
28. Answer : Option B
Python Database
connection.commit()
cursor.commit()
18
2. Which method of cursor class is used to get the number of rows affected after any
of the insert/update/delete database operation executed from Python
cursor.rowcount
cursor.getaffectedcount
cursor.rowscount
3. Which method of cursor class is used to insert or update multiple rows using a
single query
cursor.executemany(query, rows)
cursor.execute(query, rows)
cursor.executmultiple(query, rows)
5. Which method of cursor class is used to fetch limited rows from the table
cursor.fetchsize(SIZE)
cursor.fetchmany(SIZE)
cursor.fetchonly(SIZE)
Ans:
1. connection.commit()
2. cursor.rowcount
3. cursor.executemany(query, rows)
4. Username, Password, Hostname, Database Name
5. cursor.fetchmany(SIZE)
19