0% found this document useful (0 votes)
14 views19 pages

Module 3 Part B

Uploaded by

Ayush Sinha
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
0% found this document useful (0 votes)
14 views19 pages

Module 3 Part B

Uploaded by

Ayush Sinha
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/ 19

Unit III Part B:SQL

Characteristics of SQL

SQL, or Structured Query Language, is a powerful tool for managing relational databases with
several key characteristics:

1. Declarative Nature: SQL allows users to specify what data they want without detailing
how to retrieve it, focusing on the desired outcome rather than the process.
2. Standardization: SQL is standardized by the ISO, ensuring consistency in query syntax
and functionality across different relational database systems.
3. Data Manipulation: SQL provides commands for data manipulation (e.g., SELECT,
INSERT, UPDATE, DELETE), which are essential for querying and modifying data.
4. Data Definition: SQL includes commands for defining and modifying database structures
(e.g., CREATE, ALTER, DROP), crucial for schema management.
5. Transaction Management: SQL supports transaction control (e.g., COMMIT,
ROLLBACK), which ensures data integrity and consistency during multi-step operations.

Advantages of SQL

There are the following advantages of SQL:

1. High speed - Using the SQL queries, the user can quickly and efficiently retrieve a large number
of records from a database.
2. No coding needed - In standard SQL, it is very easy to manage the database system. It doesn't
require a substantial amount of code to manage the database system.
3. Well defined standards - Long established are used by the SQL databases that are being used by
ISO and ANSI.
4. Portability - SQL can be used in laptops, PCs, servers and even some mobile phones.
5. Interactive language - SQL is a domain language used to communicate with the database. It is
also used to receive answers to the complex questions in seconds.
6. Multiple data view - Using the SQL language, the users can make different views of the database
structure.
SQL Datatypes:

SQL supports a range of data types for defining the kind of data that can be stored in a database.
These data types help ensure that data is stored and processed in an efficient and accurate manner.
While the specific data types can vary slightly between different SQL database systems, the core
types are fairly consistent. Here’s a rundown of common SQL data types:

Numeric Data Types

1. INT: A standard integer type. In most systems, it can be specified as TINYINT, SMALLINT,
MEDIUMINT, INT, or BIGINT to represent different ranges of integer values.
2. FLOAT: A floating-point number, which can be used for approximate numeric values.
3. DOUBLE: A double-precision floating-point number, offering more precision than FLOAT.
4. DECIMAL: A fixed-point number used for exact numeric values with a specified number
of digits before and after the decimal point (e.g., DECIMAL (10,2)).

Character and String Data Types

1. CHAR(n): A fixed-length character string. If the string is shorter than n, it is padded with
spaces.
2. VARCHAR(n): A variable-length character string with a maximum length of n. It only
uses as much storage as needed for the actual string length.
3. TEXT: A variable-length string used for longer text entries. Variants include TINYTEXT,
TEXT, MEDIUMTEXT, and LONGTEXT for different maximum lengths.
4. CLOB: Character large object, like TEXT, used for storing large amounts of text data.

Date and Time Data Types

1. DATE: Stores date values (year, month, day).


2. TIME: Stores time values (hours, minutes, seconds).
3. DATETIME: Stores date and time values combined.
4. TIMESTAMP: Stores date and time values, typically including time zone information.
Often used to track changes to records.
5. YEAR: Stores a year value (e.g., 2024).

Binary Data Types

1. BINARY(n): Stores fixed-length binary data.


2. VARBINARY(n): Stores variable-length binary data with a maximum length of n.
3. BLOB: Binary large object, used for storing large amounts of binary data. Variants include
TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.

Boolean Data Type


1. BOOLEAN: Stores TRUE or FALSE values. In some systems, this might be represented as
TINYINT (1) or another equivalent.

Other Data Types

1. ENUM: A string object with a value chosen from a list of predefined values. For example,
ENUM ('small', 'medium', 'large').
2. SET: A string object that can have zero or more values from a predefined list. For example,
SET ('A', 'B', 'C').

SQL Server data types

In SQL Server, a column, variable, and parameter hold a value that associated with a type, or also
known as a data type. A data type is an attribute that specifies the type of data that these objects
can store. It can be an integer, character string, monetary, date and time, and so on.

SQL Server provides a list of data types that define all types of data that you can use e.g., defining
a column or declaring a variable.

The following picture illustrates the SQL Server data types system:
String Data Types

Data type Description Max size Storage

char(n) Fixed width character 8,000 characters Defined width


string

varchar(n) Variable width 8,000 characters 2 bytes + number of


character string chars

varchar(max) Variable width 1,073,741,824 2 bytes + number of


character string characters chars

text Variable width 2GB of text data 4 bytes + number of


character string chars

nchar Fixed width Unicode 4,000 characters Defined width x 2


string

nvarchar Variable width Unicode 4,000 characters


string

nvarchar(max) Variable width Unicode 536,870,912


string characters

ntext Variable width Unicode 2GB of text data


string

binary(n) Fixed width binary 8,000 bytes


string

varbinary Variable width binary 8,000 bytes


string

varbinary(max) Variable width binary 2GB


string

image Variable width binary 2GB


string
Numeric Data Types

Data type Description Storage

bit Integer that can be 0, 1, or NULL

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 4 bytes


2,147,483,647

bigint Allows whole numbers between -9,223,372,036,854,775,808 8 bytes


and 9,223,372,036,854,775,807

decimal(p,s) Fixed precision and scale numbers. 5-17 bytes


Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits
that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored
to the right of the decimal point. s must be a value from 0 to p.
Default value is 0

numeric(p,s) Fixed precision and scale numbers. 5-17 bytes


Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits
that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored
to the right of the decimal point. s must be a value from 0 to p.
Default value is 0

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to 8 bytes


922,337,203,685,477.5807

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 4 or 8


308. bytes
The n parameter indicates whether the field should hold 4 or 8
bytes. float(24) holds a 4-byte field and float(53) holds an 8-
byte field. Default value of n is 53.
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date and Time Data Types

Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 8 bytes
3.33 milliseconds

date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5


bytes

timestamp Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an
internal clock and does not correspond to real time. Each table
may have only one timestamp variable

What is an Operator in SQL?

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause
to perform operation(s), such as comparisons and arithmetic operations. These Operators are used
to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in
a statement.
• Arithmetic operators
• Comparison operators
• Logical operators
• Operators used to negate conditions

SQL Arithmetic Operators


Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

+ (Addition) Adds values on either side of the operator. a + b will give 30

Subtracts right hand operand from left hand


- (Subtraction) a - b will give -10
operand.

* (Multiplication) Multiplies values on either side of the operator. a * b will give 200
Divides left hand operand by right hand
/ (Division) b / a will give 2
operand.

Divides left hand operand by right hand operand


% (Modulus) b % a will give 0
and returns remainder.

SQL Comparison Operators

Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or not, if


= (a = b) is not true.
yes then condition becomes true.

Checks if the values of two operands are equal or not, if


!= (a != b) is true.
values are not equal then condition becomes true.

Checks if the values of two operands are equal or not, if


<> (a <> b) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value


> (a > b) is not true.
of right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (a < b) is true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal


>= to the value of right operand, if yes then condition (a >= b) is not true.
becomes true.

Checks if the value of left operand is less than or equal to


<= the value of right operand, if yes then condition becomes (a <= b) is true.
true.

Checks if the value of left operand is not less than the


!< (a !< b) is false.
value of right operand, if yes then condition becomes true.

Checks if the value of left operand is not greater than the


!> (a !> b) is true.
value of right operand, if yes then condition becomes true.
SQL Logical Operators
Here is a list of all the logical operators available in SQL.

Sr. No. Operator & Description

ALL
1
The ALL operator is used to compare a value to all values in another value set.

AND
2 The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.

ANY
3 The ANY operator is used to compare a value to any applicable value in the list as per the
condition.

BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of values, given the
minimum value and the maximum value.

EXISTS
5 The EXISTS operator is used to search for the presence of a row in a specified table that meets
a certain criterion.

IN
6
The IN operator is used to compare a value to a list of literal values that have been specified.

LIKE
7
The LIKE operator is used to compare a value to similar values using wildcard operators.

NOT
8 The NOT operator reverses the meaning of the logical operator with which it is used. E.g.: NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR
9
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

IS NULL
10
The NULL operator is used to compare a value with a NULL value.

UNIQUE
11
The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
Graphical User Interface

GUI is a user-friendly interface used to communicate with the help of electronic devices. It displays
all the contents whether a text file or an object or pictures or videos and all the things that a user
wants to visualize.

Integrating a graphical user interface (GUI) with a database can enhance the functionality and
usability of your software applications. A GUI allows users to interact with your program through
visual elements, such as buttons, menus, and forms. A database stores and manages data in a
structured way, such as tables, records, and fields. In this article, you will learn how to connect a
GUI with a database using some common tools and techniques.

1. Choose a programming language

The first step is to choose a programming language that supports both GUI and database
development. There are many options available, such as Python, Java, C#, and Visual Basic. Each
language has its own advantages and disadvantages, depending on your project requirements,
preferences, and skills. You should also consider the availability and compatibility of libraries,
frameworks, and drivers that can facilitate the integration process.

2. Design a GUI

The next step is to design a GUI that meets the needs and expectations of your users. You can use
various tools and methods to create a GUI, such as drag-and-drop editors, code generators, or
custom coding. You should follow the principles of user interface design, such as clarity,
consistency, feedback, and simplicity. You should also test and refine your GUI to ensure it works
well and looks appealing.

3. Connect to a database

The third step is to connect your GUI to a database that stores the data you want to manipulate.
You can use different types of databases, such as relational, non-relational, or in-memory
databases. You should choose a database that suits your data model, volume, and performance.
You should also use a suitable driver or connector that allows your programming language to
communicate with your database.

4. Execute queries

The fourth step is to execute queries that perform the operations you want on your data. Queries
are statements that specify what data to retrieve, insert, update, or delete from your database. You
can use various query languages, such as SQL, NoSQL, or LINQ. You should write queries that
are clear, efficient, and secure. You should also handle any errors or exceptions that may occur
during the execution.

5. Display results

The fifth step is to display the results of your queries on your GUI. You can use various
components and controls to show the data, such as labels, text boxes, grids, or charts. You should
format and present the data in a way that is easy to read and understand. You should also provide
options and features that allow users to interact with the data, such as sorting, filtering, or
exporting.

6. Update changes

The sixth step is to update the changes that users make on your GUI to your database. You can use
various techniques and mechanisms to synchronize the data, such as triggers, events, or
transactions. You should ensure that the changes are consistent, accurate, and reliable. You should
also prevent or resolve any conflicts or errors that may arise due to concurrency or network issues.

SQL, or Structured Query Language, is a database language that allows you to create a database
and perform various operations. This is done using various types of SQL commands, such as DDL,
DQL, DML, TCL, and DCL. In this article, we will focus only on DCL commands.
DCL Commands
Definition: DCL or Data Control Language commands in SQL allow you to manage access
control by either granting privileges to the users in a database or revoking their privileges.

With the help of DCL commands, you can easily define the level of access and permissions that
users have on the database and its objects, such as tables, views, procedures, etc. In layman’s terms,
Data Control Language commands in SQL allow database administrators to control who has access
to the data in a database and what actions they can perform on that data.

Types of DCL Commands in SQL

There are mainly two types of DCL commands in SQL that help data administrators a lot in
managing access control. These two types of Data Control Language commands are:

• GRANT
• REVOKE

GRANT Command
The GRANT command allows the database administrator to grant specific privileges or
permissions to a user on a database object, such as tables, views, procedures, etc.
In layman’s terms, the GRANT command allows a user to access and perform specific actions on
the database or its objects. You should also remember that the GRANT command is mainly used
by database administrators in order to ensure the security and integrity of the data in the database.

Example:

Consider a database with a table named “employees.” If you want to allow a user named “Vivek”
to only SELECT (read) data from the “employees” table, you can use the following GRANT
command:

GRANT SELECT ON employees TO Vivek;

This command will allow the user “Vivek” to run SELECT queries on the “employees” table. But
Vivek won’t be able to make any changes, such as inserting, updating, or removing the data in the
“employees” table.

REVOKE Command

The REVOKE command allows the database administrator to revoke previously granted privileges
or permissions to a user on a database object, such as tables, views, procedures, etc.

In layman’s terms, the REVOKE command restricts a user from accessing and performing specific
actions on the database or its objects. You should remember that the REVOKE command is also
mainly used by database administrators in order to ensure the security and integrity of the data in
the database.

Example:

Let’s consider the above example that we discussed in the GRANT command. In that, we have
granted access to Vivek to SELECT (read) data from the “employees” table. Now, due to certain
reasons, you want to revoke those permissions. Hence, you can use the following REVOKE
command to remove that privilege:
REVOKE SELECT ON employees FROM Vivek;

This would revoke user “Vivek”’s ability to run SELECT queries on the “employees” table.

Advantages of DCL Commands

There are various advantages to using DCL commands. Let’s explore some of the most common
and popular advantages of DCL commands, such as:

• Security: DCL commands allow database administrators to control who has access to the
data in a database and what actions they can perform on that data. Thus, ensuring the
security and integrity of the data stored in the database.
• Granular control: DCL commands allow administrators to grant and revoke specific
privileges and permissions, Thus giving differing levels of access (granular control) to a
particular user.
• Flexibility: The ability to grant and revoke privileges as per the requirements provides
flexibility to database administrators in order to manage access to the database.

Disadvantages of DCL Commands

Along with the advantages of using DCL commands, there are some drawbacks also. Some of the
most common disadvantages of using data control language commands are:

• Complexity: If there is a large number of users and the database is complex, then granting
and revoking privileges can be complex and time-consuming.
• Risk of human error: Human administrators execute DCL commands and can make
mistakes in granting or revoking privileges. Thus, giving unauthorized access to data or
imposing unintended restrictions on access.
• Lack of audit trail: There may be no built-in mechanism to track changes to privileges
and permissions over time. Thus, it is extremely difficult to determine who has access to
the data and when that access was granted or revoked.
Transaction Control Language (TCL)

Transaction Control Language (TCL) is a critical component of SQL used to manage


transactions and ensure data integrity in relational databases. By using TCL commands, we can
control how changes to the database are committed or reverted, maintaining consistency across
multiple operations.

TCL Commands

TCL includes the following commands:

1. COMMIT

• The COMMIT command is used to save all the transactions to the database that have
been performed during the current transaction.

• Once a transaction is committed, it becomes permanent and cannot be undone.

• This command is typically used at the end of a series of SQL statements to ensure that all
changes made during the transaction are saved.

Syntax: COMMIT;

2. ROLLBACK

• The ROLLBACK command is used to undo all the transactions that have been
performed during the current transaction but have not yet been committed.

• This command is useful for reverting the database to its previous state in case an error
occurs or if the changes made are not desired.

Syntax: ROLLBACK;

3. SAVEPOINT
• The SAVEPOINT command is used to set a point within a transaction to which we can
later roll back.

• This command allows for partial rollbacks within a transaction, providing more control
over which parts of a transaction to undo.

Syntax:

SAVEPOINT savepoint_name;

Uses of TCL Commands

• COMMIT: Used after data modifications (INSERT, UPDATE, DELETE) to save changes
to the database.

• ROLLBACK: Used to revert changes if something goes wrong, ensuring data integrity.

• SAVEPOINT: Used to create intermediate points within a transaction to which you can
roll back, providing finer control over transaction management.

• SET TRANSACTION: Used to configure transaction behavior, ensuring proper isolation


and consistency as per requirements.

Advantages of TCL

1. Data Integrity: Ensures that either all operations within a transaction are completed
successfully or none are, maintaining consistency.

2. Error Recovery: Allows for rolling back incomplete transactions in case of errors,
preventing partial updates.

3. Savepoints: Provides intermediate checkpoints within transactions, offering more granular


control over rollbacks.
4. Transaction Management: Facilitates complex transaction management, ensuring correct
execution sequences and isolation.

Disadvantages of TCL

1. Performance Overhead: Frequent commits and rollbacks can introduce performance


overhead due to additional logging and management operations.

2. Complexity: Managing transactions, especially in large and distributed systems, can


become complex and error-prone.

3. Resource Locking: Long transactions can hold locks on resources, potentially leading to
contention and reduced concurrency.

In a GUI-based application that connects to a SQL Server database, the choice of ADO.NET
objects like SqlConnection, SqlCommand, and SqlDataAdapter can significantly impact the
application's performance and reliability. Let’s explore how these objects influence these aspects
and provide examples to support the analysis.

1. SqlConnection

Role: Manages the connection to the SQL Server database.

Performance and Reliability Impact:

• Connection Pooling: SqlConnection utilizes connection pooling, which can significantly


improve performance by reusing existing connections rather than creating new ones for
each request. Properly managing the connection string and closing connections promptly
helps maximize the benefits of connection pooling.
o Example: If your application frequently opens and closes connections without
reusing them, it may experience delays due to the overhead of creating new
connections. Using SqlConnection effectively with connection pooling can reduce
these delays.
• Connection Lifetime Management: Always close SqlConnection objects as soon as they
are no longer needed. Failing to do so can lead to connection leaks, which may eventually
exhaust the available connections, causing application failures.
o Example: Using a using statement to ensure the connection is closed automatically:
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Perform database operations
}

2. SqlCommand

Role: Executes queries and commands against the SQL Server database.

Performance and Reliability Impact:

• Parameterized Queries: SqlCommand supports parameterized queries, which enhance


performance and prevent SQL injection attacks. Parameterized queries can be cached and
reused, reducing the overhead of query parsing and execution.
o Example: Using parameters with SqlCommand:
SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE
UserId = @UserId", connection);
command.Parameters.AddWithValue("@UserId", userId);

• Efficient Query Execution: Using SqlCommand with appropriate command types (e.g.,
Text, StoredProcedure) can optimize query execution. Stored procedures can offer better
performance compared to inline SQL queries, as they are precompiled and can leverage
database optimization.
o Example: Executing a stored procedure:
SqlCommand command = new SqlCommand("GetUserDetails", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@UserId", userId);

3. SqlDataAdapter
Role: Acts as a bridge between a DataSet or DataTable and the SQL Server database, facilitating
the retrieval and updating of data.

Performance and Reliability Impact:

• Data Retrieval and Updates: SqlDataAdapter provides a convenient way to retrieve data
into a DataSet or DataTable, which can be useful for disconnected data scenarios.
However, it might not be as performant as working directly with SqlCommand for single,
simple queries.
o Example: Retrieving data into a DataSet:

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users",


connection);
DataSet dataSet = new DataSet();

adapter.Fill(dataSet, "Users");

• Concurrency Handling: SqlDataAdapter can handle concurrency by using DataSet with


concurrency checking mechanisms (e.g., timestamps, row versions). This can prevent data
conflicts when multiple users are accessing and modifying the data simultaneously.
o Example: Implementing optimistic concurrency by setting up a RowVersion
column in SQL Server and configuring the SqlDataAdapter to handle concurrency
issues.

Considerations for Performance and Reliability

• Connection Management: Always manage SqlConnection lifecycle carefully to avoid


excessive connection overhead and potential leaks.
• Command Efficiency: Use parameterized queries to enhance security and performance.
Choose stored procedures for complex operations to leverage server-side optimization.
• Data Adapter Use: While SqlDataAdapter is useful for disconnected data scenarios, be
mindful of its overhead in scenarios where direct SqlCommand usage might be more
efficient for simple or high-frequency queries.
Summary: The choice of ADO.NET objects and their proper usage has a direct impact on the
performance and reliability of a GUI-based application. Efficient use of SqlConnection,
SqlCommand, and SqlDataAdapter, along with best practices in connection management, query
optimization, and data handling, ensures that the application performs well and maintains data
integrity.

You might also like