0% found this document useful (0 votes)
15 views11 pages

Assignment On Cassandra - Queries - 1. Create A

The document outlines a comprehensive set of Cassandra CQL commands for various database operations, including creating keyspaces and tables, performing CRUD operations, and managing data types and collections. It includes specific queries for inserting, updating, deleting, and retrieving student records, as well as handling collection types, counters, TTL, and import/export tasks. Each command is structured for execution in the cqlsh shell, covering a wide range of database functionalities.

Uploaded by

praneash P
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)
15 views11 pages

Assignment On Cassandra - Queries - 1. Create A

The document outlines a comprehensive set of Cassandra CQL commands for various database operations, including creating keyspaces and tables, performing CRUD operations, and managing data types and collections. It includes specific queries for inserting, updating, deleting, and retrieving student records, as well as handling collection types, counters, TTL, and import/export tasks. Each command is structured for execution in the cqlsh shell, covering a wide range of database functionalities.

Uploaded by

praneash P
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

Assignment on Cassandra – Queries

1. Create a keyspace named College with replication factor as 1.


2. Create a new column family named ‘Student’ with attributes like
stud_id
stud_name TEXT,
dept TEXT,
year INT,
gpa FLOAT
where the student ID should be a primary key, student name and department are strings, year is
a numeric data type, and GPA is a decimal number.
3. Problem Set: Cassandra CRUD Operations
i. Insert the following student records into the Students table:
John, CSE, 2nd year, GPA 7.8
Priya, ECE, 3rd year, GPA 8.4
Karthik, CSE, 1st year, GPA 6.9
ii. Retrieve all students from the Students table.
iii. Find the names and GPA of all students who belong to the CSE
department.
iv. Update Priya’s GPA from 8.4 to 9.0.
v. Delete Karthik’s record from the table.
vi. Retrieve all students whose GPA is greater than 8.0.
vii. Add a new column email TEXT to the Students table.
viii. Delete the entire Students table from the database.

4. CREATE (Insert Data)


i. Insert a new student Anitha, IT, 4th year, GPA 9.2.
ii. Insert a student Rahul, Mechanical, 2nd year, GPA 7.1.
iii. Insert multiple rows in a batch for:
o Meena, CSE, 3rd year, GPA 8.6
o Arjun, Civil, 1st year, GPA 6.5

READ (Select Data)


i. Retrieve only student names and departments of all students.
ii. Find all students in year 2 (second year).
iii. Get the details of a student using a specific stud_id.
iv. Retrieve students with GPA between 7.0 and 9.0.
v. Count the number of students in each department.
vi. Retrieve students ordered by GPA descending.
UPDATE (Modify Data)
i. Change John’s department from CSE to AI-DS.
ii. Increase Rahul’s GPA by 0.5.
iii. Update all 3rd year students’ GPA to 8.0.
iv. Add an email ID for Anitha: anitha@college.edu.
v. Update multiple columns at once for Priya: set dept = 'EEE' and gpa =
8.7.

DELETE (Remove Data)


i. Delete all students from IT department.
ii. Delete the GPA column for John (but keep other details).
iii. Remove all records from the Students table.
iv. Delete only students who are in 1st year.
v. Remove the column email from the Students table schema.

5. Table with Collection Types


CREATE TABLE Students (
stud_id UUID PRIMARY KEY,
stud_name TEXT,
dept TEXT,
subjects LIST<TEXT>,
skills SET<TEXT>,
grades MAP<TEXT, FLOAT>
);
subjects (LIST) → maintains insertion order, allows duplicates.
skills (SET) → no duplicates, unordered.
grades (MAP) → key-value pairs, e.g., course → GPA.

i. Insert a student with multiple subjects, skills, and grades.


ii. Insert another student with different inputs.
iii. Append a new subject "ML" to John’s subjects list.
iv. Prepend "OS" at the beginning of Priya’s subjects.
v. Remove "DBMS" from John’s subjects.
vi. Add a new skill "Java" to John’s skills.
vii. Remove "C++" from Priya’s skills.
viii. Update John’s grade in "AI" to 8.2.
ix. Add a new grade "OS": 9.1 for Priya.
x. Remove the "Math" entry from John’s grades.
xi. Retrieve all subjects of John.
xii. Retrieve only John’s grade in "DBMS".
xiii. Retrieve all students who have "Python" as a skill.
xiv. Retrieve all students who took "AI" as a subject.

6. MAP based queries


CREATE TABLE Students (
stud_id UUID PRIMARY KEY,
stud_name TEXT,
dept TEXT,
grades MAP<TEXT, FLOAT> -- course : grade
);

Insert John with some grades. 'John', 'CSE', {'Math': 8.5, 'DBMS': 9.0, 'AI': 7.8}
Insert Priya with different grades.'Priya', 'ECE', {'Circuits': 8.9, 'VLSI': 9.2}
Update John’s AI grade from 7.8 → 8.2.
Add a new grade "OS": 9.1 for Priya.
Add multiple subjects with grades for John.
Remove "Math" grade from John’s record.
Clear all grades for Priya.
Get all grades of John.
Get only John’s "DBMS" grade.
Retrieve students who have a grade in "VLSI".

7. Queries on COUNTER

Table Definition:
CREATE TABLE PageViews (
page_name TEXT PRIMARY KEY,
view_count COUNTER
);
Dataset Input:
· HomePage currently has 100 views
· ContactPage currently has 50 views
Questions:
i. Write a query to increment HomePage view count by 1 when a user
visits.
ii. Write a query to increase ContactPage views by 5 when a bulk update
of logs is processed.
iii. Write a query to decrease HomePage views by 2 (in case of duplicate
logs).
iv. Write a query to retrieve all pages with their current view counts.

8. Queries using TTL

Table Definition:
CREATE TABLE UserSessions (
session_id UUID PRIMARY KEY,
user_name TEXT,
login_time TIMESTAMP
);
Dataset Input:
· Alice logs in at 2025-08-29 10:00:00
· Bob logs in at 2025-08-29 10:05:00
· Charlie logs in at 2025-08-29 10:10:00
Questions:
i. Write a query to insert Alice’s session so it automatically expires after 1
hour (3600 seconds).
ii. Write a query to insert Bob’s session so it expires after 10 minutes (600
seconds).
iii. Write a query to find the remaining TTL of Bob’s username column.
iv. Write a query to insert Charlie’s session without TTL (permanent entry).

9. ALTER Command

CREATE KEYSPACE ecommerce


WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

USE ecommerce;

CREATE TABLE Orders (


order_id UUID PRIMARY KEY,
customer_name TEXT,
order_date TEXT,
amount TEXT,
status TEXT
);

i. Write a query to change the data type of amount from TEXT to FLOAT.
ii. Write a query to delete the status column from the Orders table.
iii. Write a query to drop the Orders table.
iv. Write a query to drop the ecommerce keyspace.

10. IMPORT and EXPORT

CREATE TABLE Products (


product_id UUID PRIMARY KEY,
product_name TEXT,
category TEXT,
price FLOAT,
stock INT
);

i. Write a command to export all data from the Products table


into a CSV file named products_backup.csv.
ii. Write a command to export only product_name and price
columns into products_price.csv.
iii. You have a CSV file new_products.csv with the following
content:
product_id,product_name,category,price,stock
c5b8d8b2-75e2-4d91-901a-3fdd12345678,Smartphone,Electronics,29999,50
d2a6c41f-48f4-48bb-9a3e-3fdd98765432,Laptop,Electronics,55000,30
Write a command to import this CSV file into the Products table.
iv. Write a command to import new_products.csv while skipping
the header row.
v. Write a command to export the Products table into
products_semicolon.csv with ; as delimiter.
give me a answer
Here is a comprehensive set of Cassandra CQL commands solving all the assignment queries
across schema definition, CRUD operations, collections, counters, TTL, ALTER, and
import/export tasks. Each command is ready to run in the cqlsh shell.

Keyspace and Table Creation

-- 1. Create keyspace
CREATE KEYSPACE College
WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};

-- 2. Create Students table (column family)


CREATE TABLE College.Student (
stud_id UUID PRIMARY KEY,
stud_name TEXT,
dept TEXT,
year INT,
gpa FLOAT
);

CRUD Operations

Insert Student Records

-- iii. Insert students (use UUID for stud_id, here using uuid())
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'John',
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Priya'
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Karthi
Read and Query Students

-- ii. Retrieve all students


SELECT * FROM College.Student;

-- iii. Names and GPA of CSE students


SELECT stud_name, gpa FROM College.Student WHERE dept = 'CSE' ALLOW FILTERING;

-- vi. Students with GPA > 8.0


SELECT * FROM College.Student WHERE gpa > 8.0 ALLOW FILTERING;

Update and Delete

-- iv. Update Priya's GPA (need stud_id of Priya from previous SELECT)
UPDATE College.Student SET gpa = 9.0 WHERE stud_id = <priya-uuid>;

-- v. Delete Karthik's record


DELETE FROM College.Student WHERE stud_id = <karthik-uuid>;

Add and Remove Columns/Tables

-- vii. Add email column


ALTER TABLE College.Student ADD email TEXT;

-- viii. Delete Students table


DROP TABLE College.Student;

Additional CRUD Examples

More Inserts

-- i. Anitha
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Anitha

-- ii. Rahul
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Rahul'

-- iii. Batch insert


BEGIN BATCH
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Meena'
INSERT INTO College.Student (stud_id, stud_name, dept, year, gpa) VALUES (uuid(), 'Arjun'
APPLY BATCH;
Reads

-- i. Student names and departments


SELECT stud_name, dept FROM College.Student;

-- ii. Students in year 2


SELECT * FROM College.Student WHERE year = 2 ALLOW FILTERING;

-- iii. Student details by stud_id


SELECT * FROM College.Student WHERE stud_id = <some-uuid>;

-- iv. GPA between 7.0 and 9.0


SELECT * FROM College.Student WHERE gpa >= 7.0 AND gpa <= 9.0 ALLOW FILTERING;

-- v. Count students per department


SELECT dept, COUNT(*) FROM College.Student GROUP BY dept; -- (Note: direct GROUP BY limit

-- vi. Ordered by GPA descending


SELECT * FROM College.Student WHERE gpa IS NOT NULL ALLOW FILTERING; -- Ordering needs to

Updates

-- i. Change John's department


UPDATE College.Student SET dept = 'AI-DS' WHERE stud_id = <john-uuid>;

-- ii. Increase Rahul's GPA by 0.5


UPDATE College.Student SET gpa = <current_gpa> + 0.5 WHERE stud_id = <rahul-uuid>;

-- iii. Set all 3rd year GPAs to 8.0


UPDATE College.Student SET gpa = 8.0 WHERE year = 3 ALLOW FILTERING;

-- iv. Add email for Anitha


UPDATE College.Student SET email = 'anitha@college.edu' WHERE stud_id = <anitha-uuid>;

-- v. Update Priya's dept and GPA


UPDATE College.Student SET dept = 'EEE', gpa = 8.7 WHERE stud_id = <priya-uuid>;

Deletes

-- i. Delete students from IT


DELETE FROM College.Student WHERE dept = 'IT' ALLOW FILTERING;

-- ii. Delete GPA for John


UPDATE College.Student SET gpa = null WHERE stud_id = <john-uuid>;

-- iii. Remove all Students table records


TRUNCATE College.Student;

-- iv. Delete 1st year students


DELETE FROM College.Student WHERE year = 1 ALLOW FILTERING;
-- v. Remove email column
ALTER TABLE College.Student DROP email;

Table with Collection Types

CREATE TABLE College.Students (


stud_id UUID PRIMARY KEY,
stud_name TEXT,
dept TEXT,
subjects LIST<TEXT>,
skills SET<TEXT>,
grades MAP<TEXT, FLOAT>
);

-- i. Insert student with collections


INSERT INTO College.Students (stud_id, stud_name, dept, subjects, skills, grades)
VALUES (uuid(), 'John', 'CSE', ['Math', 'DBMS'], {'Python', 'C++'}, {'Math': 8.7, 'DBMS':

-- ii. Another student


INSERT INTO College.Students (stud_id, stud_name, dept, subjects, skills, grades)
VALUES (uuid(), 'Priya', 'ECE', ['Circuits', 'VLSI'], {'C++', 'VHDL'}, {'Circuits': 8.8,

-- iii. Append subject "ML" to John's subjects


UPDATE College.Students SET subjects = subjects + ['ML'] WHERE stud_id = <john-uuid>;

-- iv. Prepend "OS" to Priya's subjects


UPDATE College.Students SET subjects = ['OS'] + subjects WHERE stud_id = <priya-uuid>;

-- v. Remove "DBMS" from John's subjects


UPDATE College.Students SET subjects = subjects - ['DBMS'] WHERE stud_id = <john-uuid>;

-- vi. Add skill "Java" to John


UPDATE College.Students SET skills = skills + {'Java'} WHERE stud_id = <john-uuid>;

-- vii. Remove "C++" from Priya


UPDATE College.Students SET skills = skills - {'C++'} WHERE stud_id = <priya-uuid>;

-- viii. Update John's "AI" grade


UPDATE College.Students SET grades['AI'] = 8.2 WHERE stud_id = <john-uuid>;

-- ix. Add grade "OS": 9.1 for Priya


UPDATE College.Students SET grades['OS'] = 9.1 WHERE stud_id = <priya-uuid>;

-- x. Remove "Math" grade from John


DELETE grades['Math'] FROM College.Students WHERE stud_id = <john-uuid>;

-- xi. Get all subjects of John


SELECT subjects FROM College.Students WHERE stud_id = <john-uuid>;

-- xii. Get John's "DBMS" grade


SELECT grades['DBMS'] FROM College.Students WHERE stud_id = <john-uuid>;

-- xiii. Students who have "Python" skill


SELECT * FROM College.Students WHERE skills CONTAINS 'Python' ALLOW FILTERING;
-- xiv. Students who took "AI" as subject
SELECT * FROM College.Students WHERE subjects CONTAINS 'AI' ALLOW FILTERING;

MAP Based Queries

CREATE TABLE College.Students (


stud_id UUID PRIMARY KEY,
stud_name TEXT,
dept TEXT,
grades MAP<TEXT, FLOAT>
);

-- Insert John and Priya


INSERT INTO College.Students (stud_id, stud_name, dept, grades)
VALUES (uuid(), 'John', 'CSE', {'Math':8.5, 'DBMS':9.0, 'AI':7.8});
INSERT INTO College.Students (stud_id, stud_name, dept, grades)
VALUES (uuid(), 'Priya', 'ECE', {'Circuits':8.9, 'VLSI':9.2});

-- Update John's AI grade


UPDATE College.Students SET grades['AI'] = 8.2 WHERE stud_id = <john-uuid>;

-- Add new grade for Priya


UPDATE College.Students SET grades['OS'] = 9.1 WHERE stud_id = <priya-uuid>;

-- Add multiple grades for John


UPDATE College.Students SET grades = grades + {'ML': 8.7, 'DL': 8.9} WHERE stud_id = <joh

-- Remove "Math" grade from John


DELETE grades['Math'] FROM College.Students WHERE stud_id = <john-uuid>;

-- Clear all grades for Priya


UPDATE College.Students SET grades = {} WHERE stud_id = <priya-uuid>;

-- Get all grades of John


SELECT grades FROM College.Students WHERE stud_id = <john-uuid>;

-- Get only John's "DBMS" grade


SELECT grades['DBMS'] FROM College.Students WHERE stud_id = <john-uuid>;

-- Students with grade in "VLSI"


SELECT * FROM College.Students WHERE grades CONTAINS KEY 'VLSI' ALLOW FILTERING;

Counter Queries

CREATE TABLE PageViews (


page_name TEXT PRIMARY KEY,
view_count COUNTER
);

-- HomePage has 100, ContactPage 50 (set via updates)


UPDATE PageViews SET view_count = view_count + 100 WHERE page_name = 'HomePage';
UPDATE PageViews SET view_count = view_count + 50 WHERE page_name = 'ContactPage';

-- i. Increment HomePage by 1
UPDATE PageViews SET view_count = view_count + 1 WHERE page_name = 'HomePage';

-- ii. Increase ContactPage by 5


UPDATE PageViews SET view_count = view_count + 5 WHERE page_name = 'ContactPage';

-- iii. Decrease HomePage by 2


UPDATE PageViews SET view_count = view_count - 2 WHERE page_name = 'HomePage';

-- iv. Retrieve all pages/views


SELECT * FROM PageViews;

TTL Queries

CREATE TABLE College.UserSessions (


session_id UUID PRIMARY KEY,
user_name TEXT,
login_time TIMESTAMP
);

-- Insert session with TTL


INSERT INTO College.UserSessions (session_id, user_name, login_time) VALUES (uuid(), 'Ali
INSERT INTO College.UserSessions (session_id, user_name, login_time) VALUES (uuid(), 'Bob

-- Query remaining TTL of Bob's username


SELECT TTL(user_name) FROM College.UserSessions WHERE session_id = <bob-session-uuid>;

-- Charlie's session permanent


INSERT INTO College.UserSessions (session_id, user_name, login_time) VALUES (uuid(), 'Cha

ALTER Commands

CREATE KEYSPACE ecommerce


WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

USE ecommerce;

CREATE TABLE Orders (


order_id UUID PRIMARY KEY,
customer_name TEXT,
order_date TEXT,
amount TEXT,
status TEXT
);

-- i. Change amount type (drop then add)


ALTER TABLE Orders DROP amount;
ALTER TABLE Orders ADD amount FLOAT;
-- ii. Delete status column
ALTER TABLE Orders DROP status;

-- iii. Drop Orders table


DROP TABLE Orders;

-- iv. Drop ecommerce keyspace


DROP KEYSPACE ecommerce;

IMPORT and EXPORT

CREATE TABLE Products (


product_id UUID PRIMARY KEY,
product_name TEXT,
category TEXT,
price FLOAT,
stock INT
);

-- i. Export all to CSV


COPY Products TO 'products_backup.csv';

-- ii. Export product_name and price only


COPY Products (product_name, price) TO 'products_price.csv';

-- iii. Import CSV (entire content)


COPY Products FROM 'new_products.csv';

-- iv. Import skipping header


COPY Products FROM 'new_products.csv' WITH HEADER = TRUE;

-- v. Export with semicolon delimiter


COPY Products TO 'products_semicolon.csv' WITH DELIMITER = ';';

Notes
Replace <uuid> with the actual UUID returned from inserts or select queries as needed for
updates/deletes.
Use ALLOW FILTERING carefully—filtering on non-primary-key columns is inefficient for large
tables.
Cassandra does not support some SQL features like direct aggregation or ordering in
SELECT, so handle some queries at application-level if required.
This covers every part of the assignment with the necessary Cassandra CQL syntax.

You might also like