Dbms
Dbms
Estd.1998
A
Practicle file of ‘Database Management System’
Subject Code: 505
COURSE: Bachlor’s Of Computer Application (BCA)
Submitted To :- Submitted By :-
Himanshu Sir Abhinay Rana
A Database Management System (DBMS) is a software application that interacts with the
user, applications and the database itself to capture and analyze data. The data stored in the
database can be modified, retrieved and deleted, and can be of any type like strings, numbers,
images etc.
There are mainly 4 types of DBMS, which are Hierarchical, Relational, Network, and
Object-Oriented DBMS.
• Hierarchical DBMS: As the name suggests, this type of DBMS has a style of
predecessor-successor type of relationship. So, it has a structure similar to that of
a tree, wherein the nodes represent records and the branches of the tree represent
fields.
• Relational DBMS (RDBMS): This type of DBMS, uses a structure that allows the
users to identify and access data in relation to another piece of data in the
database.
• Network DBMS: This type of DBMS supports many to many relations wherein
multiple member records can be linked.
• Object-oriented DBMS: This type of DBMS uses small individual software called
objects. Each object contains a piece of data, and the instructions for the actions
to be done with the data.
o MySQL is an open-source database, so you don't have to pay a single penny to use
it.
o MySQL is a very powerful program that can handle a large set of functionality of
the most expensive and powerful database packages.
o MySQL is customizable because it is an open-source database, and the open-
source GPL license facilitates programmers to modify the SQL software according
to their own specific environment.
o MySQL is quicker than other databases, so it can work well even with the large data
set.
o MySQL supports many operating systems with many languages like PHP, PERL, C,
C++, JAVA, etc.
o MySQL uses a standard form of the well-known SQL data language.
o MySQL is very friendly with PHP, the most popular language for web development.
o MySQL supports large databases, up to 50 million rows or more in a table. The
default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).
MySQL SQL
MySQL available only in the English language. SQL is available in different languages.
Application of MySQL :
• MySQL used in E-Commerce websites.
• MySQL used in Data Warehousing.
• MySQL is used in the Login Application.
These SQL commands are mainly categorized into five categories:
These commands are used to update the database schema that's why they come under
Data definition language.
CREATE
The create command is used to create a new database object, such as a table,
view, or index.
Example :- The SQL query that follows creates the "employees" database
with the columns "id," "name," and "salary" −
ALTER
ALTER is used to change a database object's existing structure. You can create,
alter, or delete columns, constraints, or indexes with the ALTER command.
Output Table :-
+ + + + +
| id | name | salary | department |
+ + + + +
DROP
DROP is used to remove a table, view, or other existing database object. The
object and any related data are permanently deleted with the DROP command.
Example :- The "employees" table is deleted with the SQL query that
follows –
Output :-
The "employees" table and all of its data would be permanently wiped following
the execution of the "DROP TABLE employees" command, and there would be
no input or output table to show.
TRUNCATE
Every piece of data from a table that already exists can be removed using
TRUNCATE. The Shorten order, as opposed to the DROP order, basically
eliminates the information from a data set, not the actual table.
+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +
Output Table :-
+----+------+-------+ ------------ +
| id | name | salary| department |
+----+------+-------+ ------------ +
| | | | |
+----+------+-------+ ------------ +
Example :-
Input Table
+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +
The "staff" table is renamed in the following SQL query from the "employees"
table −
RENAME TABLE employees TO staff;
Output Table :-
+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +
The SQL command "RENAME TABLE employees TO staff" just renames the
existing "employees" table to "staff" in the current keyspace, therefore there is
no change to the input and output tables. As a result, the sole distinction is the
name of the table, which has been changed from "employees" to "staff".
3. Data Manipulation Language
(DML) Commands
DML (data manipulation language) is part of SQL, the language used to interact
with relational databases. It is used to add, update, and remove records from a
database and otherwise change the data there. DML enables you to interact with and
modify the data in your database
Data Manipulation Language (DML) is a language by which users access and
manipulate data. Data manipulation refers to retrieval, insertion, deletion and modification
of data or information stored in the database. The basic goal is to attain efficient human
interaction with the system. DML is just like simple English language and is mostly used
as a Structured Query Language (SQL) for information retrieval and manipulation.
c) INSERT – This command is used for adding one or more records to a database.
d) DELETE – This command is used for removing one or more records from a database
according to the specified conditions.
INSERT
The INSERT command is used to add data to a table.
The syntax of the INSERT command is as follows –
INSERT INTO table_name (column1, column2, column3, ...) VALUES
(value1, value2, value3, ...);
Example :- Consider a table having the columns "id," "name," and "email"
named "customers." We can use the following command to add a new record to
the table −
Input Table
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
INSERT INTO customers (id, name, email) VALUES (1, 'John Doe',
'john.doe@example.com');
Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 1 | John Doe| john.doe@example.com|
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
UPDATE
Input Table
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
UPDATE customers SET email = 'johndoe@example.com' WHERE id = 1;
Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 1 | John Doe| johndoe@example.com|
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
DELETE
Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
SELECT
Example :- Consider the scenario where we need to get the names and
email addresses of every consumer who has made a transaction.We can use the
following command to this −
Input Table
+ + + + +
| id | name | email | has_made_purchase |
+ + + + +
|1 | John Doe | john.doe@example.com | true |
|2 | Jane Doe | jane.doe@example.com | false |
|3 | Bob Smith| bob.smith@example.com| true |
|4 | Alice Lee| alice.lee@example.com| true |
+ + + + +
Output Table :-
+ + +
| name | email |
+ + +
| John Doe | john.doe@example.com |
| Bob Smith| bob.smith@example.com|
| Alice Lee| alice.lee@example.com|
+ + +
4. Sub Queries and Joins
Sub Queries –
A Subquery or Inner query or Nested query is a query within SQL
query and embedded within the WHERE clause. A Subquery is a SELECT
statement that is embedded in a clause of another SQL statement. They can be
very useful to select rows from a table with a condition that depends on the data
in the same or another table. A Subquery is used to return data that will be used
in the main query as a condition to further restrict the data to be retrieved. The
subquery can be placed in the following SQL clauses they are WHERE clause,
HAVING clause, FROM clause.
Advantages Of Subquery:
• Subqueries divide the complex query into isolated parts so that a complex
query can be broken down into a series of logical steps.
• It is easy to understand and code maintenance is also at ease.
• Subqueries allow you to use the results of another query in the outer query.
• In some cases, subqueries can replace complex joins and unions.
Disadvantages of Subquery:
• The optimizer is more mature for MYSQL for joins than for subqueries, so in
many cases a statement that uses a subquery can be executed more
efficiently if you rewrite it as join.
• We cannot modify a table and select from the same table within a subquery
in the same SQL statement.
UPDATE table
SET column_name = new_value
[WHERE OPERATOR [VALUE](SELECT COLUMN_NAME FROM TABLE_NAME
[WHERE]);
Joins :-
A join is a query that combines records from two or more tables. A join
will be performed whenever multiple tables appear in the FROM clause of the
query. The select list of the query can select any columns from any of these
tables. If join condition is omitted or invalid then a Cartesian product is formed.
If any two of these tables have a column name in common, then must qualify
these columns throughout the query with table or table alias names to avoid
ambiguity. Most join queries contain at least one join condition, either in the
FROM clause or in the WHERE clause.
Advantages Of Joins:
• The advantage of a join includes that it executes faster.
• The retrieval time of the query using joins almost always will be faster than
that of a subquery.
• By using joins, you can minimize the calculation burden on the database i.e.,
instead of multiple queries using one join query. This means you can make
better use of the database’s abilities to search through, filter, sort, etc.
Disadvantages Of Joins:
• Disadvantage of using joins includes that they are not as easy to read as
subqueries.
• More joins in a query means the database server has to do more work,
which means that it is more time consuming process to retrieve data
• As there are different types of joins, it can be confusing as to which join is
the appropriate type of join to use to yield the correct desired result set.
• Joins cannot be avoided when retrieving data from a normalized database,
but it is important that joins are performed correctly, as incorrect joins can
result in serious performance degradation and inaccurate query results.
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
INNER JOIN :-
The INNER JOIN keyword selects records that have matching values in
both tables.
Syntax :
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
LEFT JOIN :-
The LEFT JOIN keyword returns all records from the left table
(table1), and the matching records from the right table (table2). The
result is 0 records from the right side, if there is no match.
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
RIGHT JOIN :-
The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1). The
result is 0 records from the left side, if there is no match.
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
The FULL OUTER JOIN keyword returns all records when there
is a match in left (table1) or right (table2) table records.
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
5. Views
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of
a table.
1. Join View: A join view is a view that has more than one table or view in its from
clause and it does not use any Group by Clause, Rownum, Distinct and set
operation.
2. Inline View: An inline view is a view which is created by replacing a subquery in
the from clause which defines the data source that can be referenced in the main
query. The sub query must be given an alias for efficient working.
Advantages of View:
1. Complexity: Views help to reduce the complexity. Different views can be created
on the same base table for different users.
2. Security: It increases the security by excluding the sensitive information from the
view.
3. Query Simplicity: It helps to simplify commands from the user. A view can draw
data from several different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure
of the database. Views can be used to rename the columns without affecting the
base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets the specified integrity
constraints.
6. Storage Capacity: Views take very little space to store the data.
7. Logical Data Independence: View can make the application and database tables
to a certain extent independent.
Disadvantages of View:
The DML statements which can be performed on a view created using single base table
have certain restrictions are:
1. You cannot INSERT if the base table has any not null column that do not appear in
view.
2. You cannot INSERT or UPDATE if any of the column referenced in the INSERT or
UPDATE contains group functions or columns defined by expression.
3. You can't execute INSERT, UPDATE, DELETE statements on a view if with read only
option is enabled.
4. You can't be created view on temporary tables.
5. You cannot INSERT, UPDATE, DELETE if the view contains group functions GROUP
BY, DISTINCT or a reference to a pseudo column row num.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
Just like table query, we can query the view to view the data.
Query:
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax:
All the statements of a block are passed to Oracle engine all at once
which increases processing speed and decreases the traffic.
Advantages:
Disadvantages:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments --
CREATE PROCEDURE procedure_name
= ,
= ,
=
AS
BEGIN
-- Query --
END
GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetStudentDetails
@StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, BirthDate, City, Country
FROM Students WHERE StudentID=@StudentID
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments --
ALTER PROCEDURE procedure_name
= ,
= ,
=
AS
BEGIN
-- Query --
END
GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE GetStudentDetails
@StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, City
FROM Students WHERE StudentID=@StudentID
END
GO
Syntax to drop a Procedure:
DROP PROCEDURE procedure_name
Example:
DROP PROCEDURE GetStudentDetails
7. Cursors
In SQL, a cursor is a temporary workstation that is allocated by the database server during
the execution of a statement.
It is a database object that allows us to access data of one row at a time. This concept of
SQL is useful when the user wants to update the rows of the table one by one.
The cursor in SQL is the same as the looping technique of other programming languages.
The collection of tuples held by the cursor is known as the active set.
In SQL database systems, users define the cursor using DECLARE statement and take the
SELECT statement as the parameter, which helps in returning the set of rows.
1. Implicit Cursor
2. Explicit Cursor
Implicit Cursor
These types of cursors are generated and allocated by the SQL server when the system
performs INSERT, DELETE, and UPDATE operations on SQL queries.
An implicit cursor is also created by the system when the SELECT query selects the single
row.
Explicit Cursor
These types of cursors are created by the user using the SELECT query.
An explicit cursor holds multiple records but processes a single row at a time. It uses the
pointer, which moves to another row after reading one row.
It is basically used for gaining extra control over the temporary workstation.
1. Declare a Cursor
2. Open Cursor
3. Fetch Data from Cursor
4. Close Cursor Connection
5. Deallocate cursor
1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:
In this syntax, we have to specify the name and data type of the cursor just after the
DECLARE keyword. After that, we have to write the SELECT statement, which defines the
result set for the cursor.
2. Open Cursor
It is the second stage that opens the cursor for storing the data retrieved from
the result set. We can open the cursor by using the following SQL syntax:
OPEN Cursor_Name;
3. Fetch Cursor
It is the third stage in the cursor life cycle that fetches the rows for performing the
insertion, deletion, and updation operations on the currently active tuple in the cursor.
Following are the six options that are used in syntax for fetching data from the cursor:
i. FIRST: This option allows the system to access only the first record from the
cursor table. The syntax for the FIRST option is given below:
ii. LAST: This option allows the system to access only the last record from the cursor
table. The syntax for the LAST option is as follows:
iii. NEXT: This method allows the system to access the data in the forward direction
from the cursor table. It is the default option. The syntax of this method is as follows:
iv. PRIOR: This method allows the system to access the data in the backward
direction from the cursor table. The syntax of this option is as follows:
v. ABSOLUTE n: This method allows the system to access the data of the exact nth
row from the cursor table. The syntax of this option is mentioned below:
vi. RELATIVE n: This method allows the system to access the data in both incremental
and decremental processes. The syntax of this option is mentioned below:
FETCH RELATIVE n FROM Cursor_Name;
4. Close Cursor
It is the fourth stage in the process of the cursor. When we complete the work
with the cursor, we have to close the cursor in this stage. We can close the cursor in SQL
by using the following query:
CLOSE Cursor_Name;
5. Deallocate Cursor
It is the last and fifth stage of the cursor life cycle. In this part, we have to erase
the definition of the cursor and discharge all the system resources combined with the
cursor.
8. Triggers
A Trigger in Structured Query Language is a set of procedural statements which are
executed automatically when there is any response to certain events on the particular
table in the database. Triggers are used to protect the data integrity in the database.
In SQL, this concept is the same as the trigger in real life. For example, when we pull the
gun trigger, the bullet is fired.
This trigger is invoked in SQL after the modification of the data in the table.
This trigger is invoked after deleting the data from the table.
This trigger is invoked before the inserting the record in the table.
This trigger is invoked before the updating the record in the table.
This trigger is invoked before deleting the record from the table.
1. SQL provides an alternate way for maintaining the data and referential integrity in
the tables.
2. Triggers helps in executing the scheduled tasks because they are called
automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.
o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new
tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the deletion
of data results in the unintended loss of some other important data.
o Updatation Anomaly: The update anomaly is when an update of a single data
value requires multiple rows of data to be updated.
2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are fully
4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has no
multi-valued dependency.
5NF A relation is in 5NF. If it is in 4NF and does not contain any join dependency,
Disadvantages of Normalization
o You cannot start building the database before knowing what the user needs.
o The performance degrades when normalizing the relations to higher normal forms,
i.e., 4NF, 5NF.
o It is very time-consuming and difficult to normalize relations of a higher degree.
o Careless decomposition may lead to a bad database design, leading to serious
problems.
10. Checking Normalizations
Data normalization formula is the method of scaling values to bring them to a
common range. It is used to process any data set so that they become comparable to
other data set and can be used by anyone who wants to understand and interpret it.
It is mainly used by professionals working with a huge data volume. The formula
changes the data set, so their variation falls between 0 and 1. Thus, in
the data normalization formula, the highest data point will have a value of one as the
normalized value and the lowest data point will have zero as the normalized value. The
decimal values of other data points will be between zero and one.
The process is also called feature selling and is mainly used in sets in which the two ends
of the two extreme limits are known, and the data is more or less evenly distributed. It is
frequently used by data analysts in modelling or forecasting.
1. Firstly, identify the minimum and maximum values in the data set,
denoted by x(minimum) and x(maximum).
2. Next, calculate the range of the data set by deducting the minimum
value from the maximum value.
Range = x(maximum) – x(minimum)
Limitations
• Outlier sensitive – Outliers are data points that differ significantly from the other values.
The formula is outlier sensitive, which can reduce its effectiveness.
• May not suit all data sets – The method may not suit all types of data, like the ones that
are categorical or non-linear in nature.
• Bias – The method can bring in the problem of biasness during the choice of range. If
the range is too wide or too narrow, then the result may be incorrect.
• Interpretation and communication are difficult – Sometime, the performance of the
result of the standard normalization formula may not be straightforward, and it is
further difficult to communicate it to the stakeholders.
INDEX
S_no. TITLE Page no.
Write a SQL Statement to Create a table
1.
Write a SQL Statement for Describing the table.
2.
Write a SQL command for Inserting the values into table
SQL operators
11.
Write a SQL statement using ALTER command with ADD,
12. MODIFYand DELETE keyword.
Integrity Constraints
i. Primary key
13. ii. Unique key
Update
14.
Joins
15.
Q-1 Write a SQL Statement to Create a table?
1. Basic CREATE TABLE: To create a table named “Companies” with different columns
(id, name, address, email, and phone), you can use the following SQL statement:
SQL
This creates an empty table called “Companies” with the specified columns and
1
their data types .
2. CREATE TABLE … AS SELECT: You can create a new table by extracting specific
rows from an existing table based on certain criteria. For example, to create a new
table named “USACustomers” containing data from an existing table “Customers”
where the country is ‘USA’, you can use:
SQL
This will create a new table “USACustomers” with the same structure as the
2
“Customers” table and populate it with relevant data .
3. CREATE TABLE Using Another Existing Table: To duplicate an existing table’s
structure and create a new table, you can use the following:
SQL
This creates a new table “CustomersBackup” with the same columns as the
2
“Customers” table and copies all the data into it .
4. Create a Table with a Primary Key: To create a table with a primary key, you can
specify the primary key column(s) within the CREATE TABLE statement. For
example:
SQL
1
This ensures that the “id” column acts as the primary key for the “Companies” table .
5. Define Constraints While Creating a Table: You can add different types of
constraints while creating a table. For instance, the following statement adds the
NOT NULL constraint to some columns:
SQL
Remember to adjust the column names, data types, and constraints according to your
specific requirements when creating tables in SQL!
Q-2 Write a SQL Statement for Describing the table.?
Here’s how you can create the “users” table and then describe its structure:
SQL
-- Creating the "users" table
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100),
age INT
);
Column names
Data types
Nullability (whether a column can contain null values)
For instance, if we execute the DESC users; command, we might see something like this:
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(50) | YES | | NULL | |
| email | varchar(100) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
In this example, the “id” column is the primary key (denoted by PRI), and the other columns
can contain null values (denoted by YES). The data types are also specified.
Remember to execute the DESC command within your database system software, as it
won’t run in a regular text editor.
Q-3 Write a SQL command for Inserting the values into table?
Certainly! To insert new records into a table using SQL, you can use the INSERT
INTO statement. Here are some examples:
1. Inserting Specific Values into All Columns: Suppose we have a table named
“Customers” with
columns: CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country.
We want to add a new customer named “Cardinal” with contact name “Tom B.
Erichsen,” address “Skagen 21,” city “Stavanger,” postal code “4006,” and country
“Norway.” The SQL statement would be:
SQL
After executing this command, the “Customers” table will look like this:
Table
2. Inserting Data Only in Specific Columns: If we want to insert data only in specific
columns (e.g., “CustomerName,” “City,” and “Country”), we can omit the other
columns. For example:
SQL
The “CustomerID” will still be automatically generated, and the other columns will
1
be set to default values (usually NULL) .
After executing this command, the “Customers” table will look like this:
Table
92 Cardinal null
3. Inserting Multiple Rows in One Statement: You can insert multiple rows at once
using a single INSERT INTO statement. For example:
SQL
how to retrieve data from a database table using an SQL SELECT statement.
The SELECT statement allows you to fetch specific information from one or more tables.
Here’s the basic syntax:
SQL
SELECT column1, column2, ...
FROM table_name;column1, column2, and so on represent the names of the columns you want
to retrieve data from.
SQL
SQL
SELECT *
FROM Customers;
This query will return a result set containing all columns from the Customers table.
3. Filtering Data Using the WHERE Clause: Suppose we want to retrieve only those
customers who are located in London. We can add a WHERE clause to filter the data:
SQL
SELECT *
FROM Customers
WHERE City = 'London';
This query will return a result set containing all columns from the Customers table
where the value in the City column is equal to ‘London’.
Q-5 Write a SQL Statement Sorting the data?
you can use the ORDER BY clause. This clause allows you to arrange the result set in
either ascending or descending order based on one or more columns. Here’s how you can
use it:
1. Ascending Order (ASC): To sort data in ascending order, specify the column(s) you
want to sort by and use the ASC keyword. For example, if you have a table
called Orders and you want to retrieve all orders sorted by the OrderDate in ascending
order:
SQL
SELECT *
FROM Orders
ORDER BY OrderDate ASC;
This query will return the orders sorted from the earliest to the latest OrderDate.
2. Descending Order (DESC): To sort data in descending order, use the DESC keyword.
For instance, if you want to retrieve all orders sorted by the TotalAmount in
descending order:
SQL
SELECT *
FROM Orders
ORDER BY TotalAmount DESC;
This query will return the orders sorted from the highest TotalAmount to the lowest.
Q-6 Write a SQL Statement to rename the table.?
To rename a table in SQL, you use the ALTER TABLE statement followed by the RENAME TO clause.
Here's the basic syntax:
Let's say you have a table named students and you want to rename it to class_members. You can
use the following SQL statement:
Q-7 Write a SQL Statement to Delete a particular row?
To delete a particular row from a table in SQL, you use the DELETE FROM statement along with a
WHERE clause to specify the condition that identifies the row(s) you want to delete. Here's the
basic syntax:
Q-8 Write a SQL Statement to delete all records from the table.?
Q-9Write a SQL Statement to drop the table.?
Q-10 Write a SQL statement using Aggregate Functions(MIN, MAX, AVG,
SUM,COUNT)?
the ALTER TABLE statement in SQL to add, modify, and delete columns in an existing table. I’ll
provide examples for each operation along with the expected output.
1. Adding a Column: To add a new column to an existing table, you can use the ALTER
TABLE ... ADD statement. Let’s say we have a table called Students, and we want to add
an Email column of type varchar(255):
SQL
Table
1 Ram 20
2 Abhi 22
3 Rahul 21
4 Tanu 19
2. Modifying a Column: To modify an existing column (e.g., changing its data type),
you can use the ALTER TABLE ... MODIFY statement. Let’s say we want to reduce the
maximum size of the COURSE column from varchar(40) to varchar(20):
SQL
SQL
Table
ROLL_NO NAME
1 Ram
2 Abhi
3 Rahul
4 Tanu
Remember to replace Students, Email, COURSE, and other column names with your actual
table and column names.
o The OUTPUT clause was introduced in SQL Server 2005 and is available in
later versions as well.
o When you use an UPDATE statement with an OUTPUT clause, it returns
information about the rows affected by the update operation.
o The OUTPUT clause provides access to two virtual tables:
INSERTED: Contains the new rows resulting from the update (values
after the update).
DELETED: Contains the old copy of the rows (values before the
update).
o Both these tables are accessible simultaneously during the execution of
the UPDATE statement.
o Common use cases for the OUTPUT clause include auditing, logging, and
confirmation messages.
o You can even insert the results from the OUTPUT clause into a separate table.
o Example: Suppose we have a table called Department_SRC with
columns: DepartmentID, Name, GroupName, and ModifiedDate. Let’s say
we want to update a row in this table and capture the updated values:
SQL
UPDATE [dbo].[Department_SRC]
SET [Name] = 'IT Department'
OUTPUT INSERTED.DepartmentID, INSERTED.Name, INSERTED.GroupName,
INSERTED.ModifiedDate
INTO @UpdatedRows
WHERE [DepartmentID] = 1;
The above query updates the Name column for the department
with DepartmentID = 1 and captures the updated values in
the @UpdatedRows table variable.
o Using the OUTPUT clause, you can display the updated values in the output
window.
o Select the column names with the INSERTED prefix or use INSERTED.* to
display all columns from the INSERTED table.
o Additionally, you can display the old data values (before the update) from
the DELETED table.
o Example:
SQL
UPDATE [dbo].[Department_SRC]
SET [GroupName] = 'IT Group'
OUTPUT INSERTED.DepartmentID, INSERTED.Name, DELETED.GroupName
AS OldGroupName
WHERE [DepartmentID] = 1;
The above query updates the GroupName column and displays both the new
and old values.
Remember, the OUTPUT clause allows you to capture and work with the results of the
updated rows, making it a powerful tool for tracking changes and ensuring data integrity!
Q-15 Joins?
Certainly! In a Database Management System (DBMS), joins are used to combine rows
from two or more tables based on related columns. Let’s explore the different types of
joins and their outputs:
1. Inner Join:
o The INNER JOIN keyword selects all rows from both tables as long as the
condition is satisfied.
o It creates a result-set by combining rows from both tables where the
condition matches (i.e., the value of the common field is the same).
o Syntax:
SQL
SQL
Output:
Table
… … …
o Returns all rows from the left table and matches rows from the right table.
o If there’s no matching row on the right side, the result-set contains null.
o Syntax:
SQL
SQL
Output:
Table
NAME COURSE_ID
… …
o Similar to LEFT JOIN but returns all rows from the right table.
o Matches rows from the left table.
o For unmatched rows on the left side, the result-set contains null.
o Syntax:
SQL
SQL
Output:
Table
NAME COURSE_ID
… …
SQL
SQL
Output:
Table
NAME COURSE_ID
… …
📊
Remember that these joins allow you to retrieve data from multiple tables, enhancing the
power of your database queries!