Some More Programming Examples and Coding Challenges Week-5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Some More Programming Examples and Coding Challenges -week5

Practice Activity-1: Please identify the primary key from


Employee table and Department Table
Employee-Table

Employee-Id Employee- Employee- Employee-email Salary


name address
1 ABS Dggdgggg [email protected] 566
2 Gfgf Gfgfgfgfgf [email protected] 66
3 Gfdgd Ggddsgsdg [email protected] 678
m
4 Dgg Fgshfh [email protected] 444
m
6 gfgfgf fgdgsssgg [email protected] 345
m

Department-Id Department - Department - Department -email


name address
501 Computer ABA [email protected]
Science
502 Biology ABC [email protected]
503 Botany BNH [email protected]
504 Chemistry HHH [email protected]
505 Engineering HHH [email protected]

Practice Activity-2: Please identify and add foreign key to


the Employee-Table to create a relationship between
employee table and department table.
__________________________________________________
SQL CREATE TABLE statement
SQL CREATE TABLE statement is used to create a new table in a database. Here is the
general syntax for the CREATE TABLE command.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
Some More Programming Examples and Coding Challenges -week5

...
columnN datatype
);
In this syntax:

 CREATE TABLE is the SQL keyword that tells the database system to create a new
table.
 table_name is the name of the table you want to create.
 column1, column2, ..., columnN are the names of the columns in the table.
 datatype specifies the type of data that each column can hold. Examples of data
types include INTEGER, TEXT, REAL, BLOB, and others, depending on the database
system you are using.
You can also specify constraints such as PRIMARY KEY, NOT NULL, UNIQUE, and FOREIGN
KEY within the CREATE TABLE statement to enforce data integrity rules. Here's an example
illustrating the use of some constraints:
CREATE TABLE Students (
student_id INTEGER PRIMARY KEY,
student_name TEXT NOT NULL,
student_age INTEGER,
address TEXT,
grade TEXT
);
In this example, a table named Students is created with columns student_id, student_name,
student_age, address, and grade. The student_id column is defined as the primary key,
while the student_name column is marked as NOT NULL.

The SQL INSERT statement


The SQL INSERT statement is used to insert new rows or records into a table in a database.
Here is the general syntax for the INSERT statement:
INSERT INTO table_name (column1, column2, column3, ..., columnN)
VALUES (value1, value2, value3, ..., valueN);

In this syntax:
Some More Programming Examples and Coding Challenges -week5

 INSERT INTO is the SQL keyword that specifies the action of inserting data.
 table_name is the name of the table where you want to insert data.
 column1, column2, ..., columnN are the names of the columns in the table into
which you want to insert data.
 value1, value2, ..., valueN are the values to be inserted into the corresponding
columns.
Here's an example illustrating the use of the INSERT statement:

INSERT INTO Students (student_id, student_name, student_age, address, grade)


VALUES (1, 'John Doe', 20, '123 Main St', 'A');
In this example, the INSERT statement adds a new record to the Students table. It specifies
values for the columns student_id, student_name, student_age, address, and grade. The
actual values in the VALUES clause correspond to the data you want to insert into the table.
If you are inserting values into all columns of the table, you can omit the column names
from the INSERT INTO statement, like this:
INSERT INTO Students
VALUES (1, 'John Doe', 20, '123 Main St', 'A');
This syntax will work if the order of the values matches the order of the columns in the
table. However, it's generally considered good practice to explicitly specify the columns in
the INSERT INTO statement to avoid any confusion or potential issue.
_______________________________________________________________________

The SQL DELETE Command


The SQL DELETE statement is used to delete existing records from a table in a database.
Here is the general syntax for the DELETE command:
DELETE FROM table_name
WHERE condition;
In this syntax:

 DELETE FROM is the SQL keyword that indicates the action of deleting data from a
table.
 table_name is the name of the table from which you want to delete data.
 WHERE is an optional clause that allows you to specify a condition that must be met
for the deletion to occur. If you omit the WHERE clause, all records in the table will
be deleted.
Here's an example illustrating the use of the DELETE statement:
Some More Programming Examples and Coding Challenges -week5

DELETE FROM Students


WHERE student_id = 1;
In this example, the DELETE statement removes the record from the Students table where
the student_id is equal to 1. If the WHERE clause is omitted, all records in the Students table
will be deleted.

You can also use more complex conditions in the WHERE clause, such as using logical
operators like AND, OR, and NOT to specify multiple conditions for the deletion.

SQL UPDATE COMMAND


The SQL UPDATE command is used to modify the existing records in a table. It allows you to
change the values of one or more columns in one or more rows that meet the specified
condition. The main purpose of the UPDATE command is to make changes to the data
already stored in the database.

Syntax
PDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Assume we have a table named employees with columns employee_id, employee_name,
salary, and hire_date. Let's say we want to update the salary of an employee with ID 123 to
$60,000.
UPDATE employees
SET salary = 60000
WHERE employee_id = 123;
This command will update the salary column of the employees table to 60000 for the row
where the employee_id is 123.

ORDER BY SQL COMMAND


Some More Programming Examples and Coding Challenges -week5

The ORDER BY command in SQL is used to sort the result set by one or more columns. It
arranges the rows returned by a query in either ascending or descending order based on
the specified column(s). Here is the basic syntax for using the ORDER BY clause:

Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
In this syntax:

 column1, column2, ... are the columns you want to select from the table.
 table_name is the name of the table from which you want to retrieve data.
 ORDER BY specifies the column(s) you want to sort the result set by.
 [ASC | DESC] indicates whether the sorting should be in ascending (ASC) or
descending (DESC) order. ASC is the default if not specified.

Example:
Let's say you have a table named students with columns student_id, student_name, and
age. To retrieve the data sorted by the age column in ascending order, the SQL query would
be:
SELECT student_id, student_name, age
FROM students
ORDER BY age ASC;
This query would return the student_id, student_name, and age for all records in the
students table, sorted by the age column in ascending order.
You can also use multiple columns in the ORDER BY clause to sort the data by multiple
criteria. For example:
SELECT student_id, student_name, age
FROM students
ORDER BY age ASC, student_name ASC;
This query would sort the records first by the age column in ascending order, and for
records with the same age, it would then sort by the student_name column in ascending
order.
____________________________________________________________________
Some More Programming Examples and Coding Challenges -week5

Practice Programming Activity-3


Objective: The Python program provided creates a SQLite database named 'student.db' and
a table named 'Student_Information'. It then adds five records, each containing information
about a student, into the table. Finally, it displays the contents of the 'Student_Information'
table.

import sqlite3

# Create a connection to the database (or it will create a new one if it doesn't exist)
conn = sqlite3.connect('student.db')

# Create a cursor object to execute SQL commands


cursor = conn.cursor()

# Create a table to store student information


cursor.execute('''
CREATE TABLE IF NOT EXISTS Student_Information (
student_id INTEGER PRIMARY KEY,
name TEXT,
address TEXT,
fname TEXT
)
''')

# Insert data into the table using separate insert statements


cursor.execute("INSERT INTO Student_Information (student_id, name, address, fname)
VALUES (1, 'John Doe', '123 Main St, City, State', 'Michael Doe')")
cursor.execute("INSERT INTO Student_Information (student_id, name, address, fname)
VALUES (2, 'Jane Smith', '456 Maple Ave, Town, State', 'David Smith')")
Some More Programming Examples and Coding Challenges -week5

cursor.execute("INSERT INTO Student_Information (student_id, name, address, fname)


VALUES (3, 'Alex Johnson', '789 Oak Rd, Village, State', 'Chris Johnson')")
cursor.execute("INSERT INTO Student_Information (student_id, name, address, fname)
VALUES (4, 'Emily Williams', '567 Pine Lane, County, State', 'James Williams')")
cursor.execute("INSERT INTO Student_Information (student_id, name, address, fname)
VALUES (5, 'Daniel Brown', '432 Cedar Court, District, State', 'Andrew Brown')")

# Commit the changes


conn.commit()

# Display the records in the Student_Information table


cursor.execute("SELECT * FROM Student_Information")
print("Student Information table contents:")
for row in cursor.fetchall():
print(row)

# Close the connection


conn.close()

print("Database 'student.db' and the 'Student_Information' table created successfully.")


Explanation: Importing the SQLite Module: The program begins by importing the sqlite3
module, which is used for working with SQLite databases in Python.

 Connecting to the Database: The program establishes a connection to the SQLite


database named 'student.db' using the connect function. If the database does not
already exist, it will be created.
 Creating the Table: The program creates a table named 'Student_Information' using
the execute method. This table has four fields: student_id, name, address, and
fname. The student_id field is specified as the primary key.
 Inserting Data: The program inserts five records into the 'Student_Information' table
using the execute method. Each record represents information about a student,
including their student_id, name, address, and fname.
 Committing Changes: After inserting the data, the program calls the commit method
to save the changes made to the database.
Some More Programming Examples and Coding Challenges -week5

 Displaying the Table Contents: The program fetches and displays the contents of the
'Student_Information' table using the SELECT query and a loop that iterates over the
fetched data.
 Closing the Connection: Finally, the program closes the connection to the database.

Programming Practice Activity-4: Modified Version of


Practice Activity-3
This program insert records into table using the cursor.execute many command.

import sqlite3

# Create a connection to the database (or it will create a new one if it doesn't exist)
conn = sqlite3.connect('student.db')

# Create a cursor object to execute SQL commands


cursor = conn.cursor()

# Create a table to store student information. (''' ''') allows you to write the CREATE TABLE
SQL query across multiple lines without encountering syntax errors or the need for escaping
special characters. It is a way to make the code more readable and manageable.
# When you use the "CREATE TABLE IF NOT EXISTS" statement, the database checks if a
table with the specified name already exists. If it does not, the database creates a new table
with the specified structure. If a table with the same name already exists, the database does
not create a new table and simply continues without any changes to the existing table.

cursor.execute('''
CREATE TABLE IF NOT EXISTS Student_Information (
student_id INTEGER PRIMARY KEY,
name TEXT,
address TEXT,
fname TEXT
)
Some More Programming Examples and Coding Challenges -week5

''')

# Insert some sample data into the table ( List of tuples or list of record ).
students_data = [
(1, 'John Doe', '123 Main St, City, State', 'Michael Doe'),
(2, 'Jane Smith', '456 Maple Ave, Town, State', 'David Smith'),
(3, 'Alex Johnson', '789 Oak Rd, Village, State', 'Chris Johnson'),
(4, 'Emily Williams', '567 Pine Lane, County, State', 'James Williams'),
(5, 'Daniel Brown', '432 Cedar Court, District, State', 'Andrew Brown')
]

# Insert the data into the table


cursor.executemany('''
INSERT INTO Student_Information (student_id, name, address, fname) VALUES (?, ?, ?, ?)
''', students_data)

# Commit the changes


conn.commit()

# Display the records in the Student_Information table


cursor.execute("SELECT * FROM Student_Information")
print("Student Information table contents:")
for row in cursor.fetchall():
print(row)

# Close the connection


conn.close()

print("Database 'student.db' and the 'Student_Information' table created successfully.")


Some More Programming Examples and Coding Challenges -week5

You might also like