TRUNCATE
TRUNCATE
TRUNCATE
structure.
DROP: Removes the entire table, including its structure.
DELETE: Removes specific rows, preserving the table
structure and other rows.
ere are some practice questions based on the SQL concepts you've reviewed:
sql
Copy code
CREATE DATABASE SchoolDB;
2. Use a Database:
o Write an SQL query to select the SchoolDB database for subsequent operations.
sql
Copy code
USE SchoolDB;
3. Delete a Database:
o Write an SQL query to delete the SchoolDB database.
sql
Copy code
DROP DATABASE SchoolDB;
4. Create a Table:
o Write an SQL query to create a table named Teachers with the following
columns: TeacherID (integer), FirstName (nvarchar(50)), LastName
(nvarchar(50)), HireDate (date), and Subject (nvarchar(100)).
sql
Copy code
CREATE TABLE Teachers (
TeacherID int,
FirstName nvarchar(50),
LastName nvarchar(50),
HireDate date,
Subject nvarchar(100)
);
5. Drop a Table:
o Write an SQL query to delete the Teachers table from the database.
sql
Copy code
DROP TABLE Teachers;
6. Truncate a Table:
o Write an SQL query to truncate the Students table, removing all its data but
keeping the table structure.
sql
Copy code
TRUNCATE TABLE Students;
SQL Constraints
sql
Copy code
CREATE TABLE Courses (
CourseID int PRIMARY KEY,
CourseName nvarchar(100) NOT NULL,
Credits int NOT NULL
);
sql
Copy code
ALTER TABLE Teachers
ADD CONSTRAINT UNIQUE_Teachers_Email UNIQUE (Email);
sql
Copy code
CREATE TABLE Departments (
DepartmentID int PRIMARY KEY,
DepartmentName nvarchar(100) NOT NULL
);
10. Add a Foreign Key Constraint:
o Write an SQL query to create a Enrollments table with StudentID (int, foreign
key referencing Students(StudentID)), CourseID (int, foreign key referencing
Courses(CourseID)), and EnrollmentDate (date).
sql
Copy code
CREATE TABLE Enrollments (
StudentID int,
CourseID int,
EnrollmentDate date,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
sql
Copy code
ALTER TABLE Courses
ADD CONSTRAINT CHECK_Credits CHECK (Credits >= 1 AND Credits <= 5);
sql
Copy code
ALTER TABLE Courses
ADD CONSTRAINT DEFAULT_Credits DEFAULT 3 FOR Credits;
sql
Copy code
INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth)
VALUES (1, 'John', 'Doe', '2000-01-01');
sql
Copy code
UPDATE Students
SET LastName = 'Smith'
WHERE StudentID = 1;
sql
Copy code
DELETE FROM Students
WHERE LastName = 'Doe';
sql
Copy code
TRUNCATE TABLE Enrollments;
sql
Copy code
SELECT *
FROM Employees;
sql
Copy code
SELECT FirstName, LastName, Email
FROM Customers;
sql
Copy code
SELECT *
FROM Orders
WHERE OrderDate > '2023-01-01';
LIKE Operator
sql
Copy code
SELECT *
FROM Employees
WHERE LastName LIKE 'S%';
sql
Copy code
SELECT *
FROM Courses
WHERE CourseName LIKE '%Math%';
6. Renaming Columns:
o Write an SQL query to retrieve the ProductName and Price columns from the
Products table, but rename them as Product and Cost, respectively.
sql
Copy code
SELECT ProductName AS Product, Price AS Cost
FROM Products;
sql
Copy code
SELECT GETDATE();
8. Extracting Substrings:
o Write an SQL query to retrieve the first 3 characters of the FirstName column
from the Employees table.
sql
Copy code
SELECT SUBSTRING(FirstName, 1, 3) AS ShortName
FROM Employees;
ORDER BY Clause
9. Sorting Data:
o Write an SQL query to retrieve the ProductName and Price from the Products
table, sorted by Price in descending order.
sql
Copy code
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC;
TOP Clause
sql
Copy code
SELECT TOP 5 ProductName, Price
FROM Products
ORDER BY Price DESC;
Key Constraints
Key constraints ensure that the data within a table is uniquely
identifiable and maintain the integrity of relationships between
tables.
Certainly! Here are more practice questions on SQL concepts, including solved examples for
each:
Question: Write an SQL query to create a database named LibraryDB with UTF-8 encoding.
Solution:
sql
Copy code
CREATE DATABASE LibraryDB
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Question: Write an SQL query to list all tables in the LibraryDB database.
Solution:
sql
Copy code
USE LibraryDB;
SHOW TABLES;
Question: Write an SQL query to create a table named Books with the following columns:
BookID (auto-incrementing integer, primary key), Title (nvarchar(200)), Author
(nvarchar(100)), and PublicationYear (int).
Solution:
sql
Copy code
CREATE TABLE Books (
BookID int AUTO_INCREMENT PRIMARY KEY,
Title nvarchar(200),
Author nvarchar(100),
PublicationYear int
);
Question: Write an SQL query to drop the Books and Authors tables from the database.
Solution:
sql
Copy code
DROP TABLE IF EXISTS Books;
DROP TABLE IF EXISTS Authors;
Question: Write an SQL query to truncate the LibraryRecords table but only if the table
contains fewer than 1000 rows.
Solution:
sql
Copy code
SET @row_count = (SELECT COUNT(*) FROM LibraryRecords);
(Note: The conditional truncation might require a stored procedure or script in some SQL
implementations.)
2. SQL Constraints
Question: Write an SQL query to set a default value of 0 for the Discount column in the
Products table, assuming Discount is of type decimal(5,2).
Solution:
sql
Copy code
ALTER TABLE Products
ADD CONSTRAINT DF_Discount DEFAULT 0 FOR Discount;
Question: Write an SQL query to create a table named OrderItems with columns OrderID (int),
ProductID (int), and Quantity (int), and set both OrderID and ProductID as a composite
primary key.
Solution:
sql
Copy code
CREATE TABLE OrderItems (
OrderID int,
ProductID int,
Quantity int,
PRIMARY KEY (OrderID, ProductID)
);
Question: Write an SQL query to modify the OrderItems table to add a foreign key constraint
on OrderID that references Orders(OrderID) with cascade delete.
Solution:
sql
Copy code
ALTER TABLE OrderItems
ADD CONSTRAINT FK_OrderItems_Orders
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID)
ON DELETE CASCADE;
Question: Write an SQL query to add a UNIQUE constraint to ensure that the combination of
FirstName and LastName is unique in the Customers table.
Solution:
sql
Copy code
ALTER TABLE Customers
ADD CONSTRAINT UQ_Customers_Name UNIQUE (FirstName, LastName);
Question: Write an SQL query to add a CHECK constraint to ensure that the Status column in
the Orders table only contains values 'Pending', 'Shipped', or 'Delivered'.
Solution:
sql
Copy code
ALTER TABLE Orders
ADD CONSTRAINT CHK_Status CHECK (Status IN ('Pending', 'Shipped',
'Delivered'));
Question: Write an SQL query to insert three rows into the Books table with different titles and
authors.
Solution:
sql
Copy code
INSERT INTO Books (Title, Author, PublicationYear)
VALUES
('The Great Gatsby', 'F. Scott Fitzgerald', 1925),
('1984', 'George Orwell', 1949),
('To Kill a Mockingbird', 'Harper Lee', 1960);
Solution:
sql
Copy code
UPDATE Books
SET PublicationYear = 2024
WHERE Author = 'J.K. Rowling';
Question: Write an SQL query to delete all rows from the Orders table where OrderDate is
before '2023-01-01'.
Solution:
sql
Copy code
DELETE FROM Orders
WHERE OrderDate < '2023-01-01';
Question: Write an SQL query to delete all records from the OrderItems table where the
corresponding OrderID in the Orders table has a Status of 'Cancelled'.
Solution:
sql
Copy code
DELETE oi
FROM OrderItems oi
JOIN Orders o ON oi.OrderID = o.OrderID
WHERE o.Status = 'Cancelled';
Question: Write an SQL query to retrieve the average price and total number of products from
the Products table.
Solution:
sql
Copy code
SELECT
AVG(Price) AS AveragePrice,
COUNT(*) AS TotalProducts
FROM Products;
Question: Write an SQL query to retrieve the ProductName and Price from the Products table,
sorted by Price in ascending order, and limit the results to the top 10 rows.
Solution:
sql
Copy code
SELECT ProductName, Price
FROM Products
ORDER BY Price ASC
LIMIT 10;
Question: Write an SQL query to retrieve all rows from the Employees table where the
Department is 'Sales' and the Salary is greater than 50000.
Solution:
sql
Copy code
SELECT *
FROM Employees
WHERE Department = 'Sales' AND Salary > 50000;
5. LIKE Operator
Question: Write an SQL query to find all email addresses in the Customers table that end with
'example.com'.
Solution:
sql
Copy code
SELECT Email
FROM Customers
WHERE Email LIKE '%@example.com';
Solution:
sql
Copy code
SELECT ProductName
FROM Products
WHERE ProductName LIKE '%\_%' ESCAPE '\';
Question: Write an SQL query to retrieve Price and its 10% discount from the Products table,
renaming the discount column as DiscountedPrice.
Solution:
sql
Copy code
SELECT
Price,
Price * 0.90 AS DiscountedPrice
FROM Products;
Question: Write an SQL query to retrieve the year from the OrderDate column in the Orders
table.
Solution:
sql
Copy code
SELECT YEAR(OrderDate) AS OrderYear
FROM Orders;
Question: Write an SQL query to concatenate FirstName and LastName from the Employees
table with a space in between, and rename the concatenated result as FullName.
Solution:
sql
Copy code
SELECT
CONCAT(FirstName, ' ', LastName) AS FullName
FROM Employees;
8. ORDER BY Clause
Question: Write an SQL query to retrieve ProductName and Price from the Products table,
sorted by Price in ascending order and then by ProductName in descending order.
Solution:
sql
Copy code
SELECT ProductName, Price
FROM Products
ORDER BY Price ASC, ProductName DESC;
9. TOP Clause
Question: Write an SQL query to retrieve the top 10% most expensive products from the
Products table.
Solution:
sql
Copy code
SELECT TOP (10) PERCENT ProductName, Price
FROM Products
ORDER BY Price DESC;
These solved questions cover a variety of SQL concepts, helping you practice and enhance your
skills in SQL queries, constraints, and data manipulation.