0% found this document useful (0 votes)
25 views16 pages

UNIT2

The document discusses various SQL concepts: 1. It defines different types of integrity constraints like primary key, foreign key, unique, check and not null constraints along with examples. 2. It explains the three basic DML commands - INSERT, UPDATE and DELETE for manipulating data along with syntax and examples. 3. It describes the important DDL commands - CREATE, ALTER, DROP and TRUNCATE for defining and managing database schema along with syntax and examples. 4. It lists some commonly used SQL date functions like CURRENT_DATE(), DATEADD(), DATEDIFF() etc for performing date/time operations.

Uploaded by

skcakcv
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)
25 views16 pages

UNIT2

The document discusses various SQL concepts: 1. It defines different types of integrity constraints like primary key, foreign key, unique, check and not null constraints along with examples. 2. It explains the three basic DML commands - INSERT, UPDATE and DELETE for manipulating data along with syntax and examples. 3. It describes the important DDL commands - CREATE, ALTER, DROP and TRUNCATE for defining and managing database schema along with syntax and examples. 4. It lists some commonly used SQL date functions like CURRENT_DATE(), DATEADD(), DATEDIFF() etc for performing date/time operations.

Uploaded by

skcakcv
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/ 16

UNIT-II

1. Explain the different types of integrity constraints with suitable examples.

A)1)Integrity constraints in a database are rules or conditions that ensure the accuracy, consistency,
and validity of the data stored in tables. They define restrictions and relationships that data must
adhere to. Here are the different types of integrity constraints commonly used in database
management systems:

1. Primary Key Constraint:

A primary key constraint ensures that a column or combination of columns uniquely identifies each
row in a table. It ensures that the primary key values are unique and not null. Examples:

sql

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

Name VARCHAR(50),

Age INT

);

In the above example, the `StudentID` column is defined as the primary key, guaranteeing that each
student has a unique ID.

2. Foreign Key Constraint:

A foreign key constraint establishes a relationship between two tables, ensuring referential integrity.
It enforces that values in a column (foreign key) of one table correspond to the primary key values in
another table (referenced table). Examples:

sql

CREATE TABLE Orders (

OrderID INT PRIMARY KEY,

CustomerID INT,

OrderDate DATE,

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)

);
In this example, the `CustomerID` column in the `Orders` table is a foreign key referencing the
`CustomerID` column in the `Customers` table.

3. Unique Constraint:

A unique constraint ensures that the values in a column or combination of columns are unique
within a table. It allows null values, but if a non-null value exists, it must be unique. Examples:

sql

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

Email VARCHAR(100) UNIQUE,

Name VARCHAR(50)

);

In this example, the `Email` column is defined with a unique constraint, ensuring that each email
address in the table is unique.

4. Check Constraint:

A check constraint specifies a condition that must be satisfied for the values in a column. It allows or
disallows specific values based on the defined condition. Examples:

sql

CREATE TABLE Products (

ProductID INT PRIMARY KEY,

ProductName VARCHAR(50),

Price DECIMAL(10, 2) CHECK (Price > 0)

);

In this example, the `Price` column has a check constraint that ensures the price is greater than zero.

5. Not Null Constraint:

A not null constraint ensures that a column cannot have null values. It requires that the column
always has a value. Examples:
sql

CREATE TABLE Customers (

CustomerID INT PRIMARY KEY,

CustomerName VARCHAR(50) NOT NULL,

City VARCHAR(50)

);

In this example, the `CustomerName` column is defined as not null, ensuring that every customer
has a name.

These integrity constraints play a crucial role in maintaining the consistency and reliability of data in
a database. They enforce data accuracy, prevent data inconsistencies, and improve the overall data
quality.
2. Explain Data Manipulation Language (DML)(insert,update,delete) commands with examples

A) 2)Data Manipulation Language (DML) commands in SQL are used to manipulate data stored in the
database tables. The three primary DML commands are INSERT, UPDATE, and DELETE. Here's an
explanation of each command with examples:

1. INSERT:

The INSERT command is used to insert new rows of data into a table.

Syntax:

sql

INSERT INTO table_name (column1, column2, ...)

VALUES (value1, value2, ...);

Example:

Consider a table named "Students" with columns: StudentID, Name, and Age. To insert a new row
into the table:

sql

INSERT INTO Students (StudentID, Name, Age)

VALUES (1, 'John Doe', 20);

This command inserts a new row with StudentID as 1, Name as 'John Doe', and Age as 20 into the
"Students" table.

2. UPDATE:

The UPDATE command is used to modify existing data in a table.

Syntax:

sql

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;
Example:

Continuing with the "Students" table, suppose we want to update the age of a student with
StudentID 1:

sql

UPDATE Students

SET Age = 21

WHERE StudentID = 1;

This command updates the Age column to 21 for the row where StudentID is 1 in the "Students"
table.

3. DELETE:

The DELETE command is used to delete one or more rows from a table.

Syntax:

sql

DELETE FROM table_name

WHERE condition;

Example:

Let's say we want to delete a student with StudentID 1 from the "Students" table:

sql

DELETE FROM Students

WHERE StudentID = 1;

This command deletes the row where StudentID is 1 from the "Students" table.

These DML commands allow you to manipulate data within the database tables. INSERT is used to
add new data, UPDATE is used to modify existing data, and DELETE is used to remove data from
tables. These commands are fundamental for managing and modifying data in SQL databases.
3. Explain Data Definition Language (DDL) commands (create,alter,drop,truncate) with examples?

3)Data Definition Language (DDL) commands in SQL are used to define and manage the structure
and schema of the database. DDL commands are responsible for creating, altering, and deleting
database objects such as tables, indexes, views, and constraints. Here's an explanation of the
commonly used DDL commands with examples:

1. CREATE:

The CREATE command is used to create a new database object, such as a table, index, or view.

a) CREATE TABLE:

Syntax:

sql

CREATE TABLE table_name (

column1 data_type constraints,

column2 data_type constraints,

...

);

Example:

sql

CREATE TABLE Employees (

EmployeeID INT,

FirstName VARCHAR(50),

LastName VARCHAR(50),

Age INT,

PRIMARY KEY (EmployeeID)

);

In this example, the CREATE TABLE command creates a table named "Employees" with columns
EmployeeID, FirstName, LastName, and Age. The EmployeeID column is defined as the primary key.

b) CREATE INDEX:
Syntax:

sql

CREATE INDEX index_name ON table_name (column1, column2, ...);

Example:

sql

CREATE INDEX idx_last_name ON Employees (LastName);

This command creates an index named "idx_last_name" on the "Employees" table's "LastName"
column.

2. ALTER:

The ALTER command is used to modify the structure of an existing database object, such as a table.
It allows adding, modifying, or dropping columns, constraints, or indexes.

a) ALTER TABLE:

Syntax:

sql

ALTER TABLE table_name

ADD column_name data_type constraints;

Example:

sql

ALTER TABLE Employees

ADD City VARCHAR(50);

This command adds a new column "City" with the VARCHAR data type to the "Employees" table.

b) ALTER TABLE DROP COLUMN:

Syntax:

sql

ALTER TABLE table_name

DROP COLUMN column_name;


Example:

sql

ALTER TABLE Employees

DROP COLUMN Age;

This command removes the "Age" column from the "Employees" table.

3. DROP:

The DROP command is used to remove an existing database object, such as a table, index, or view.

a) DROP TABLE:

Syntax:

sql

DROP TABLE table_name;

Example:

sql

DROP TABLE Employees;

This command deletes the "Employees" table and removes it from the database.

b) DROP INDEX:

Syntax:

sql

DROP INDEX index_name;

Example:

sql

DROP INDEX idx_last_name;

This command deletes the "idx_last_name" index from the database.

4. TRUNCATE:

The TRUNCATE command is used to remove all the data from a table, but keeps the table structure
intact.
Syntax:

sql

TRUNCATE TABLE table_name;

Example:

sql

TRUNCATE TABLE Employees;

This command removes all the data from the "Employees" table, but the table structure remains.

These DDL commands allow you to define, modify, and delete database objects, providing control
over the database schema and structure. CREATE is used to create new objects, ALTER is used to
modify existing objects, DROP is used to delete objects, and TRUNCATE is used to remove all data
from a table. These commands are essential for managing the database's structure and schema.

4. Explain Different SQL Date functions?

4)Certainly! Here are some commonly used SQL date functions:

1. CURRENT_DATE():

- Syntax: `CURRENT_DATE()`

- Description: Returns the current date.

- Example: `SELECT CURRENT_DATE();`

2. CURRENT_TIME():

- Syntax: `CURRENT_TIME()`

- Description: Returns the current time.

- Example: `SELECT CURRENT_TIME();`

3. CURRENT_TIMESTAMP():

- Syntax: `CURRENT_TIMESTAMP()`
- Description: Returns the current date and time.

- Example: `SELECT CURRENT_TIMESTAMP();`

4. EXTRACT():

- Syntax: `EXTRACT(unit FROM date_expression)`

- Description: Extracts a specific part (year, month, day, hour, minute, etc.) from a date or
timestamp.

- Example: `SELECT EXTRACT(YEAR FROM hire_date) FROM employees;`

5. DATEPART():

- Syntax: `DATEPART(datepart, date_expression)`

- Description: Returns a specific part (year, month, day, hour, minute, etc.) from a date or
timestamp.

- Example: `SELECT DATEPART(YEAR, hire_date) FROM employees;`

6. DATEADD():

- Syntax: `DATEADD(datepart, number, date_expression)`

- Description: Adds a specified number of units (year, month, day, hour, minute, etc.) to a date or
timestamp.

- Example: `SELECT DATEADD(MONTH, 3, hire_date) FROM employees;`

7. DATEDIFF():

- Syntax: `DATEDIFF(datepart, start_date, end_date)`

- Description: Calculates the difference between two dates or timestamps in the specified units
(year, month, day, hour, minute, etc.).

- Example: `SELECT DATEDIFF(DAY, hire_date, CURRENT_DATE()) FROM employees;`

8. DATE_FORMAT():

- Syntax: `DATE_FORMAT(date_expression, format_string)`

- Description: Formats a date or timestamp into a specified string format.

- Example: `SELECT DATE_FORMAT(hire_date, '%Y-%m-%d') FROM employees;`These date


functions enable you to perform various operations and calculations with dates and times in SQL
queries, making it easier to work with temporal data.
5. Explain various arithmetic and logical operations in sql?

5a)In SQL, arithmetic and logical operations are used to perform calculations and make logical
comparisons on data. Here's an explanation of the various arithmetic and logical operations in SQL:

Arithmetic Operations:

1. Addition (+): Used to add values together.

Example: `SELECT column1 + column2 FROM table;`

2. Subtraction (-): Used to subtract one value from another.

Example: `SELECT column1 - column2 FROM table;`

3. Multiplication (*): Used to multiply values.

Example: `SELECT column1 * column2 FROM table;`

4. Division (/): Used to divide one value by another.

Example: `SELECT column1 / column2 FROM table;`

5. Modulo (%): Returns the remainder of a division operation.

Example: `SELECT column1 % column2 FROM table;`

Logical Operations:

1. Equality (=): Checks if two values are equal.

Example: `SELECT column1 FROM table WHERE column2 = value;`

2. Inequality (<>, !=): Checks if two values are not equal.

Example: `SELECT column1 FROM table WHERE column2 <> value;`

3. Greater than (>), Less than (<): Performs a greater than or less than comparison.

Example: `SELECT column1 FROM table WHERE column2 > value;`

4. Greater than or equal to (>=), Less than or equal to (<=): Performs a greater than or equal to or less
than or equal to comparison.

Example: `SELECT column1 FROM table WHERE column2 >= value;`

5. Logical AND (AND): Combines multiple conditions, all of which must be true.

Example: `SELECT column1 FROM table WHERE condition1 AND condition2;`


6. Logical OR (OR): Combines multiple conditions, at least one of which must be true.

Example: `SELECT column1 FROM table WHERE condition1 OR condition2;`

7. Logical NOT (NOT): Negates a condition, returning the opposite result.

Example: `SELECT column1 FROM table WHERE NOT condition;`

These arithmetic and logical operations allow you to perform calculations, comparisons, and logical
evaluations on data in SQL queries. They are fundamental for filtering and manipulating data based on
specific conditions and performing mathematical operations on numeric values.
6.Explain about different constraints in SQL?

A) 6)Certainly! Here are the different constraints commonly used in SQL:

1. NOT NULL Constraint:

- The NOT NULL constraint ensures that a column cannot have a NULL value.

- Example: `CREATE TABLE Employees (EmployeeID INT NOT NULL, Name VARCHAR(50));`

2. UNIQUE Constraint:

- The UNIQUE constraint ensures that the values in a column are unique and cannot have
duplicates.

- Example: `CREATE TABLE Employees (EmployeeID INT UNIQUE, Email VARCHAR(50));`

3. PRIMARY KEY Constraint:

- The PRIMARY KEY constraint is a combination of NOT NULL and UNIQUE constraints. It uniquely
identifies each row in a table.

- Example: `CREATE TABLE Employees (EmployeeID INT PRIMARY KEY, Name VARCHAR(50));`

4. FOREIGN KEY Constraint:

- The FOREIGN KEY constraint establishes a relationship between two tables, ensuring referential
integrity.

- Example:

sql

CREATE TABLE Orders (

OrderID INT PRIMARY KEY,

ProductID INT,

FOREIGN KEY (ProductID) REFERENCES Products(ProductID)

);

5. CHECK Constraint:

- The CHECK constraint defines a condition that must be satisfied for the values in a column.

- Example: `CREATE TABLE Employees (EmployeeID INT, Age INT CHECK (Age >= 18));`
6. DEFAULT Constraint:

- The DEFAULT constraint sets a default value for a column when no value is specified during an
INSERT operation.

- Example: `CREATE TABLE Employees (EmployeeID INT, Name VARCHAR(50) DEFAULT


'Unknown');`

7. INDEX Constraint:

- The INDEX constraint is used to create an index on one or more columns of a table. It improves
query performance.

- Example: `CREATE INDEX idx_last_name ON Employees (LastName);`

These constraints play a crucial role in maintaining data integrity, defining relationships between
tables, and enforcing business rules. They ensure that the data stored in the database follows
certain rules and restrictions, providing consistency and reliability.
7. Explain about various string functions in sql?

7)Certainly! SQL provides various string functions that allow you to manipulate and work with string
values. Here are some commonly used string functions in SQL:

1. CONCAT():

- Concatenates two or more strings together.

- Example: `SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;`

2. LENGTH():

- Returns the length (number of characters) of a string.

- Example: `SELECT LENGTH(product_name) FROM products;`

3. UPPER():

- Converts a string to uppercase.

- Example: `SELECT UPPER(last_name) FROM employees;`

4. LOWER():

- Converts a string to lowercase.

- Example: `SELECT LOWER(first_name) FROM employees;`

5. SUBSTRING():

- Extracts a substring from a string.

- Example: `SELECT SUBSTRING(product_name, 1, 3) FROM products;`

6. REPLACE():

- Replaces occurrences of a substring within a string with another substring.

- Example: `SELECT REPLACE(product_description, 'old', 'new') FROM products;`

7. TRIM():

- Removes leading and trailing spaces from a string.

- Example: `SELECT TRIM(product_name) FROM products;`

8. LEFT():

- Extracts a specified number of characters from the beginning of a string.


- Example: `SELECT LEFT(last_name, 3) FROM employees;`

9. RIGHT():

- Extracts a specified number of characters from the end of a string.

- Example: `SELECT RIGHT(last_name, 2) FROM employees;`

10. CHARINDEX():

- Returns the starting position of a substring within a string.

- Example: `SELECT CHARINDEX('book', product_name) FROM products;`

These string functions allow you to manipulate and extract information from strings in SQL queries. They
can be used for various tasks such as concatenation, case conversion, substring extraction, replacing
text, and more. String functions are essential for working with textual data in SQL.

You might also like