100% found this document useful (1 vote)
2K views

Class 12 Full Syllabus Notes

Uploaded by

shaunak.ag2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

Class 12 Full Syllabus Notes

Uploaded by

shaunak.ag2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Page 1

NITIN PALIWAL
Page 2

CLASS 12 COMPUTER SCIENCE

PYTHON REVISION TOUR


INTRODUCTION TO PYTHON

Python is a high level, general purpose programming language.

ADVANTAGES OF PYTHON:

Readability: Clear and easy-to-understand syntax.


Large Standard Library: Extensive pre-built modules for various tasks.
Versatility: Suitable for web development, data science, and more.
Community Support: Active community providing resources and libraries.
Integration Capabilities: Easily integrates with other languages.
Rapid Development: Quick prototyping and development.
Cross-Platform: Compatible with major operating systems.
Scalability: Can be used in large-scale applications.

DISADVANTAGES OF PYTHON:

Speed: Interpreted nature may be slower than compiled languages.


Global Interpreter Lock (GIL): Limits thread execution on multi-core systems.
Mobile Development: Not the primary choice for mobile app development.
Design Restrictions: Some developers may find design philosophies limiting.
Memory Consumption: May use more memory, especially in resource-constrained
environments.
Threading Limitations: Challenges in leveraging multi-core processors.
Packaging Issues: Managing dependencies can be challenging.
Less Suitable for Resource-Intensive Tasks: Performance may not match
languages designed for resource-intensive tasks.

PYTHON: ADVANTAGES AND DISADVANTAGES

Advantages Disadvantages

1. Readability 1. Speed

2. Large Standard Library 2. Global Interpreter Lock (GIL)

NITIN PALIWAL
Page 3

Advantages Disadvantages

3. Versatility 3. Mobile Development

4. Community Support 4. Design Restrictions

5. Integration Capabilities 5. Memory Consumption

6. Rapid Development 6. Threading Limitations

7. Cross-Platform 7. Packaging Issues

8. Less Suitable for Resource-Intensive


8. Scalability Tasks

TOKENS

TOKENS

KEYWORD IDENTIFIER LITERALS PUNCTUATION OPERATOR

Reserved Symbols Symbols


Words with Names given Constants or used to that
predefined to various fixed values structure perform
meaning in program used in a code and operations
the elements. program. separate on variables
language. statements. and values.

Tokens: The smallest individual unit in a program is known as Token

LITERALS

IDENTIFIERS

KEYWORDS

OPERATORS

IDENTIFIERS NITIN PALIWAL


Page 4

KEYWORDS: RESEVED WORDS

Keyword Description
and Logical operator for conjunction (logical AND).
as Used to create an alias for a module or symbol.
assert Used for debugging to check if a condition is true.
break Terminates the loop prematurely.
class Declares a class in object-oriented programming.
continue Skips the rest of the loop's code and continues to the next iteration.
def Defines a function.
del Deletes an object or a part of an object.
elif Stands for "else if" and is used in conditional statements.
else Specifies a block of code to be executed if the condition is false.
except Catches exceptions during exception handling.
False Boolean value representing false.
finally Specifies a block of code to be executed, regardless of the try-except block.
for Used to iterate over a sequence (e.g., list, tuple, string).
from Used to import specific attributes or functions from a module.
global Declares a global variable.
if Conditional statement, executes code if a specified condition is true.
import Imports a module into the current program.
in Membership test, checks if a value exists in a sequence.
is Compares object identity.
lambda Creates an anonymous function (lambda function).
None Represents the absence of a value or a null value.
not Logical operator for negation (logical NOT).
or Logical operator for disjunction (logical OR).
pass Placeholder indicating no action to be taken.
raise Raises an exception.
return Exits a function and returns a value.
True Boolean value representing true.
try Defines a block of code to be tested for errors.
Creates a loop that executes a block of code as long as a specified
while condition is true.
Simplifies resource management (e.g., file handling) using a context
with manager.
Pauses the execution of a generator function and returns a value to the
yield caller.

NITIN PALIWAL
Page 5

IDENTIFIERS

Rules for Identifiers:

 Must start with a letter (a-z, A-Z) or an underscore (_).


 The remaining characters can be letters, underscores, or digits (0-9).
 Case-sensitive (myVar and myvar are different).

Examples of Identifiers:

Valid:
 my_variable
 count_1
 PI
 _underscore
 Name123
Invalid:
 123abc (starts with a digit)
 my-var (contains a hyphen)
 if (using a Python keyword)
 spaces not allowed
 #hash_symbol (contains a special character)

LITERALS

Single Quotes: 'Hello'


STRING Double Quotes: "World"
Triple Quotes: '''Multi-line string'''

BOOLEAN TRUE AND FALSE

Represents the
NONE absence of a value
LITERALS
Integers: 42, -10
Floats: 3.14, -0.5
NUMERIC Complex Numbers: 2 + 3j

Lists: [1, 2, 3]
LITERAL Tuples: (1, 2, 3)
Sets: {1, 2, 3}
COLLECTIONS Dictionaries: {'key': 'value'}

NITIN PALIWAL
Page 6

PUNCTUATIONS

 Definition: Punctuations are symbols used to structure code and separate


statements in Python.
 Common Punctuations:
 Semicolon (;):
 Separates multiple statements on the same line.
 Comma (,):
 Separates items in a tuple or elements in a list.
 Period (.):
 Accesses attributes or methods of an object.

OPERATORS

Perform mathematical operations like addition,


ARITHMETIC subtraction, multiplication, and division. Example: +, -,
*, /

COMPARISON Compare values and return True or False. Example: ==


(equal), != (not equal), > (greater than)
OPERATORS

LOGICAL Combine conditions and return True or False. Example:


and, or, not

ASSIGNMENT Assign values to variables. Example: =,+=,-=

IDENTITY Check if two objects are the same. Example: is/ is not

MEMBERSHIP Test if a value is a member of a sequence. Example:


in, in not

BITWISE Perform bit-level operations. Example: &, |, ^

NITIN PALIWAL
Page 7

EXECUTING PYTHON PROGRAMS

Printing a simple “Hello Maharathi” Program


INPUT: OUTPUT:

DATA TYPES IN PYTHON

DATA TYPES

NUMBER
1) Integer DICTIONARY
2) Float
3) Complex Number 1) Unordered collection of key-value pairs.
2) Defined by curly braces ({}) with key-value pairs.
3) Example: person = {'name': 'John', 'age': 25}

STRING
1) Sequences of characters. SET
2) Enclosed in single (' '), double
(" "), or triple quotes. 1) Unordered, mutable collection with unique
3) Example: text = "Hello, World!" elements.
2) Defined by curly braces ({}).
3) Example: unique numbers = {1, 2, 3}
BOOLEAN
1) Represents truth values: True or False.
2) Used for logical operations and TUPLE
conditions.
3) Example: is_true = True 1) Ordered, immutable collection.
2) Defined by parentheses (()).
3) Example: coordinates = (x, y)

LIST
1) Ordered, mutable collection.
2) Defined by square brackets ([]).
3) Example: numbers = [1, 2, 3]

NITIN PALIWAL
Page 8

CONDITIONAL STATEMENTS

If Statement:

 Executes a block of code if a condition is true.

INPUT:

EXAMPLE : Checking if a number is positive with the help of if statement

INPUT:

OUTPUT:

NITIN PALIWAL
Page 9

If-Else Statement:

 Executes one block of code if a condition is true and another if it's false.

INPUT:

EXAMPLE : Checking if a number is positive or negative

INPUT:

OUTPUT:

OUTPUT:

NITIN PALIWAL
Page 10

If-Elif-Else Statement:

 Checks multiple conditions in sequence.


 Executes the block corresponding to the first true condition.

INPUT:

EXAMPLE : Checking the sign of a number

INPUT:

OUTPUT:

NITIN PALIWAL
Page 11

SIMPLE PYTHON PROGRAMS

Absolute Value Program:

 Calculates the absolute value of a number.


 The absolute value of a number is never negative.
 Coverts negative number to positive and positive number remains the same

EXAMPLE : Finding absolute value of -5

INPUT: OUTPUT:

Sort 3 Numbers Program:

 Sorts three numbers in ascending order.

EXAMPLE : Sorting 3 numbers in ascending order

INPUT: OUTPUT:

NITIN PALIWAL
Page 12

Divisibility Check Program:

 Checks if a number is divisible by another number.

EXAMPLE : Checking if 10 is divisible by 2

INPUT:

OUTPUT:

NITIN PALIWAL
Page 13

FOR AND WHILE LOOP

For Loop Program:

 Iterates over a sequence (list, tuple, string, etc.) or a range of values.

EXAMPLE : Calculate the square of numbers using for loop

INPUT:

OUTPUT:

NITIN PALIWAL
Page 14

While Loop Programs:

 Repeats a block of code as long as a condition is true.

EXAMPLE : Calculating the factorial of a number using loop

INPUT:

OUTPUT:

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

INTRODUCTION TO FILES

A file is a named location on a secondary storage media where data are permanently
stored for later access.

TYPES OF FILES:

Text File:

 Consists of human-readable characters and can be opened by any text editor.


 Internally stored as bytes based on encoding schemes like ASCII or
UNICODE.
 Each character's value is stored as bytes, translated by text editors for human
readability.
 Lines terminated by special character, such as newline (\n) in Python.
 Commonly use whitespace, commas (,), or tabs (\t) to separate values.

Binary File:

 Contains non-human readable characters and symbols.


 Requires specific programs to access its contents.
 Stores data such as images, audio, video, etc.
 Opening with a text editor displays garbage values.
 Stored in a sequence of bytes; even a single bit change can corrupt the file.
 Difficult to fix errors as contents are not human-readable.

OPENING AND CLOSING A TEXT FILE

Opening a File:

 To open a file in Python, use the open() function with the syntax file_object =
open(file_name, access_mode).
 open() returns a file object (file handle) stored in file_object.
 file_object has attributes like file.closed, file.mode, and file.name, providing
information about the file.
 file_name should be the name of the file. If not in the current directory, specify
the complete path.
 access_mode is optional, representing the mode of file access. Also called
the processing mode. (e.g., 'r' for reading, 'w' for writing, 'a' for appending).
 Default mode is read ('r'), and files can be opened in binary mode ('b') for non-
textual data.

NITIN PALIWAL
Page 3

Closing a File:

 After read/write operations, it's good practice to close the file using the close()
method (file_object.close()).
 Python flushes unwritten data before closing.
 If a file object is reassigned or control exits a program block, the file is
automatically closed.

Opening a File using 'with' Clause:

 Python supports opening files using the with clause, ensuring automatic file
closure.
 Syntax: with open(file_name, access_mode) as file_object:
 Provides simpler syntax and automatic closure even if an exception occurs or
user forgets to close the file.

WRITING TO A TEXT FILE

 Open file in write ('w') or append ('a') mode.


 Write mode erases previous data, append mode adds new data at the end.
 Methods to write data:
 write(): Writes a single string.
 writelines(): Writes a sequence of strings.

NITIN PALIWAL
Page 4

The write() Method:

 Takes a string as argument and writes it to file.


 Returns number of characters written.
 Add newline character (\n) to mark end of line.

The writelines() Method:

 Writes multiple strings to file.


 Requires an iterable object (lists, tuples) containing strings.
 Does not return number of characters written.

Note:

 Numeric data needs to be converted to string before writing.


 write() writes data to buffer, which is then moved to permanent storage on
close().

Differences:

 write() erases previous data, append() adds to existing.


 Use flush() to clear buffer and forcefully write to file.

NITIN PALIWAL
Page 5

READING FROM A TEXT FILE

 Ensure file is opened in "r", "r+", "w+", or "a+" mode before reading.
 Three methods to read contents:
o read(): Reads specified number of bytes.
o readline(): Reads one complete line or specified number of bytes.
o readlines(): Reads all lines and returns as list of strings.

The read() Method:

 Syntax: file_object.read(n).
 Returns specified number of bytes.
 If no argument or negative number specified, reads entire file.

The readline() Method:

 Reads one complete line or specified number of bytes.


 Syntax: file_object.readline(n).
 Returns string.

The readlines() Method:

 Reads all lines and returns as list of strings.


 Syntax: file_object.readlines().

NITIN PALIWAL
Page 6

Additional Notes:

 Can loop over file object for line-by-line reading.


 Use split() to separate words in a line.
 Program example demonstrates writing to and reading from a file.

SETTING OFFSETS IN A FILE

Sequential access is common, but Python offers seek() and tell() for random
access.

The tell() Method:

 Returns current position of file object in bytes from beginning.


 Syntax: file_object.tell().

The seek() Method:

 Positions file object at specified position in file.


 Syntax: file_object.seek(offset [, reference_point]).
 offset: Number of bytes to move file object.
 reference_point: Starting position for offset calculation (0: beginning, 1: current,
2: end).

Note:

 By default, offset calculated from beginning of file.


 Example program demonstrates usage of seek() and tell().

NITIN PALIWAL
Page 7

Seeking Adventure:

 Use seek() and tell() to navigate the boundless realms of files.


 Find your position, explore, and unravel the mysteries hidden within the bytes.

CREATING AND TRAVERSING A TEXT FILE

Creating a File and Writing Data:

 Use open() method to create file.


 Specify filename and mode.
 Mode "w" overwrites existing file, "a" appends to it.
 If file doesn't exist, new file is created.

Traversing a File and Displaying Data:

 Open file in read mode ("r").


 Use readline() or read() to access data.
 Loop through lines and display.

Reading and Writing Operations:

 Use single file object for both reading and writing.


 Open file in "w+" mode.

NITIN PALIWAL
Page 8

THE PICKLE MODULE

Introduction:
 Python treats everything as objects, including data types like lists,
tuples, and dictionaries.
 Sometimes, it's necessary to store the current state of variables for
later retrieval.
 Pickle module helps serialize and deserialize Python objects, allowing
for easy storage and retrieval.

Serialization and Deserialization:


 Serialization transforms data or objects in memory to byte streams.
 Byte streams can be stored in files or sent over networks.
 Serialization is also called pickling.
 Deserialization is the reverse process of serialization.

Working with Pickle:


 Pickle deals with binary files, using dump() and load() methods.
 dump() serializes Python objects for writing to a binary file.
 load() deserializes data from a binary file.

Program Examples:
 Pickling Data:
 Example: Writing a list to a binary file.
 Method: pickle.dump(data_object, file_object).
 Unpickling Data:
 Example: Reading data from a binary file.
 Method: stored_object = pickle.load(file_object).

File Handling with Pickle:


 Writing and reading operations similar to text files.
 Example: Program to write and read employee records in a binary file.
 Methods: dump() for writing, load() for reading.

Conclusion:
 Pickle module offers a convenient way to store and retrieve Python
objects.
 Serialization and deserialization simplify data handling tasks, ensuring
data persistence and ease of use.

NITIN PALIWAL
Page 9

CSV FILES

What is CSV (Comma Separated Values)?

 CSV is a plain-text format for storing tabular data, where each line represents
a row, and fields are separated by commas.
 It is a widely used format for data interchange due to its simplicity and
compatibility with various applications.

Structure of CSV Files:

 CSV files consist of rows and columns.


 Rows are separated by newline characters ('\n').
 Columns within a row are separated by commas (','), although other delimiters
like tabs or semicolons can be used.

Working with CSV Files in Python:

a. Reading from a CSV file:

 Python provides the csv module for reading and writing CSV files.
 csv.reader() function is used to read data from a CSV file.
 Each row from the CSV file is returned as a list of strings.

b. Writing to a CSV file:

 To write data to a CSV file, use csv.writer() function.


 Data is provided as a list of lists, where each inner list represents a row to be
written

EXAMPLE:

import csv

with open("Employee.txt") as CSV_file:


CSV_reader = csv.reader(CSV_file, delimiter=',')
line_count = 0
for row in CSV_reader:
if line_count == 0:
print(f"Column names: {''.join(row)}")
line_count += 1
else:
print(f"\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.")
line_count += 1
print(f"Processed {line_count} lines.")

NITIN PALIWAL
Page 10

NCERT PROGRAMS:

NITIN PALIWAL
Page 11

NITIN PALIWAL
Page 12

NITIN PALIWAL
Page 13

NITIN PALIWAL
Page 14

NITIN PALIWAL
Page 15

COMMON QUESTIONS

Ques. What is the difference between r+ and w+ mode?

1. Opening a file: r+ mode opens the file if it exists, while w+ mode also
opens the file, but it deletes all the content present in the file. The pointer
in both cases is present at the start of the file.

2. Making a new file: If the file does not exist, r+ throws an exception error
of 'filenotfound' while w+ creates a new empty file. No error message is
thrown in w+ mode.

3. Reading a file: r+ helps in the complete reading of the file, while w+


doesn't allow the same. As opening a file in w+ erases all the contents of
the file, one can not read the content present inside the file.

4. Writing a file: r+ overwrites the file with the new content from the
beginning of the document, while w+ deletes all the old content and then
adds the new text to the file.

5. Error Message: r+ throws an exception or an error message if the file


does not exist, while w+ does not throw any error message; instead, it
creates a new file.

Ques. Differentiate between Text file and Binary file.

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

COMPUTER NETWORKS: INTRODUCTION

Computer Networks:

 Definition: Interconnection of computers/devices for data and resource


sharing.
 Sizes: Varies from small (few computers) to large (numerous devices).
 Components: Hosts (servers, desktops, laptops) and networking devices
(switches, routers, modems).
 Data Transmission: Wired or wireless, in packets.
 Node: Any device capable of data operations (e.g., modems, switches).

Benefits of Interconnectivity:

 Facilitates real-time information exchange (email, websites, calls).


 Enables resource sharing (printers, storage).
 Formation of personal networks via hotspots.

EVOLUTION OF NETWORKING

NITIN PALIWAL
Page 3

TYPES OF NETWORKS

1. Personal Area Network (PAN):

 Connects personal devices like computers, laptops, smartphones, within 10


meters.
 Can be wired (e.g., USB connection) or wireless (e.g., Bluetooth).

2. Local Area Network (LAN):

 Connects devices within a limited area (e.g., room, office, campus).


 Connectivity through wires, Ethernet cables, fiber optics, or Wi-Fi.
 Offers high-speed data transfer rates (10 Mbps to 1000 Mbps).
 Provides security for authenticated users.

NITIN PALIWAL
Page 4

3. Metropolitan Area Network (MAN):

 Extends LAN coverage to larger areas like cities or towns.


 Lower data transfer rates compared to LAN.
 Examples: Cable TV networks, broadband internet services.
 Can extend up to 30-40 km.

4. Wide Area Network (WAN):

 Connects LANs and MANs across different geographical locations.


 Utilizes wired or wireless connections.
 Examples: Connecting business branches, educational institutions,
government organizations.
 The Internet is the largest WAN, connecting billions of devices and LANs
globally.

NITIN PALIWAL
Page 5

NETWORK DEVICES

1. Modem:

 Converts digital signals to analog for transmission and vice versa.


 Modulator at sender's end, demodulator at receiver's end.

2. Ethernet Card (NIC):

 Network adapter for wired


connections.

 Mounts on computer's
motherboard.

 Supports data transfer from


10 Mbps to 1 Gbps.

 Each NIC has a unique MAC address.

3. RJ45 Connector:

 Eight-pin connector exclusively


for Ethernet cables.

 Standard interface seen at the


end of network cables.

NITIN PALIWAL
Page 6

4. Repeater:

 Regenerates weakened signals over cables.


 Necessary for signals traveling beyond 100 m.

5. Hub:

 Connects devices through wires.


 Broadcasts data to all ports.
 Susceptible to data collisions.

6. Switch:

 Connects multiple devices in a LAN.

 Selectively forwards packets based


on destination address.

 Drops noisy or corrupted signals.

7. Router:

 Connects LAN to the internet.


 Analyses and forwards data
packets between networks.
 Can repackage data for transmission
over different networks.

NITIN PALIWAL
Page 7

8. Gateway:

 Acts as entry/exit point between an organization's network and the internet.


 Routes data packets and maintains connection information.
 Often integrated with firewall for network security.

NETWORK TOPOLOGIES

1. Bus Topology:

 Each device connects to a shared transmission medium (bus).


 Data sent from a node are transmitted along the bus in both directions.
 Cheaper and easier to maintain.
 Less secure and less reliable.

NITIN PALIWAL
Page 8

2. Star Topology:

 Each device connects to a central node (hub or switch).


 Effective, efficient, and fast communication.
 Failure in central node affects entire network.
 Central node can broadcast data to all nodes or unicast data to specific
nodes.

3. Tree or Hybrid Topology:

 Hierarchical structure with multiple branches.


 Each branch may have different basic topologies like star, ring, or bus.
 Common in WANs connecting multiple LANs.
 Data passes through central device before reaching branches, allowing for
diverse connectivity.

NITIN PALIWAL
Page 9

NETWORK PROTOCOLS

1. HTTP (Hypertext Transfer Protocol):

 Used for web communication between clients and servers.


 Facilitates transfer of hypertext documents.

2. FTP (File Transfer Protocol):

 Enables file transfer between client and server.


 Supports upload, download, delete operations.

3. PPP (Point-to-Point Protocol):

 Establishes direct connections between nodes.


 Commonly used for dial-up internet connections.

4. SMTP (Simple Mail Transfer Protocol):

 Sends emails between servers.


 Defines email message transfer over the internet.

5. TCP/IP (Transmission Control Protocol/Internet Protocol):

 Fundamental internet communication protocol.


 TCP ensures reliable data delivery, while IP handles packet routing.

6. POP3 (Post Office Protocol version 3):

 Retrieves emails from server to client.


 Allows downloading of emails for offline access.

7. HTTPS (Hypertext Transfer Protocol Secure):

 Secure version of HTTP using encryption.


 Ensures secure data transmission, often used for online transactions.

8. Telnet:

 Provides remote access to computers over a network.


 Allows users to interact with remote systems via command-line interface.

9. VoIP (Voice over Internet Protocol):

 Transmits voice communication over the internet.


 Converts analog audio signals to digital data packets for transmission.

NITIN PALIWAL
Page 10

WEB SERVICES

1. WWW (World Wide Web):

 Global collection of interconnected web pages.


 Accessible through web browsers for information retrieval.

2. HTML (Hypertext Markup Language):

 Standard language for creating web pages.


 Defines structure and content using tags.

3. XML (Extensible Markup Language):

 Encodes documents for human and machine readability.


 Facilitates data exchange between systems.

4. Domain Names:

 Human-readable website addresses.


 Translated to IP addresses by DNS servers.

5. URL (Uniform Resource Locator):

 Specifies web resource location.


 Consists of protocol, domain name, and path.

6. Website:

 Collection of related web pages under a domain.


 Hosted on web servers and accessed via browsers.

7. Web Browser:

 Software for accessing and viewing web content.


 Interprets HTML documents for display.

8. Web Servers:

 Hosts and serves web content to clients.


 Responds to browser requests for web pages.

9. Web Hosting:

 Service providing server space for websites.


 Enables website accessibility on the internet.

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

DATA COMMUNICATION:

Concept:

 Definition: Data Communication = Data + Communication.


 Data: Refers to any text, image, audio, video, or multimedia files.
 Communication: Act of sending or receiving data.
 Data Communication: Exchange of data between networked devices.
 Devices: Personal computers, mobile phones, laptops, etc.

Components of Data Communication:

 Sender: Device capable of sending data over a network (e.g., computers,


mobile phones).
 Receiver: Device capable of receiving data from the network (e.g., computers,
printers).
 Message: Data or information exchanged between sender and receiver (e.g.,
text, image, audio).
 Communication Media: Path through which the message travels (e.g., wired
or wireless mediums like cables, satellite links).
 Protocols: Rules followed for successful data communication (e.g., Ethernet,
HTTP).

MEASURING CAPACITY OF COMMUNICATION MEDIA

Bandwidth:

 Definition: Range of frequencies available for data transmission.


 Relation to Data Transfer Rate: Higher bandwidth leads to higher data
transfer rate.
 Measurement: In Hertz (Hz).
 1 KHz = 1000 Hz
 1 MHz = 1000 KHz = 1,000,000 Hz

Data Transfer Rate:

 Definition: Number of bits transmitted per second between source and


destination.
 Also Known As: Bit rate.
 Measurement: In bits per second (bps).
 Units:
 1 Kbps = 2^10 bps = 1024 bps
 1 Mbps = 2^20 bps = 1024 Kbps
 1 Gbps = 2^30 bps = 1024 Mbps
 1 Tbps = 2^40 bps = 1024 Gbps

NITIN PALIWAL
Page 3

SWITCHING TECHNIQUES

Switching Overview:
 In a network with multiple devices, establishing one-to-one
communication is vital.
 Dedicated connections for each device pair (mesh or star topology) are
costly for large networks.
 Switching offers an alternative by routing data through various network
nodes.

Circuit Switching:
 Definition: Establishes a dedicated path between sender and receiver
before communication.
 Process: Identifies a connected sequence of links between network
nodes.
 Example: Traditional telephone calls where a physical path is
established from sender to receiver.
 Characteristic: All packets follow the same path set during connection.

Advantages of Circuit Switching:


 Guaranteed bandwidth: Circuit switching provides a dedicated path for
communication, ensuring that bandwidth is guaranteed for the duration of
the call.
 Low latency: Circuit switching provides low latency because the path is
predetermined, and there is no need to establish a connection for each
packet.
 Predictable performance: Circuit switching provides predictable
performance because the bandwidth is reserved, and there is no
competition for resources.
 Suitable for real-time communication: Circuit switching is suitable for real-
time communication, such as voice and video, because it provides low
latency and predictable performance.

Disadvantages of Circuit Switching:


 Inefficient use of bandwidth: Circuit switching is inefficient because the
bandwidth is reserved for the entire duration of the call, even when no data
is being transmitted.
 Limited scalability: Circuit switching is limited in its scalability because the
number of circuits that can be established is finite, which can limit the
number of simultaneous calls that can be made.
 High cost: Circuit switching is expensive because it requires dedicated
resources, such as hardware and bandwidth, for the duration of the call.

NITIN PALIWAL
Page 4

Packet Switching:
 Definition: Breaks down information into smaller packets for
transmission.
 Process: Packets are transmitted independently through the network.
 Route Flexibility: Packets may take different routes depending on
network conditions.
 Packet Structure: Each packet comprises a header with destination
address and main message part.
 Reassembly: At the destination, packets are reassembled to retrieve
the complete message.
 Channel Usage: Channels are occupied only during packet
transmission, freeing up for other communication afterwards.

Advantages of Packet Switching:


 Efficient use of bandwidth: Packet switching is efficient because bandwidth
is shared among multiple users, and resources are allocated only when
data needs to be transmitted.
 Flexible: Packet switching is flexible and can handle a wide range of data
rates and packet sizes.
 Scalable: Packet switching is highly scalable and can handle large
amounts of traffic on a network.
 Lower cost: Packet switching is less expensive than circuit switching
because resources are shared among multiple users.

Disadvantages of Packet Switching:


 Higher latency: Packet switching has higher latency than circuit switching
because packets must be routed through multiple nodes, which can cause
delay.
 Limited QoS: Packet switching provides limited QoS guarantees, meaning
that different types of traffic may be treated equally.
 Packet loss: Packet switching can result in packet loss due to congestion
on the network or errors in transmission.
 Unsuitable for real-time communication: Packet switching is not suitable
for real-time communication, such as voice and video, because of the
potential for latency and packet loss

TRANSMISSION MEDIA

Definition and Importance:

 Transmission medium: Physical pathway that enables signals or data


transfer between a source (transmitter) and a destination (receiver).
 Vital for establishing communication networks, facilitating the exchange
of information across various devices.

NITIN PALIWAL
Page 5

Guided vs Unguided Transmission:

Guided Transmission:

 Description: Involves physical links, typically wires or cables,


connecting transmitting and receiving devices.
 Examples: Metallic cables (e.g., twisted pair, coaxial cable),
fiber-optic cables.
 Characteristics: Provides a stable and controlled path for data
transmission, offering reliability and security.

Unguided Transmission:

 Description: Transmission through free space, utilizing


electromagnetic waves.
 Examples: Radio waves, microwaves, infrared waves, and light
waves.
 Characteristics: Offers mobility and flexibility but may be
susceptible to interference and attenuation.

Wired Transmission Media:

 Twisted Pair Cable:


 Structure: Consists of two copper wires twisted together and
insulated with plastic covers.
 Types: Unshielded twisted-pair (UTP) and Shielded twisted-pair
(STP).
 Applications: Commonly used in telephone lines, LANs due to
cost-effectiveness and ease of installation.

NITIN PALIWAL
Page 6

 Coaxial Cable:
 Structure: Features a copper core surrounded by insulating
material and an outer conductor (usually copper mesh).
 Characteristics: Offers better shielding and higher bandwidth
compared to twisted pair cables.
 Applications: Suitable for transmitting signals of higher
frequencies over longer distances.

 Optical Fiber:
 Structure: Utilizes thin glass fibers to carry data as light signals.
 Advantages: Lightweight, immune to electromagnetic
interference, capable of high-speed data transmission over long
distances.
 Applications: Widely used in backbone networks for high-
performance data transmission.

Wireless Transmission Media:


 Description: Involves transmission of data through electromagnetic
signals propagated through the air.
 Frequency Range: Spans from 3 KHz to 900 THz, encompassing
various types of electromagnetic waves.
 Types of Waves: Includes radio waves, microwaves, infrared waves,
and light waves, each with specific characteristics and applications.

NITIN PALIWAL
Page 7

Wireless Technologies:
 Bluetooth:
 Description: Short-range wireless technology operating at the
2.4 GHz frequency band.
 Applications: Enables wireless connections between devices
within close proximity, forming personal area networks
(piconets).

Wireless LAN (Wi-Fi):


 Description: Utilizes IEEE standard 802.11 to create wireless
local area networks.
 Features: Access points (APs) are deployed to provide wireless
connectivity, offering flexibility and increased access for mobile
devices.

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

DATA STRUCTURE

A data structure defines a mechanism to store, organise and access data along with
operations (processing) that can be efficiently performed on the data.

STACK

Introduction to Stack
 Analogous to piles of books or plates at home.
 New items are added to and removed from the top of the pile.
 Conventional to add/remove objects only from the top due to
convenience.
 This linear order of arrangement is termed as a stack.

Last-In-First-Out (LIFO) Principle


 Follows the principle of LIFO.
 The most recently inserted element will be the first one to be removed.
 In a stack, the element inserted last is at the top and is the first one to
be taken out.

APPLICATIONS OF STACK

Real-Life Applications
 Piles of clothes in an almirah.
 Vertical stacks of chairs.
 Bangles worn on the wrist.
 Piles of boxes of eatables in a pantry or kitchen shelf.

Programming Applications
 String Reversal: Easily achieved by placing characters of a
string in a stack and retrieving them in reverse order.
 Text/Image Editing: Stack keeps track of changes made,
enabling redo/undo functionalities in text/image editors.
 Web Browsing: Back button functionality in browsers is
implemented using a stack to maintain the history of visited web
pages.
 Arithmetic Expressions: Used to handle matching of
parentheses in arithmetic expressions, ensuring proper nesting
and throwing errors for mismatched parentheses.

NITIN PALIWAL
Page 3

OPERATIONS ON STACK

Stack Fundamentals
 Stack implements Last-In-First-Out (LIFO) arrangement.
 Elements are added to and deleted from one end, termed as the TOP
of the stack.

Key Operations
 PUSH: Adds a new element at the top of the stack.
 Insertion operation.
 Continues until the stack is full, resulting in an 'overflow'
exception if attempted beyond capacity.
 POP: Removes the topmost element of the stack.
 Deletion operation.
 Continues until the stack is empty, resulting in an 'underflow'
exception if attempted on an empty stack.

IMPLEMENTATION OF STACK

Creating an Empty Stack:

NITIN PALIWAL
Page 4

To check whether the stack is empty or not:

To insert a new element in the stack:

To find the number of elements

NITIN PALIWAL
Page 5

To read the most recent element:

To remove the topmost element from stack:

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

DATABASE CONCEPTS:

File System: Basics and Structure

 Definition of a File:
 Container for storing data on a computer system.
 Contents can vary from text to multimedia files.

 Storage and Access:


 Files stored on a computer's storage device.
 Accessible and searchable for desired data, albeit requiring software
intervention.

 Example Continuation:
 Separate storage of student and attendance data in two files.
 Description of columns in both STUDENT and ATTENDANCE files.

Limitations of File System: Challenges and Drawbacks

 Difficulty in Access:
 Files require application programs for data retrieval.
 Challenges arise due to unforeseen data access requirements.

 Data Redundancy:
 Duplicated data in different files leads to redundancy.
 Example: Repeated student names and guardian details.

 Data Inconsistency:
 Mismatch of data in different files due to lack of synchronization.
 Changes in one file may not reflect in another, causing inconsistencies.

 Data Isolation:
 Lack of linkage between related files necessitates separate programs
for access.
 Complex systems with disparate file formats pose challenges in data
retrieval.

 Data Dependence:
 Changes in file structure require modifications in all accessing
programs.
 Failure to update programs leads to operational issues.

 Controlled Data Sharing:


 Challenges in enforcing access control for different user categories.
 Need for limited access to certain files based on user roles.

NITIN PALIWAL
Page 3

DATABASE MANAGEMENT SYSTEM:

Features of DBMS:

 Overcoming File System Limitations:


 Storing data in a database offers solutions to file system limitations.
 Databases organize related data efficiently and logically.

 Definition and Function of DBMS:


 Software for creating, managing, and retrieving databases.
 Examples include MySQL, Oracle, PostgreSQL, SQL Server, and
MongoDB.

 Abstract View and Interface:


 DBMS hides the technical storage details, providing users an abstract
view.
 Offers programs for users or applications to access, modify, and
retrieve data.

 Querying and Data Modification:


 Retrieving data through specific commands termed as querying.
 Users can modify database structure via DBMS.

 Applications of Databases:
 Banking: Customer information, account details, transactions, etc.
 Crop Loan: Farmer data, land details, loan history, etc.
 Inventory Management, Organizational Resource Management, Online
Shopping.

Key Concepts in DBMS:

 Database Schema: Design representing table structures, data types,


constraints, and relationships.

 Data Constraint: Imposing restrictions on data insertion to ensure accuracy


and reliability.

 Meta-data or Data Dictionary: Storage of schema and constraints by DBMS,


known as meta-data.

 Database Instance: Snapshot of the database at a given time with loaded


data.

 Query and Data Manipulation:


 Requests for data retrieval or modification using query language.
 Operations include Insertion, Deletion, and Update.

 Database Engine: Underlying component handling database creation,


querying, and manipulation.

NITIN PALIWAL
Page 4

RELATIONAL DATABASE MODEL:

Types of DBMS:
 Classification based on underlying data models.
 Data model defines database structure, relationships, and constraints.
 Most commonly used: Relational Data Model.

Relational Model Overview:


 Tables termed as relations store data in columns.
 Each table consists of multiple columns with unique names.
 Rows represent related sets of values, forming relationships.
 Relations are interlinked, ensuring data integrity and validity.

Example of Relation Schemas:


 Description of attributes for STUDENT, ATTENDANCE, and
GUARDIAN tables.
 Attributes include unique identifiers, names, contact details, and dates.

Key Concepts in Relational Data Model:


 Attribute: Columns representing characteristics or parameters for data
storage.
 Tuple: Rows of data in a relation, each representing a related set of
values.
 Domain: Set of values an attribute can take, defined by data type.
 Degree: Number of attributes in a relation.
 Cardinality: Number of tuples in a relation.

Important Properties of a Relation:


 Property 1: Unique attribute names, sequence immaterial.
 Property 2: Distinct tuples, unordered sequence.
 Property 3: Consistency in attribute data type and atomicity.
 Use of "NULL" for unknown or non-applicable attribute values.

Illustration of Relation GUARDIAN:


 Example relation showcasing attributes and tuples.
 Understanding degree, cardinality, and properties of a relation.

Limitations of DBMS:
 Increased complexity in maintenance and operational functionalities.
 Vulnerability to data loss due to hardware or software failures.

NITIN PALIWAL
Page 5

KEYS IN RELATIONAL DATABASE:

Distinct Tuples Requirement:


 Tuples within a relation must be distinct, ensuring uniqueness.
 Imposes constraints on attribute values and cross-referencing between
relations.

Types of Keys:

Candidate Key:
 Attributes with distinct values capable of uniquely identifying tuples.
 Candidates for becoming the primary key.
 Example: GUID and GPhone in the GUARDIAN relation.
Primary Key:
 Chosen attribute, among candidate keys, to uniquely identify tuples.
 Remaining candidate keys termed as alternate keys.
 Example: GUID chosen as the primary key in the GUARDIAN relation.
Composite Primary Key:
 Multiple attributes together form the primary key when no single
attribute is sufficient.
 Called composite primary key.
 Example: {RollNumber, AttendanceDate} in the ATTENDANCE
relation.
Foreign Key:
 Represents relationships between two relations.
 Derived from the primary key of another relation.
 Attribute in referencing relation becomes a foreign key.
 Allows referencing contents from another relation.
 Can take NULL if not part of the primary key of the foreign table.
 Example shown in the schema diagram of the Student Attendance
database.

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

CLASS 11 AND 12 COMPUTER SCIENCE

FUNCTIONS
WHAT ARE FUNCTIONS?

A function is a reusable block of code that performs a specific task or set of tasks.
Functions provide a way to organize code into modular and manageable pieces.
They take input, process it, and produce output. Functions are crucial for promoting
code reusability, readability, and maintainability.

TYPES OF FUNCTIONS:

Built-in Functions:
 Definition: Functions that are predefined in Python and come built into the
interpreter.
 Examples:
 len(): Returns the length of an object (e.g., a string, list, or tuple).
 print(): Outputs text or variables to the console.
 type(): Returns the type of an object.

Functions Defined in Modules:


 Definition: Functions that are part of external modules or libraries, extending
Python's functionality.
 Examples:
 math.sqrt(): Returns the square root of a number (from the math
module).
 random.randint(): Generates a random integer (from the random
module).

User-Defined Functions:
 Definition: Functions created by the user to perform specific tasks or
operations.
 Example:

NITIN PALIWAL
Page 3

FUNCTION BASICS

Arguments and Parameters:


 Parameters: Variables listed in the function definition.
 Arguments: Values passed to the function during a function call.
 Parameters act as placeholders for arguments.

PARAMETER

ARGUMENT

Default Parameters:
 Definition: Assign default values to parameters in the function definition.
 If an argument is not provided during the function call, the default value is
used.

DEFAULT PARAMETER

Positional Parameters:
 Definition: Parameters defined by their position in the function call.
 The order and number of arguments matter.

NITIN PALIWAL
Page 4

PROGRAM TO CALCULATE THE PAYABLE

AMOUNT FOR THE TENT WITHOUT USING

FUNCTIONS K2 (KYA, KAISE)


# Program to calculate the payable amount for the tent without 1. User Inputs:
functions - The program prompts the
user to enter values for the
cylindrical part of the tent:
# Prompting the user to enter values for the cylindrical part of the tent
height, radius, and slant height
print("Enter values for the cylindrical part of the tent in meters\n") of the conical part.
h = float(input("Enter height of the cylindrical part: "))
2. Area Calculation:
r = float(input("Enter radius: "))
- The program calculates the
l = float(input("Enter the slant height of the conical part in meters: ")) area of the conical part and
cylindrical part separately using
mathematical formulas.
# Calculating the area of the conical part
csa_conical = 3.14 * r * l 3. Total Canvas Area:
- The total canvas area used
# Calculating the area of the cylindrical part for making the tent is calculated
by adding the areas of the
csa_cylindrical = 2 * 3.14 * r * h conical and cylindrical parts.

# Calculate total canvas area used for making the tent 4. Cost Calculation:
- The program prompts the
canvas_area = csa_conical + csa_cylindrical
user to enter the cost of 1 m² of
print("The area of the canvas is", canvas_area, "m^2") canvas.
- It calculates the total cost of
canvas by multiplying the total
# Prompting the user to enter the cost of 1 m^2 canvas
canvas area by the unit price.
unit_price = float(input("Enter the cost of 1 m^2 canvas: "))
5. Tax Calculation and Net
Amount Payable:
# Calculate total cost of canvas
- Tax is calculated as 18% of
total_cost = unit_price * canvas_area the total cost.
print("The total cost of canvas = ", total_cost) - The net amount payable by
the customer, including tax, is
calculated by adding the tax to
# Adding tax to the total cost to calculate net amount payable by the
the total cost.
customer
tax = 0.18 * total_cost 6. Output:
- The program displays the
net_price = total_cost + tax
area of the canvas, total cost of
print("Net amount payable = ", net_price) canvas, and the net amount
payable by the customer.

NITIN PALIWAL
Page 5

PROGRAM TO CALCULATE THE PAYABLE

AMOUNT FOR THE TENT USING FUNCTIONS


K2 (KYA, KAISE)
# Program to calculate the cost of a tent
# Function definition for calculating the area of the cylindrical part
def cyl(h, r): 1. Function Definitions:
- Three functions are defined:
area_cyl = 2 * 3.14 * r * h # Area of cylindrical part
`cyl(h, r)`, `con(l, r)`, and
return area_cyl `post_tax_price(cost)`.
- They compute the area of
# Function definition for calculating the area of the conical part the cylindrical part, conical part,
and net payable amount
def con(l, r): including tax, respectively.
area_con = 3.14 * r * l # Area of conical part
return area_con 2. User Inputs:
- Height, radius, and slant
height of the tent are entered by
# Function definition for computing payable amount for the tent the user.
def post_tax_price(cost):
tax = 0.18 * cost
3. Function Calls:
net_price = cost + tax
return net_price - `cyl()` and `con()` are called
to calculate respective areas.

print("Enter values of cylindrical part of the tent in meters:")


h = float(input("Height: ")) 4. Canvas Area and Cost
r = float(input("Radius: ")) Calculation:

csa_cyl = cyl(h, r) # Function call to calculate cylindrical area - Total canvas area and cost
l = float(input("Enter slant height of the conical area in meters: ")) are calculated based on user
inputs.
csa_con = con(l, r) # Function call to calculate conical area

# Calculate area of the canvas used for making the tent 5. Tax Calculation and Net
canvas_area = csa_cyl + csa_con Amount Payable:

print("Area of canvas = ", canvas_area, " m^2") - Tax is computed as 18% of


the total cost and added to get
the net payable amount.
# Calculate cost of canvas
unit_price = float(input("Enter cost of 1 m^2 canvas in rupees: "))
6. Output:
total_cost = unit_price * canvas_area
- The program displays the
print("Total cost of canvas before tax = ", total_cost) area of the canvas, total cost
before tax, and net amount
payable including tax.
# Calculate and print net amount payable (including tax)
print("Net amount payable (including tax) = ",
post_tax_price(total_cost))

NITIN PALIWAL
Page 6

WRITING A USER DEFINED FUNCTION TO ADD 2 NUMBERS AND

DISPLAY THEIR SUM


1. User Input:
 Accepts two numbers from the user.
# Function to add two numbers 2. Sum Calculation:
# The requirements are listed below:  Calculates the sum of the two numbers.
3. Output:
# 1. Accept 2 numbers from the user.
 Displays the sum of the numbers.
# 2. Calculate their sum.
# 3. Display the sum. Concise Explanation:

 The function addnum() prompts the user to input two


# Function definition numbers, calculates their sum, and then displays the
result. It accomplishes these tasks in a single function call.
def addnum():
fnum = int(input("Enter first number: ")) # Accept first number from the user
snum = int(input("Enter second number: ")) # Accept second number from the user
sum = fnum + snum # Calculate the sum
print("The sum of ", fnum, "and ", snum, "is ", sum) # Display the sum

# Function call
addnum() # Call the function to execute

WRITE A PROGRAM USING A USER DEFINED FUNCTION THAT

DISPLAYS SUM OF FIRST N NATURAL NUMBERS, WHERE N IS

PASSED AS AN ARGUMENT.

# Program to find the sum of first n natural numbers


# The requirements are: K2 (KYA, KAISE)
# 1. n be passed as an argument
Parameter Passing:
# 2. Calculate sum of first n natural numbers The function accepts n as a parameter.

# 3. Display the sum Sum Calculation:


It calculates the sum of the first n natural numbers using
a loop.
# Function definition Output:
The function displays the sum of the first n natural
def sumSquares(n): # n is the parameter numbers.
Concise Explanation:
sum = 0 The sumSquares() function takes an integer n as input
and calculates the sum of the first n natural numbers
for i in range(1, n+1): using a loop. The function then prints the sum. Finally,
the program prompts the user to input a value for n and
calls the sumSquares() function with the user-provided
value.
NITIN PALIWAL
Page 7

sum = sum + i
print("The sum of first", n, "natural numbers is:", sum)

# Getting user input for n


num = int(input("Enter the value for n: "))

# Function call
sumSquares(num)

NITIN PALIWAL
Page 8

NITIN PALIWAL
Page 9

NITIN PALIWAL
Page 1

NITIN PALIWAL
Page 2

STRUCTURED QUERY LANGUAGE

 Purpose: SQL is used to access and manipulate data stored in databases,


unlike file systems where application programs are required for data access.

 Popular Usage: SQL is widely used in major relational database


management systems such as MySQL, Oracle, and SQL Server.

 Ease of Learning: SQL is easy to learn as its statements use descriptive


English words and are not case-sensitive.

 Database Interaction: SQL allows easy creation and interaction with


databases. Users don't need to specify how to retrieve data; they only specify
what data they need, and SQL handles the retrieval process.

 Versatility: Despite being called a query language, SQL can perform various
tasks beyond querying. It provides statements for defining data structure, data
manipulation, declaring constraints, and retrieving data in different ways
based on requirements..

DATA TYPES IN MYSQL

 Definition: Data type indicates the type of data value an attribute can have
and determines the operations that can be performed on it.
 Examples: MySQL supports numeric types, date and time types, and string
types.
 Commonly Used Data Types:
 CHAR(n): Fixed-length character type data with length n (0 to 255).
Padded with spaces if needed.
 VARCHAR(n): Variable-length character type data with maximum length
n (0 to 65535). Adjusts storage based on actual string length.
 INT: Integer value occupying 4 bytes, supporting unsigned values up to
4,294,967,295. For larger values, use BIGINT (8 bytes).
 FLOAT: Decimal numbers, each value occupying 4 bytes.
 DATE: Date type in 'YYYY-MM-DD' format, supporting a range from
'1000-01-01' to '9999-12-31'..

CONSTRAINTS

 Definition: Constraints are restrictions on data values an attribute can have,


ensuring data correctness.
 Examples:
 NOT NULL: Disallows NULL values in a column.
 UNIQUE: Ensures all values in a column are distinct.
 DEFAULT: Specifies a default value if none is provided.
 PRIMARY KEY: Identifies each row uniquely in a table.
 FOREIGN KEY: Refers to the primary key of another table.

NITIN PALIWAL
Page 3

SQL FOR DATA DEFINITION

CREATE Database
 Definition: To store data, we need to create a database and its tables
(relations) using the CREATE DATABASE statement.
Syntax: CREATE DATABASE databasename;
Example: CREATE DATABASE StudentAttendance;
Activity:
 Objective: Check if the database 'StudentAttendance' was created
successfully.
 Command: show databases;
 Observation: The 'StudentAttendance' database should be listed.

CREATE Table:
 Definition: After creating a database, we define relations (tables) within it
using the CREATE TABLE statement.

Describe Table
 Purpose: View the structure of an existing table using the DESCRIBE
statement.
 Syntax: DESCRIBE tablename;

ALTER Table
 Definition: Modify the structure of an existing table using the ALTER
statement.
 Actions: Add/remove attributes, modify datatypes, add constraints, etc.
 Syntax: Various ALTER TABLE statements for different modifications.

A. Adding Columns:
Syntax: ALTER TABLE table_name ADD column_name datatype;
Example: ALTER TABLE Students ADD Email VARCHAR(50);

B. Modifying Columns:
Syntax: ALTER TABLE table_name MODIFY column_name new_datatype;
Example: ALTER TABLE Students MODIFY Email VARCHAR(100);

NITIN PALIWAL
Page 4

C. Renaming Columns:
Syntax: ALTER TABLE table_name RENAME COLUMN old_column TO
new_column;
Example: ALTER TABLE Students RENAME COLUMN Email TO Email_Address;

D. Dropping Columns:
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
Example: ALTER TABLE Students DROP COLUMN Email_Address;

E. Adding Constraints:
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name
constraint_definition;
Example: ALTER TABLE Students ADD CONSTRAINT pk_student_id PRIMARY
KEY (StudentID);

F. Dropping Constraints:
Syntax: ALTER TABLE table_name DROP CONSTRAINT constraint_name;
Example: ALTER TABLE Students DROP CONSTRAINT pk_student_id;

G. Adding Indexes:
Syntax: ALTER TABLE table_name ADD INDEX index_name (column_name);
Example: ALTER TABLE Students ADD INDEX idx_student_name (Name);

H. Dropping Indexes:
Syntax: ALTER TABLE table_name DROP INDEX index_name;
Example: ALTER TABLE Students DROP INDEX idx_student_name;

I. Adding Foreign Keys:


Syntax: ALTER TABLE table_name ADD FOREIGN KEY (column_name)
REFERENCES referenced_table_name (referenced_column_name);
Example: ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES
Customers (CustomerID);

J. Dropping Foreign Keys:


Syntax: ALTER TABLE table_name DROP FOREIGN KEY constraint_name;
Example: ALTER TABLE Orders DROP FOREIGN KEY fk_customer;

DROP Statement:
 Purpose: Permanently remove a table or database from the system.
 Syntax:
o To drop a table: DROP TABLE table_name;
o To drop a database: DROP DATABASE database_name;

NITIN PALIWAL
Page 5

SQL FOR DATA MANIPULATION

Inserting Records
To add new data into a table, we use the INSERT INTO statement. Here's the
syntax:

SQL FOR DATA QUERY

 DELETE Command:
 Syntax: DELETE FROM table_name WHERE condition;
 Example: DELETE FROM EMPLOYEE WHERE Salary < 20000;
 SELECT Statement:
 Syntax: SELECT column1, column2, ... FROM table_name WHERE
condition;
 Example: SELECT EName, Salary FROM EMPLOYEE WHERE DeptId =
'D01';

Operators (Mathematical, Relational, and Logical):


 Mathematical Operators:
 Syntax: +, -, *, /
 Example: SELECT Salary * 12 AS AnnualIncome FROM EMPLOYEE;
 Relational Operators:
 Syntax: =, <>, >, <, >=, <=
 Example: SELECT * FROM EMPLOYEE WHERE Salary > 50000;

NITIN PALIWAL
Page 6

 Logical Operators:
 Syntax: AND, OR, NOT
 Example: SELECT * FROM EMPLOYEE WHERE DeptId = 'D01' AND
Salary > 40000;

 Aliasing:
 Syntax: SELECT column_name AS alias_name FROM table_name;
 Example: SELECT Salary AS MonthlySalary FROM EMPLOYEE;

 DISTINCT Clause:
 Syntax: SELECT DISTINCT column_name FROM table_name;
 Example: SELECT DISTINCT DeptId FROM EMPLOYEE;

 WHERE Clause:
 Syntax: SELECT * FROM table_name WHERE condition;
 Example: SELECT * FROM EMPLOYEE WHERE Salary > 50000;

 IN Operator:
 Syntax: SELECT * FROM table_name WHERE column_name IN
(value1, value2, ...);
 Example: SELECT * FROM EMPLOYEE WHERE DeptId IN ('D01',
'D02', 'D03');

 BETWEEN Operator:
 Syntax: SELECT * FROM table_name WHERE column_name BETWEEN
value1 AND value2;
 Example: SELECT * FROM EMPLOYEE WHERE Salary BETWEEN 30000
AND 60000;

 ORDER BY Clause:
 Syntax: SELECT * FROM table_name ORDER BY column_name [ASC |
DESC];
 Example: SELECT * FROM EMPLOYEE ORDER BY Salary DESC;

 Meaning of NULL:
 Represents missing or unknown values.
 IS NULL Operator:
 Syntax: SELECT * FROM table_name WHERE column_name IS NULL;
 Example: SELECT * FROM EMPLOYEE WHERE Bonus IS NULL;

 IS NOT NULL Operator:


 Syntax: SELECT * FROM table_name WHERE column_name IS NOT
NULL;
 Example: SELECT * FROM EMPLOYEE WHERE Bonus IS NOT NULL;

 LIKE Operator:
 Syntax: SELECT * FROM table_name WHERE column_name LIKE
pattern;
 Example: SELECT * FROM EMPLOYEE WHERE EName LIKE 'A%';

NITIN PALIWAL
Page 7

 UPDATE Command:
 Syntax: UPDATE table_name SET column1 = value1, column2 =
value2, ... WHERE condition;
 Example: UPDATE EMPLOYEE SET Salary = 55000 WHERE EName =
'Kritika';

 Aggregate Functions (MAX, MIN, AVG, SUM, COUNT):


 Syntax: SELECT function_name(column_name) FROM table_name;
 Example: SELECT MAX(Salary) FROM EMPLOYEE;

 GROUP BY Clause:
 Syntax: SELECT column1, function(column2) FROM table_name
GROUP BY column1;
 Example: SELECT DeptId, AVG(Salary) FROM EMPLOYEE GROUP BY
DeptId;

 HAVING Clause:
 Syntax: SELECT column1, function(column2) FROM table_name
GROUP BY column1 HAVING condition;
 Example: SELECT DeptId, AVG(Salary) FROM EMPLOYEE GROUP BY
DeptId HAVING AVG(Salary) > 40000;

 Joins:
 Cartesian Product: No explicit syntax, it's a result of not specifying a
JOIN condition.
 Equi-Join: SELECT * FROM table1 JOIN table2 ON table1.column =
table2.column;
 Natural Join: SELECT * FROM table1 NATURAL JOIN table2;

NITIN PALIWAL
Page 8

NITIN PALIWAL
Page 9

NITIN PALIWAL

You might also like