0% found this document useful (0 votes)
28 views

INDEX F DBMS-1

The document provides an index of SQL statements and concepts that will be covered. These include creating tables, describing tables, inserting data, selecting data, sorting data, updating tables, joining tables, and more. Specific SQL keywords, clauses, and functions are listed such as CREATE TABLE, SELECT, WHERE, ORDER BY, UPDATE, JOIN, and aggregate functions.

Uploaded by

skekhero
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)
28 views

INDEX F DBMS-1

The document provides an index of SQL statements and concepts that will be covered. These include creating tables, describing tables, inserting data, selecting data, sorting data, updating tables, joining tables, and more. Specific SQL keywords, clauses, and functions are listed such as CREATE TABLE, SELECT, WHERE, ORDER BY, UPDATE, JOIN, and aggregate functions.

Uploaded by

skekhero
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/ 25

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

i. To Insert values in selective columns


3.
ii. To insert values of all columns.

Write a SQL Statement to fetch the data from the table.


4.
Write a SQL Statement Sorting the data
5.
Write a SQL Statement to rename the table.
6.
Write a SQL Statement to Delete a particular row
7.
Write a SQL Statement to delete all records from the table.
8.
Write a SQL Statement to drop the table.
9.
Write a SQL statement using Aggregate Functions(MIN, MAX,
10. AVG,SUM,COUNT)

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

iii. Not Null

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

CREATE TABLE Companies (


id INT,
name VARCHAR(50),
address TEXT,
email VARCHAR(50),
phone VARCHAR(10)
);

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

CREATE TABLE USACustomers AS


SELECT * FROM Customers WHERE country = 'USA';

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

CREATE TABLE CustomersBackup AS


SELECT * FROM Customers;

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

CREATE TABLE Companies (


id INT NOT NULL PRIMARY KEY,
name VARCHAR(50),
address TEXT,
email VARCHAR(50),
phone VARCHAR(10)
);

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

CREATE TABLE Companies (


id INT NOT NULL,
name VARCHAR(50) NOT NULL,
address TEXT,
email VARCHAR(50) NOT NULL,
phone VARCHAR(10)
);
1
Here, the “id,” “name,” and “email” columns cannot contain NULL values .

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.?

Certainly! To describe the structure of a table in SQL, you can use


the DESCRIBE or DESC command. These commands provide information about the columns
within the specified table. Let’s illustrate this with an example:

Suppose we have a table named “users” with the following columns:

 id (integer, primary key)


 name (varchar, maximum length 50 characters)
 email (varchar, maximum length 100 characters)
 age (integer)

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
);

-- Describing the structure of the "users" table


DESC users;
.
The output of the DESC command will show details about each column:

 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

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
.

After executing this command, the “Customers” table will look like this:

Table

CustomerID CustomerName ContactName Address

89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45

91 Wolski Zbyszek ul. Filtrowa 68 Walla

92 Cardinal Tom B. Erichsen Skagen 21

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

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');

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

CustomerID CustomerName ContactName

89 White Clover Markets Karl Jablonski

90 Wilman Kala Matti Karttunen

91 Wolski Zbyszek ul. Filtrowa 68

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

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway');
Q-4 Write a SQL Statement to fetch the data from the table.?

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.

 table_name is the name of the table containing the data.

Now, let’s look at some examples:


1. Selecting Specific Columns: Suppose we have a table called Customers with columns
like CustomerID, FirstName, LastName, Email, Address, City, PostalCode, and Country. To select
only the FirstName and LastName columns from this table, you can use the following
SQL statement:

SQL

SELECT FirstName, LastName


FROM Customers;
This query will return a result set containing only the FirstName and LastName columns.
2. Selecting All Columns: To retrieve all columns from the Customers table, use the
wildcard *:

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)?

CREATE TABLE sales (


product_id INT,
product_name VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);

INSERT INTO sales (product_id, product_name, quantity, price) VALUES


(1, 'Product A', 10, 100.00),
(2, 'Product B', 15, 150.00),
(3, 'Product C', 20, 200.00),
(4, 'Product D', 5, 50.00);
Q-11 SQL operators?
Q-12 Write a SQL statement using ALTER command with ADD, MODIFY
and DELETE keyword.

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

ALTER TABLE Students


ADD Email varchar(255);
After running this query, the Students table will have an additional Email column.

Output (Sample Data):

Table

ROLL_NO NAME AGE

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

ALTER TABLE Students


After running this query, the COURSE column will now allow a maximum of 20
characters.
3. Deleting a Column: To remove a column from a table, use the ALTER TABLE ... DROP
COLUMN statement. Let’s drop the COURSE column from the Students table:

SQL

ALTER TABLE Students


DROP COLUMN COURSE;
Output (Sample Data after Dropping COURSE column):

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.

13. Integrity Constraints


i. Primary key
ii. Unique key
iii. Not Null
Q-14 Update?
Database Management System (DBMS), the UPDATE statement is used to modify existing
records in a table. It allows you to change the values of specific columns based on certain
conditions. Let’s explore how the OUTPUT clause can be used with an UPDATE statement
and what it provides:
1. The OUTPUT Clause for UPDATE Statements:

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

-- Sample table creation


CREATE TABLE [dbo].[Department_SRC] (
[DepartmentID] [smallint] IDENTITY(1,1) NOT NULL,
[Name] varchar(50) NOT NULL,
[GroupName] varchar(50) NOT NULL,
[ModifiedDate] [datetime] NOT NULL
);

-- Insert a sample record


INSERT INTO [dbo].[Department_SRC] ([Name], [GroupName],
[ModifiedDate])
VALUES ('Engineering', 'Research and Development', GETDATE());

-- Update the record and capture the results


DECLARE @UpdatedRows TABLE (
[DepartmentID] smallint,
[Name] varchar(50),
[GroupName] varchar(50),
[ModifiedDate] datetime
);

UPDATE [dbo].[Department_SRC]
SET [Name] = 'IT Department'
OUTPUT INSERTED.DepartmentID, INSERTED.Name, INSERTED.GroupName,
INSERTED.ModifiedDate
INTO @UpdatedRows
WHERE [DepartmentID] = 1;

-- Display the updated values


SELECT * FROM @UpdatedRows;

The above query updates the Name column for the department
with DepartmentID = 1 and captures the updated values in
the @UpdatedRows table variable.

2. Viewing Update Values:

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

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (INNER JOIN):

SQL

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student
INNER JOIN StudentCourse ON Student.ROLL_NO =
StudentCourse.ROLL_NO;

Output:

Table

COURSE_ID NAME AGE

… … …

2. Left Join (Left Outer Join):

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

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
LEFT JOIN table2 ON table1.matching_column = table2.matching_column;
.

o Example Query (LEFT JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

Table

NAME COURSE_ID

… …

3. Right Join (Right Outer Join):

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

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
RIGHT JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (RIGHT JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
RIGHT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;

Output:

Table
NAME COURSE_ID

… …

4. Full Join (Full Outer Join):

o Combines results of both LEFT JOIN and RIGHT JOIN.


o Contains all rows from both tables.
o For unmatched rows, the result-set contains NULL values.
o Syntax:

SQL

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
FULL JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (FULL JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
FULL JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

Table

NAME COURSE_ID

… …

📊
Remember that these joins allow you to retrieve data from multiple tables, enhancing the
power of your database queries!

You might also like