diff --git a/Nandini/SQLAssignments/NandiniVujani_1543_Assignment1.sql b/Nandini/SQLAssignments/NandiniVujani_1543_Assignment1.sql new file mode 100644 index 0000000000000000000000000000000000000000..e81009053439ad81f554c6a5274b4f51c88044e5 --- /dev/null +++ b/Nandini/SQLAssignments/NandiniVujani_1543_Assignment1.sql @@ -0,0 +1,238 @@ +--CREATE A TABLE WITH CHECK ,DEFAULT CONSTRAINTS +CREATE TABLE Event( + EventID int PRIMARY KEY, + EventName varchar(50), + EventDate Date CHECK (EventDate >= CAST(GETDATE() AS DATE)), + Venue varchar(50) NOT NULL, + MaxAttendees int CHECK (MaxAttendees >0), + Status varchar(50) DEFAULT 'SCHEDULED'); + +--THIS INSERTION GIVES THE DEFAULT VALUE TO STATUS COL AS I NOT MENTIONED THE STATUS COL IN INSERT STMT +INSERT INTO Event (EventID, EventName, EventDate, Venue, MaxAttendees) +VALUES + (1, 'Annual Tech Conference', CAST('2024-12-15' AS DATE), 'Convention Center', 500), + (2, 'Music Festival', CAST('2025-01-20' AS DATE), 'City Park', 1000); + +--This insert stmt throws error like conflicted with CHECK constraint of MaxAttendees as the attendees are zero +INSERT INTO Event (EventID, EventName, EventDate, Venue, MaxAttendees,Status) +VALUES + (1, 'Annual Tech Conference', CAST('2024-12-15' AS DATE), 'Convention Center', 0,'Pending'); + +--This insert stmt throws error like conflicted with CHECK constraint of Date as it is less than the current date +INSERT INTO Event (EventID, EventName, EventDate, Venue, MaxAttendees,Status) +VALUES + (1, 'Annual Tech Conference', CAST('2024-01-15' AS DATE), 'Convention Center', 0,'Pending'); + +--Create a table with all the below data types and insert records +--INT, Varchar, Char, Nvarchar, Float, Double, Numeric, Date, Datetime +-- Create the Datatype table +CREATE TABLE DemoDataType ( + ID INT PRIMARY KEY, -- Integer type + Name VARCHAR(100), -- Variable-length string + Code CHAR(10), -- Fixed-length string + Description NVARCHAR(255), -- Variable-length Unicode string + Price FLOAT, -- Approximate numeric with floating point + Amount NUMERIC(10, 2), -- Exact numeric with specified precision + CreatedDate DATE, -- Date type (without time) + CreatedAt DATETIME -- Date and time type +); + +-- Insert records into the SampleData table +INSERT INTO DemoDataType (ID, Name, Code, Description, Price, Amount, CreatedDate, CreatedAt) +VALUES +(1, 'Product A', 'A001', 'Description for Product A', 19.99, 100.00, '2023-01-01', '2023-01-01 10:00:00'), +(2, 'Product B', 'B002', 'Description for Product B', 29.99, 200.50, '2023-02-01', '2023-02-01 11:30:00'), +(3, 'Product C', 'C003', 'Description for Product C', 39.99, 300.75, '2023-03-01', '2023-03-01 12:45:00'), +(4, 'Product D', 'D004', 'Description for Product D', 49.99, 400.20, '2023-04-01', '2023-04-01 09:15:00'); + +SELECT * FROM DemoDataType; + +--CREATE TABLE WITH IDENTITY AND DO BELOW OPERATIONS +--DELETE few rows and then Insert some records. Observe the Identity value and same process do it for TRUNCATE +CREATE TABLE Fruit( + FruitID int IDENTITY(1,1) PRIMARY KEY, + FruitName varchar(50), + Quantity int , + Price Decimal(10,2)); --Price per Item +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Apple', 100, 0.50); +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Banana', 150, 0.30); +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Orange', 200, 0.40); +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Grapes', 50, 2.00); + +SELECT * FROM Fruit; + +DELETE FROM Fruit WHERE FruitID = 2; -- Deletes Banana +DELETE FROM Fruit WHERE FruitID = 4; -- Deletes Grapes +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Mango', 80, 1.50); +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Pineapple', 30, 3.00); + +--Check the current records again +--After performing DELETE operations +--the IDENTITY values for new inserts continue from the last highest value (in this case, 6). +SELECT * FROM Fruit; + +--Truncate the Table +TRUNCATE TABLE Fruit; + +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Kiwi', 60, 1.20); +INSERT INTO Fruit (FruitName, Quantity, Price) VALUES ('Strawberry', 40, 2.50); +--Check the current records after truncate +--After using TRUNCATE +--the IDENTITY values reset to the initial seed value (in this case, 1). +SELECT * FROM Fruit; + +--CREATE A TABLE WITH COMPUTED COLUMN +CREATE TABLE Sales ( + SaleID INT IDENTITY(1,1) PRIMARY KEY, + ProductName NVARCHAR(100), + OriginalPrice DECIMAL(10, 2), + DiscountPercentage DECIMAL(5, 2), + DiscountAmount AS (OriginalPrice * (DiscountPercentage / 100)) -- Computed column +); + +INSERT INTO Sales (ProductName, OriginalPrice, DiscountPercentage) + VALUES ('Laptop', 1200.00, 10.00), + ('Tablet', 400.00, 5.00), + ('Headphones', 150.00, 20.00); + +SELECT * FROM Sales; + +UPDATE Sales SET DiscountPercentage = 20.00 WHERE SaleID = 2; -- Update discount + +SELECT * FROM Sales; + +--CREATE TWO TABLES ONE WITH PRIMARY KEY AND OTHER WITH FOREIGN KEY +CREATE TABLE Customer ( + CustomerID INT PRIMARY KEY, -- Primary Key + FirstName NVARCHAR(50), + LastName NVARCHAR(50), + Email NVARCHAR(100), + Phone NVARCHAR(15) +); + +CREATE TABLE Orders ( + OrderID INT PRIMARY KEY, -- Primary Key + OrderDate DATETIME, + Amount DECIMAL(10, 2), + CustomerID INT, -- Foreign Key + FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID) -- Foreign Key constraint +); + + +ALTER TABLE Customer +DROP CONSTRAINT PK__Customer__A4AE64B816E3B4D5; + +ALTER TABLE Invoices +DROP CONSTRAINT [FK__Invoices__Custom__44FF419A]; +-- Insert customers +INSERT INTO Customer (CustomerID,FirstName, LastName, Email, Phone) + VALUES (1,'John', 'Doe', 'john.doe@example.com', '123-456-7890'), + (2,'Jane', 'Smith', 'jane.smith@example.com', '098-765-4321'); +INSERT INTO Customer (CustomerID,FirstName, LastName, Email, Phone) + VALUES (3,'John', 'Smith', 'john.smith@example.com', '111-406-7890'), + (4,'David', 'Gold', 'david@example.com', '111-444-7890'), + (5,'Harry', 'Potter', 'harry@example.com', '101-944-9090'); +-- Insert orders +INSERT INTO Orders (OrderID,OrderDate, Amount, CustomerID) VALUES (1,GETDATE(), 150.00, 1); -- Order for John Doe +INSERT INTO Orders (OrderID,OrderDate, Amount, CustomerID) VALUES (2,GETDATE(), 200.00, 2); -- Order for Jane Smith + +--Try to insert the record which is not there in primary key into the table where Foreign key created +--THIS INSERT STMT CONFLICTS WITH THE FOREIGN KEY CONSTRAINT "FK__Orders__Customer__4222D4EF" +INSERT INTO Orders (OrderID,OrderDate, Amount, CustomerID) VALUES (3,GETDATE(), 219.00, 3); + +--Try to insert the NULL values into foreign key table +-- Insert an order with NULL CustomerID +INSERT INTO Orders(OrderID,OrderDate, Amount, CustomerID) VALUES (4,GETDATE(), 100.00, NULL); + +SELECT * FROM Customer; +SELECT * FROM Orders; + +--PRACTISE CASCADE +CREATE TABLE Invoices ( + InvoiceID INT IDENTITY(1,1) PRIMARY KEY, -- Primary Key + CustomerID INT, -- Foreign Key referencing Customers + InvoiceDate DATETIME, + TotalAmount DECIMAL(10, 2), + FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID) + ON DELETE CASCADE -- Cascades delete + ON UPDATE CASCADE -- Cascades update +); +-- Insert invoices +INSERT INTO Invoices (CustomerID, InvoiceDate, TotalAmount) VALUES (1, GETDATE(), 250.00); +INSERT INTO Invoices (CustomerID, InvoiceDate, TotalAmount) VALUES (2, GETDATE(), 450.00); + +SELECT + fk.name AS ForeignKeyName +FROM + sys.foreign_keys AS fk +JOIN + sys.tables AS t ON fk.parent_object_id = t.object_id +WHERE + t.name = 'Orders'; + +--DROPPING THE CONSTRAINT +ALTER TABLE Orders +DROP CONSTRAINT FK_Orders_Customer; + +ALTER TABLE Orders +ADD CONSTRAINT FK_Orders_Customer FOREIGN KEY (CustomerID) +REFERENCES Customer(CustomerID) +ON DELETE SET NULL +ON UPDATE SET DEFAULT; + + +SELECT * FROM Customer; + +SELECT * FROM Orders; + +SELECT * FROM Invoices; + +--AS we have applied cascade command that customerid deletes from invoices table & in orders table set to null +DELETE FROM Customer WHERE CustomerID=1; + +UPDATE Customer SET CustomerID=15 WHERE CustomerID=2; + + +--ALTER TABLE +--Create the Products table +CREATE TABLE Products ( + ProductID int PRIMARY KEY, + ProductName varchar(100) NOT NULL, + Price decimal(10, 2) NOT NULL, + Quantity int NOT NULL, + Email nvarchar(100) NULL +); + +-- Change the column data type and length +ALTER TABLE Products +ALTER COLUMN Email varchar(150); -- Changing the length of the Email column + +-- Rename the column name +EXEC sp_rename 'Products.ProductName', 'Name', 'COLUMN'; -- Renaming ProductName to Name + +-- Add new column +ALTER TABLE Products +ADD Category VARCHAR(50); + +-- Drop existing column +ALTER TABLE Products +DROP COLUMN Quantity; + +--Add a check constraint +ALTER TABLE Products +ADD CONSTRAINT CK_Products_Price CHECK (Price > 0); + +-- Remove the check constraint +ALTER TABLE Products +DROP CONSTRAINT CK_Products_Price; + +------------------------------------------------------------------- +---Applied check and default constraint on the same column +CREATE TABLE DemoTable ( + StockID INT PRIMARY KEY IDENTITY(1,1), + StockName VARCHAR(100) NOT NULL, + Stock INT DEFAULT 0 CHECK (Stock >= 0) -- Default value is 0, and Stock must be >= 0 +); + +INSERT INTO DemoTable(StockName) VALUES ('Product A'); +SELECT * FROM DemoTable;