Oracle Movie Rating Database Queries

Database Schema: Practice Oracle SQL queries on a Telugu movie rating database with string functions, date functions, and aggregate operations.
S.No Movie Name Year Actor Director Rating Review
1 Baahubali: The Beginning 2015 Prabhas S.S. Rajamouli 4.8 Epic visual spectacle that revolutionized Indian cinema
2 Baahubali 2: The Conclusion 2017 Prabhas S.S. Rajamouli 4.9 Grand conclusion to the epic saga with amazing climax
3 RRR 2022 N.T. Rama Rao Jr. S.S. Rajamouli 4.9 Oscar-winning masterpiece with breathtaking action sequences
4 Pushpa: The Rise 2021 Allu Arjun Sukumar 4.5 Mass entertainer with Allu Arjun's iconic performance
5 Ala Vaikunthapurramuloo 2020 Allu Arjun Trivikram Srinivas 4.3 Perfect blend of entertainment and emotions
6 Arjun Reddy 2017 Vijay Deverakonda Sandeep Reddy Vanga 4.2 Bold and intense romantic drama
7 Jersey 2019 Nani Gowtam Tinnanuri 4.6 Heartwarming sports drama with brilliant performances
8 Sita Ramam 2022 Dulquer Salmaan Hanu Raghavapudi 4.7 Beautiful period love story with soulful music
9 Eega 2012 Nani S.S. Rajamouli 4.4 Innovative revenge story with amazing visual effects
10 Majili 2019 Nani Shiva Nirvana 4.1 Emotional love story with realistic performances

Table Creation SQL

CREATE TABLE movie_ratings (
    sno NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    moviename VARCHAR2(100) NOT NULL,
    released_year NUMBER,
    actor VARCHAR2(100),
    director VARCHAR2(100),
    rating NUMBER(2,1) CHECK (rating BETWEEN 0.0 AND 5.0),
    review CLOB,
    last_updated TIMESTAMP DEFAULT SYSTIMESTAMP
);

-- Insert sample data
INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Baahubali: The Beginning', 2015, 'Prabhas', 'S.S. Rajamouli', 4.8, 'Epic visual spectacle that revolutionized Indian cinema');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Baahubali 2: The Conclusion', 2017, 'Prabhas', 'S.S. Rajamouli', 4.9, 'Grand conclusion to the epic saga with amazing climax');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('RRR', 2022, 'N.T. Rama Rao Jr.', 'S.S. Rajamouli', 4.9, 'Oscar-winning masterpiece with breathtaking action sequences');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Pushpa: The Rise', 2021, 'Allu Arjun', 'Sukumar', 4.5, 'Mass entertainer with Allu Arjun''s iconic performance');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Ala Vaikunthapurramuloo', 2020, 'Allu Arjun', 'Trivikram Srinivas', 4.3, 'Perfect blend of entertainment and emotions');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Arjun Reddy', 2017, 'Vijay Deverakonda', 'Sandeep Reddy Vanga', 4.2, 'Bold and intense romantic drama');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Jersey', 2019, 'Nani', 'Gowtam Tinnanuri', 4.6, 'Heartwarming sports drama with brilliant performances');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Sita Ramam', 2022, 'Dulquer Salmaan', 'Hanu Raghavapudi', 4.7, 'Beautiful period love story with soulful music');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Eega', 2012, 'Nani', 'S.S. Rajamouli', 4.4, 'Innovative revenge story with amazing visual effects');

INSERT INTO movie_ratings (moviename, released_year, actor, director, rating, review) VALUES
('Majili', 2019, 'Nani', 'Shiva Nirvana', 4.1, 'Emotional love story with realistic performances');

Interactive SELECT SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Display all movies with their release year and rating, sorted alphabetically by movie name

SELECT moviename, released_year, rating FROM movie_ratings ORDER BY moviename;

2. Show the 5 movies with the highest ratings in descending order

SELECT moviename, rating FROM movie_ratings ORDER BY rating DESC FETCH FIRST 5 ROWS ONLY;

3. List all movies directed by S.S. Rajamouli in chronological order

SELECT moviename, released_year FROM movie_ratings 
WHERE director LIKE '%Rajamouli%' ORDER BY released_year;

4. Display Allu Arjun's movies sorted by rating (highest first)

SELECT moviename, released_year, rating FROM movie_ratings 
WHERE actor = 'Allu Arjun' ORDER BY rating DESC;

5. Show movies released in the most recent 5 years

SELECT moviename, released_year FROM movie_ratings 
WHERE released_year >= EXTRACT(YEAR FROM SYSDATE) - 5 
ORDER BY released_year DESC;

6. Find movies where the review contains the word "performance"

SELECT moviename, review FROM movie_ratings 
WHERE REGEXP_LIKE(review, 'performance', 'i');

7. Calculate average ratings for actors with at least 2 movies

SELECT actor, AVG(rating) AS avg_rating, COUNT(*) AS movie_count 
FROM movie_ratings 
GROUP BY actor 
HAVING COUNT(*) >= 2 
ORDER BY avg_rating DESC;

8. Provide statistics about movies grouped by release year

SELECT released_year, COUNT(*) AS movie_count, 
AVG(rating) AS avg_rating, MAX(rating) AS max_rating 
FROM movie_ratings 
GROUP BY released_year 
ORDER BY released_year DESC;

9. List highly rated movies (4.5 stars or above)

SELECT moviename, rating FROM movie_ratings 
WHERE rating BETWEEN 4.5 AND 5.0 
ORDER BY rating DESC;

10. Return formatted movie information in a more readable way

SELECT moviename || ' (' || released_year || ')' || ' - Directed by ' || director AS movie_info,
'Starring: ' || actor || ' | Rating: ' || rating AS details 
FROM movie_ratings;

11. Identify movies with lengthy reviews (more than 50 characters)

SELECT moviename, LENGTH(review) AS review_length 
FROM movie_ratings 
WHERE LENGTH(review) > 50 
ORDER BY review_length DESC;

12. Categorize movies into rating ranges and count them

SELECT 
    CASE 
        WHEN rating BETWEEN 0 AND 3 THEN '0-3'
        WHEN rating BETWEEN 3 AND 4 THEN '3-4'
        WHEN rating BETWEEN 4 AND 5 THEN '4-5'
    END AS rating_range,
    COUNT(*) AS movie_count
FROM movie_ratings
GROUP BY 
    CASE 
        WHEN rating BETWEEN 0 AND 3 THEN '0-3'
        WHEN rating BETWEEN 3 AND 4 THEN '3-4'
        WHEN rating BETWEEN 4 AND 5 THEN '4-5'
    END
ORDER BY rating_range;

UPDATE SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Update Rating for a Specific Movie

UPDATE movie_ratings 
SET rating = 4.7 
WHERE moviename = 'Majili';

Updates the rating of 'Majili' to 4.7

2. Update Review Text

UPDATE movie_ratings 
SET review = 'Epic masterpiece that changed Indian cinema forever' 
WHERE moviename = 'Baahubali: The Beginning';

Modifies the review text for Baahubali: The Beginning

3. Update Multiple Columns (Rating + Review)

UPDATE movie_ratings 
SET rating = 4.8, 
    review = 'Even better on second viewing - true classic' 
WHERE moviename = 'RRR';

Updates both rating and review for RRR simultaneously

4. Conditional Update (Only if Current Rating is Lower)

UPDATE movie_ratings 
SET rating = 4.6 
WHERE moviename = 'Arjun Reddy' AND rating < 4.6;

Only updates if current rating is below 4.6

5. Update Director Name for Multiple Movies

UPDATE movie_ratings 
SET director = 'S.S. Rajamouli' 
WHERE director LIKE '%Rajamouli%';

Standardizes director name format for all Rajamouli movies

6. Update Based on Release Year

UPDATE movie_ratings 
SET rating = rating + 0.1 
WHERE released_year = 2022 AND rating <= 4.9;

Gives a small rating boost to all 2022 releases

7. Update Actor Name (Alias Correction)

UPDATE movie_ratings 
SET actor = 'Jr. NTR' 
WHERE actor = 'N.T. Rama Rao Jr.';

Changes actor name to more common alias

8. Increment All Ratings by 0.1 (Max 5.0)

UPDATE movie_ratings 
SET rating = LEAST(rating + 0.1, 5.0);

Gives all movies a small rating boost without exceeding 5.0

9. Update with Subquery (Movies Below Average Rating)

UPDATE movie_ratings 
SET review = review || ' [Underrated]' 
WHERE rating < (SELECT AVG(rating) FROM movie_ratings);

Marks reviews of below-average movies with "[Underrated]"

10. Bulk Update with CASE Statement

UPDATE movie_ratings 
SET rating = CASE 
    WHEN director = 'S.S. Rajamouli' THEN LEAST(rating + 0.2, 5.0)
    WHEN released_year >= 2020 THEN LEAST(rating + 0.1, 5.0)
    ELSE rating
END;

Gives Rajamouli movies extra boost, recent movies small boost

Oracle ALTER SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Add a New Column (Box Office Collection)

ALTER TABLE movie_ratings 
ADD (box_office NUMBER(12,2));

Adds a new column to store box office collection amounts in Oracle

2. Drop a Column last_updated

ALTER TABLE movie_ratings 
DROP COLUMN last_updated;

Removes the last_updated timestamp column (same syntax as MySQL)

3. Modify rating Column Data Type

ALTER TABLE movie_ratings 
MODIFY (rating NUMBER(3,1));

Changes rating to allow values like 4.25 (Oracle uses MODIFY instead of ALTER COLUMN)

4. Rename a Column moviename

ALTER TABLE movie_ratings 
RENAME COLUMN moviename TO title;

Changes the column name from moviename to title (same syntax as MySQL)

5. Add a Constraint (Default Value) to rating column

ALTER TABLE movie_ratings 
MODIFY (rating DEFAULT 3.0);

Sets default rating to 3.0 for new records (Oracle uses MODIFY for defaults)

6. Add a Primary Key to sno

ALTER TABLE movie_ratings 
ADD CONSTRAINT pk_movie_ratings PRIMARY KEY (sno);

Explicitly defines sno as primary key with a constraint name

7. Add a Foreign Key (Requires Reference Table)

-- First create directors table if it doesn't exist
CREATE TABLE directors (
    id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name VARCHAR2(100) NOT NULL
);

-- Then add foreign key
ALTER TABLE movie_ratings 
ADD (director_id NUMBER);

ALTER TABLE movie_ratings
ADD CONSTRAINT fk_director 
FOREIGN KEY (director_id) REFERENCES directors(id);

Sets up relationship with a directors reference table (Oracle syntax)

8. Add an Index to actor column for Faster Queries

CREATE INDEX idx_actor ON movie_ratings(actor);

Improves performance for queries filtering by actor (Oracle uses CREATE INDEX)

9. Rename the Table

RENAME movie_ratings TO telugu_movie_ratings;

Changes the table name to be more specific (Oracle uses RENAME command)

10. Add Multiple Columns at Once

ALTER TABLE movie_ratings 
ADD (
    duration NUMBER COMMENT 'Runtime in minutes',
    language VARCHAR2(20) DEFAULT 'Telugu',
    awards_won NUMBER DEFAULT 0
);

Adds three new columns in a single statement (Oracle syntax)

11. Oracle-Specific: Add a Check Constraint

ALTER TABLE movie_ratings
ADD CONSTRAINT chk_rating 
CHECK (rating BETWEEN 0.5 AND 5.0);

Adds a named check constraint in Oracle

12. Oracle-Specific: Enable/Disable Constraints

-- Disable constraint
ALTER TABLE movie_ratings
DISABLE CONSTRAINT chk_rating;

-- Enable constraint
ALTER TABLE movie_ratings
ENABLE CONSTRAINT chk_rating;

Shows Oracle's ability to temporarily disable constraints

Key Oracle ALTER TABLE Differences

  • Oracle uses MODIFY instead of ALTER COLUMN for column changes
  • ADD clause is used for adding columns, not separated commands
  • Constraints are typically named explicitly in Oracle
  • Oracle has more comprehensive constraint management (enable/disable)
  • Data types differ (VARCHAR2 instead of VARCHAR, NUMBER instead of DECIMAL)

Oracle DELETE SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Delete Single Movie by Name

DELETE FROM movie_ratings 
WHERE moviename = 'Majili';

Removes the specific movie 'Majili' from the table (same syntax as MySQL)

2. Delete Movies by Release Year (Older Films)

DELETE FROM movie_ratings 
WHERE released_year < 2015;

Deletes all movies released before 2015 (same syntax as MySQL)

3. Delete Low-Rated Movies

DELETE FROM movie_ratings 
WHERE rating < 4.0;

Removes all movies with ratings below 4.0 stars (same syntax as MySQL)

4. Delete Using Multiple Conditions

DELETE FROM movie_ratings 
WHERE actor = 'Nani' AND rating < 4.3;

Deletes Nani's movies with ratings below 4.3 (same syntax as MySQL)

5. Oracle-Specific: Delete with ROWNUM (Top 3 Oldest)

DELETE FROM movie_ratings 
WHERE sno IN (
    SELECT sno FROM (
        SELECT sno FROM movie_ratings 
        ORDER BY released_year ASC
    ) WHERE ROWNUM <= 3
);

Oracle uses ROWNUM instead of LIMIT to remove the 3 oldest movies

6. Delete Using Subquery (Movies Without Awards)

-- Assuming we have an awards column
DELETE FROM movie_ratings 
WHERE moviename NOT IN (
    SELECT moviename FROM movie_ratings 
    WHERE awards_won > 0
);

Deletes movies that haven't won any awards (same syntax as MySQL)

7. Delete All Movies by a Director

DELETE FROM movie_ratings 
WHERE director = 'Sandeep Reddy Vanga';

Removes all movies directed by Sandeep Reddy Vanga (same syntax as MySQL)

8. Delete Using Pattern Matching (Temporary/Test Entries)

DELETE FROM movie_ratings 
WHERE moviename LIKE '%test%' OR moviename LIKE '%temp%';

Removes any test or temporary entries in the database (same syntax as MySQL)

9. Oracle-Specific: Delete Duplicate Movies (Keeping Highest Rated)

DELETE FROM movie_ratings
WHERE ROWID NOT IN (
    SELECT MIN(ROWID)
    FROM movie_ratings
    GROUP BY moviename, released_year
);

Oracle uses ROWID to identify and remove duplicate movie entries

10. Delete All Data (Truncate Alternative)

DELETE FROM movie_ratings;

Removes all data from the table while keeping the structure intact

Note: For large tables, TRUNCATE TABLE would be more efficient

Oracle String Function SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Display all movie names in uppercase letters

SELECT UPPER(moviename) AS uppercase_name 
FROM movie_ratings;

Converts all movie names to uppercase (same syntax as MySQL)

2. Extract the first 5 characters from all director names

SELECT SUBSTR(director, 1, 5) AS director_initials 
FROM movie_ratings;

Oracle uses SUBSTR instead of LEFT for substring operations

3. Concatenate movie name and year with format "MovieName (Year)"

SELECT moviename || ' (' || released_year || ')' AS movie_with_year 
FROM movie_ratings;

Oracle uses || for concatenation instead of CONCAT()

4. Find movies where review contains "epic" (case insensitive)

SELECT moviename, review 
FROM movie_ratings 
WHERE REGEXP_LIKE(review, 'epic', 'i');

Oracle uses REGEXP_LIKE for advanced pattern matching

5. Replace "story" with "tale" in review column

SELECT moviename, 
       REPLACE(review, 'story', 'tale') AS modified_review 
FROM movie_ratings 
WHERE INSTR(review, 'story') > 0;

Oracle uses INSTR instead of LIKE for position checking

6. Display length (in characters) of each movie name

SELECT moviename, LENGTH(moviename) AS name_length 
FROM movie_ratings 
ORDER BY name_length DESC;

Same syntax as MySQL for LENGTH function

7. Oracle-Specific: Pad movie names to 30 characters

SELECT RPAD(moviename, 30, '.') AS padded_name 
FROM movie_ratings;

Shows Oracle's string padding functions

8. Oracle-Specific: Extract text between parentheses

SELECT moviename,
       REGEXP_SUBSTR(moviename, '\(([^)]+)\)', 1, 1, NULL, 1) AS subtitle
FROM movie_ratings
WHERE moviename LIKE '%(%';

Demonstrates Oracle's advanced REGEXP_SUBSTR function

9. Oracle-Specific: Translate characters in movie names

SELECT moviename,
       TRANSLATE(moviename, 'aeiou', 'AEIOU') AS uppercase_vowels
FROM movie_ratings;

Shows Oracle's TRANSLATE function for character replacement

10. Oracle-Specific: Soundex matching for similar names

SELECT moviename 
FROM movie_ratings 
WHERE SOUNDEX(moviename) = SOUNDEX('Bahubali');

Demonstrates Oracle's SOUNDEX function for phonetic matching

Oracle Date Function SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Display years passed since each movie was released

SELECT moviename, released_year, 
       EXTRACT(YEAR FROM SYSDATE) - released_year AS years_since_release
FROM movie_ratings;

Oracle uses EXTRACT and SYSDATE for date operations

2. Oracle-Specific: Convert year to full date

SELECT moviename, 
       TO_DATE(released_year, 'YYYY') AS release_date
FROM movie_ratings;

Oracle's TO_DATE function converts strings to dates

3. Add 5 years to release year of all movies

SELECT moviename, released_year, 
       ADD_MONTHS(TO_DATE(released_year, 'YYYY'), 60) AS future_date
FROM movie_ratings;

Oracle uses ADD_MONTHS for date arithmetic

4. Oracle-Specific: Display movies released in last 5 years

SELECT moviename, released_year
FROM movie_ratings
WHERE TO_DATE(released_year, 'YYYY') >= ADD_MONTHS(SYSDATE, -60)
ORDER BY released_year DESC;

Oracle date comparison with SYSDATE

5. Oracle-Specific: Format date in different styles

SELECT moviename, 
       TO_CHAR(TO_DATE(released_year, 'YYYY'), 'DD-MON-YYYY') AS formatted_date
FROM movie_ratings;

Oracle's TO_CHAR for date formatting

6. Oracle-Specific: Find movies released in Q1

SELECT moviename, released_year
FROM movie_ratings
WHERE TO_CHAR(TO_DATE(released_year, 'YYYY'), 'Q') = '1';

Oracle quarter extraction using TO_CHAR

7. Oracle-Specific: Days between Baahubali 1 and 2 releases

SELECT 
    TO_DATE('2017', 'YYYY') - TO_DATE('2015', 'YYYY') AS days_between_baahubali
FROM dual;

Oracle date subtraction returns number of days

8. Oracle-Specific: Last day of release year

SELECT moviename,
       LAST_DAY(TO_DATE(released_year, 'YYYY')) AS year_end
FROM movie_ratings;

Oracle's LAST_DAY function

9. Oracle-Specific: Next Friday after release

SELECT moviename,
       NEXT_DAY(TO_DATE(released_year, 'YYYY'), 'FRIDAY') AS next_friday
FROM movie_ratings;

Oracle's NEXT_DAY function

10. Oracle-Specific: Months between current date and release

SELECT moviename,
       MONTHS_BETWEEN(SYSDATE, TO_DATE(released_year, 'YYYY')) AS months_since_release
FROM movie_ratings;

Oracle's MONTHS_BETWEEN function

Oracle Aggregate, Sort, and GROUP BY SQL Queries

Hover over each query to see the SQL statement and expected results.

1. Find the average rating of all movies

SELECT AVG(rating) AS average_rating
FROM movie_ratings;

Same syntax as MySQL for basic aggregation

2. Oracle-Specific: Analytic function for rankings

SELECT moviename, rating,
       RANK() OVER (ORDER BY rating DESC) AS rank,
       DENSE_RANK() OVER (ORDER BY rating DESC) AS dense_rank
FROM movie_ratings;

Oracle's advanced analytic functions

3. Count movies per director

SELECT director, COUNT(*) AS movie_count
FROM movie_ratings
GROUP BY director
ORDER BY movie_count DESC;

Same syntax as MySQL for GROUP BY

4. Oracle-Specific: ROLLUP for subtotals

SELECT director, actor, COUNT(*) AS movie_count
FROM movie_ratings
GROUP BY ROLLUP(director, actor);

Oracle's ROLLUP for hierarchical aggregates

5. Oracle-Specific: CUBE for all combinations

SELECT director, released_year, AVG(rating) AS avg_rating
FROM movie_ratings
GROUP BY CUBE(director, released_year);

Oracle's CUBE for multi-dimensional analysis

6. Oracle-Specific: GROUPING SETS

SELECT director, actor, COUNT(*) AS movie_count
FROM movie_ratings
GROUP BY GROUPING SETS((director), (actor), ());

Oracle's flexible GROUPING SETS

7. Oracle-Specific: LISTAGG for string aggregation

SELECT director, 
       LISTAGG(moviename, ', ') WITHIN GROUP (ORDER BY released_year) AS movies
FROM movie_ratings
GROUP BY director;

Oracle's LISTAGG instead of MySQL's GROUP_CONCAT

8. Oracle-Specific: PIVOT for cross-tabulation

SELECT *
FROM (
    SELECT director, rating
    FROM movie_ratings
)
PIVOT (
    COUNT(*)
    FOR rating IN (4.0 AS "4.0", 4.5 AS "4.5", 5.0 AS "5.0")
);

Oracle's PIVOT for cross-tab reports

9. Oracle-Specific: FIRST/LAST functions

SELECT 
    MIN(released_year) KEEP (DENSE_RANK FIRST ORDER BY rating) AS year_of_highest_rated,
    MAX(released_year) KEEP (DENSE_RANK LAST ORDER BY rating) AS year_of_lowest_rated
FROM movie_ratings;

Oracle's FIRST/LAST analytic functions

10. Oracle-Specific: NTILE for bucketing

SELECT moviename, rating,
       NTILE(4) OVER (ORDER BY rating DESC) AS quartile
FROM movie_ratings;

Oracle's NTILE for dividing data into buckets

Oracle Table Constraints

Hover over each query to see the SQL statement and expected results.

1. Complete Table Definition with Constraints

CREATE TABLE movie_ratings (
    sno NUMBER GENERATED ALWAYS AS IDENTITY,
    moviename VARCHAR2(100) NOT NULL,
    released_year NUMBER NOT NULL CHECK (released_year BETWEEN 1900 AND EXTRACT(YEAR FROM SYSDATE)),
    actor VARCHAR2(100) NOT NULL,
    director VARCHAR2(100) NOT NULL,
    rating NUMBER(2,1) NOT NULL CHECK (rating BETWEEN 0.5 AND 5.0),
    review CLOB,
    language VARCHAR2(20) DEFAULT 'Telugu',
    ott_platform VARCHAR2(30),
    last_updated TIMESTAMP DEFAULT SYSTIMESTAMP,
    CONSTRAINT pk_movie_ratings PRIMARY KEY (sno),
    CONSTRAINT unique_movie UNIQUE (moviename, released_year),
    CONSTRAINT chk_ott CHECK (ott_platform IN ('Netflix', 'Prime', 'Hotstar', 'Zee5', 'Aha', 'Disney+', NULL))
);

CREATE TABLE ott_platforms (
    platform_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    platform_name VARCHAR2(30) UNIQUE NOT NULL,
    subscription_cost NUMBER(5,2)
);

ALTER TABLE movie_ratings
ADD CONSTRAINT fk_ott_platform
FOREIGN KEY (ott_platform) REFERENCES ott_platforms(platform_name);

Oracle-specific table creation with constraints

2. Oracle-Specific: Disable/Enable Constraints

-- Disable constraint
ALTER TABLE movie_ratings DISABLE CONSTRAINT chk_ott;

-- Enable constraint
ALTER TABLE movie_ratings ENABLE CONSTRAINT chk_ott;

Oracle's constraint state management

3. Oracle-Specific: Deferrable Constraints

ALTER TABLE movie_ratings
MODIFY CONSTRAINT fk_ott_platform
DEFERRABLE INITIALLY DEFERRED;

Oracle's deferrable constraint option

4. Oracle-Specific: Validate/Novalidate

-- Add constraint without validating existing data
ALTER TABLE movie_ratings
ADD CONSTRAINT chk_rating_new CHECK (rating > 3.0) NOVALIDATE;

Oracle's NOVALIDATE option for constraints

5. Oracle-Specific: Constraint Information

-- View all constraints
SELECT constraint_name, constraint_type, status 
FROM user_constraints
WHERE table_name = 'MOVIE_RATINGS';

Querying Oracle's data dictionary for constraints

Oracle Views

Hover over each query to see the SQL statement and expected results.

1. Create a View for High-Rated Movies

CREATE OR REPLACE VIEW high_rated_movies AS
SELECT moviename, released_year, rating, director
FROM movie_ratings
WHERE rating >= 4.5
ORDER BY rating DESC;

Same syntax as MySQL for basic views

2. Oracle-Specific: Force View Creation

CREATE OR REPLACE FORCE VIEW movie_summary AS
SELECT * FROM non_existent_table;

Oracle's FORCE option to create view with errors

3. Oracle-Specific: Read Only View

CREATE OR REPLACE VIEW read_only_movies AS
SELECT * FROM movie_ratings
WITH READ ONLY;

Oracle's WITH READ ONLY clause

4. Oracle-Specific: Check Option View

CREATE OR REPLACE VIEW recent_movies AS
SELECT * FROM movie_ratings
WHERE released_year >= EXTRACT(YEAR FROM SYSDATE) - 3
WITH CHECK OPTION CONSTRAINT chk_recent_movies;

Oracle's WITH CHECK OPTION for updatable views

5. Oracle-Specific: View with BEQUEATH

CREATE OR REPLACE VIEW movie_info BEQUEATH DEFINER AS
SELECT * FROM movie_ratings;

Oracle's BEQUEATH clause for view privileges

6. Oracle-Specific: Materialized View

CREATE MATERIALIZED VIEW mv_movie_stats
REFRESH COMPLETE ON DEMAND
AS
SELECT director, COUNT(*) AS movie_count, AVG(rating) AS avg_rating
FROM movie_ratings
GROUP BY director;

Oracle's materialized views for pre-computed results

7. Oracle-Specific: View with Object Types

CREATE OR REPLACE TYPE movie_type AS OBJECT (
    name VARCHAR2(100),
    year NUMBER,
    rating NUMBER(2,1)
);

CREATE OR REPLACE VIEW object_movies OF movie_type
WITH OBJECT IDENTIFIER(name) AS
SELECT moviename, released_year, rating
FROM movie_ratings;

Oracle's object-oriented view capabilities

8. Oracle-Specific: XML View

CREATE OR REPLACE VIEW xml_movies AS
SELECT XMLELEMENT("movie",
    XMLATTRIBUTES(moviename AS "name", released_year AS "year"),
    XMLFOREST(rating AS "rating", director AS "director")
) AS movie_xml
FROM movie_ratings;

Oracle's XML generation capabilities in views

9. Oracle-Specific: View with Flashback

CREATE OR REPLACE VIEW historical_movies AS
SELECT * FROM movie_ratings
AS OF TIMESTAMP SYSTIMESTAMP - INTERVAL '1' HOUR;

Oracle's flashback query in views

10. Oracle-Specific: View with Virtual Columns

CREATE OR REPLACE VIEW movie_extras AS
SELECT m.*,
    CASE WHEN rating >= 4.5 THEN 'Excellent' ELSE 'Good' END AS rating_category,
    EXTRACT(YEAR FROM SYSDATE) - released_year AS years_old
FROM movie_ratings m;

Oracle's computed columns in views

Oracle Indexes

Hover over each query to see the SQL statement and expected results.

1. Create a Basic B-tree Index

CREATE INDEX idx_moviename ON movie_ratings(moviename);

Standard B-tree index in Oracle

2. Oracle-Specific: Bitmap Index

CREATE BITMAP INDEX idx_rating_bitmap ON movie_ratings(rating);

Oracle's bitmap index for low-cardinality columns

3. Oracle-Specific: Function-Based Index

CREATE INDEX idx_upper_moviename ON movie_ratings(UPPER(moviename));

Oracle's function-based indexes

4. Oracle-Specific: Reverse Key Index

CREATE INDEX idx_sno_reverse ON movie_ratings(sno) REVERSE;

Oracle's reverse key indexes for sequence-based columns

5. Oracle-Specific: Index-Organized Table

CREATE TABLE movie_ratings_iot (
    sno NUMBER PRIMARY KEY,
    moviename VARCHAR2(100),
    released_year NUMBER
) ORGANIZATION INDEX;

Oracle's index-organized tables

6. Oracle-Specific: Domain Index

CREATE INDEX idx_review_text ON movie_ratings(review)
INDEXTYPE IS CTXSYS.CONTEXT;

Oracle's text domain index for full-text search

7. Oracle-Specific: Invisible Index

CREATE INDEX idx_invisible ON movie_ratings(director) INVISIBLE;

Oracle's invisible indexes for testing

8. Oracle-Specific: Partitioned Index

CREATE INDEX idx_partitioned ON movie_ratings(released_year)
LOCAL (PARTITION p_2010, PARTITION p_2015, PARTITION p_2020);

Oracle's partitioned indexes

9. Oracle-Specific: Index Monitoring

-- Start monitoring
ALTER INDEX idx_moviename MONITORING USAGE;

-- Check usage
SELECT * FROM v$object_usage
WHERE index_name = 'IDX_MOVIENAME';

Oracle's index usage monitoring

10. Oracle-Specific: Index Compression

CREATE INDEX idx_compressed ON movie_ratings(moviename, director)
COMPRESS 1;

Oracle's index compression

Oracle Joins with Movie Ratings

Hover over each query to see the Oracle SQL statement and expected results.

Note: For join examples, we'll use an additional table called movie_awards:
CREATE TABLE movie_awards (
    award_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    moviename VARCHAR2(100) NOT NULL,
    award_name VARCHAR2(100) NOT NULL,
    award_year NUMBER NOT NULL,
    category VARCHAR2(50),
    CONSTRAINT fk_movie FOREIGN KEY (moviename) REFERENCES movie_ratings(moviename)
);

INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('Baahubali: The Beginning', 'National Film Award', 2016, 'Best Feature Film');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('Baahubali: The Beginning', 'Filmfare Award', 2016, 'Best Film');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('RRR', 'Oscar', 2023, 'Best Original Song');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('RRR', 'Golden Globe', 2023, 'Best Foreign Language Film');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('Pushpa: The Rise', 'Filmfare Award', 2022, 'Best Actor');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('Sita Ramam', 'National Film Award', 2023, 'Best Music Direction');
INSERT INTO movie_awards (moviename, award_name, award_year, category) VALUES
('Jersey', 'Filmfare Award', 2020, 'Best Actor');

1. Oracle INNER JOIN - Movies with Awards

SELECT r.moviename, r.director, a.award_name, a.award_year
FROM movie_ratings r
INNER JOIN movie_awards a ON r.moviename = a.moviename
ORDER BY a.award_year DESC;

Returns only movies that have won awards, with award details

2. Oracle LEFT OUTER JOIN - All Movies with Award Info

SELECT r.moviename, r.rating, a.award_name
FROM movie_ratings r
LEFT OUTER JOIN movie_awards a ON r.moviename = a.moviename
ORDER BY r.rating DESC;

Shows all movies, with award info if available (NULL for no awards)

3. Oracle RIGHT OUTER JOIN - All Awards with Movie Info

SELECT a.award_name, a.category, r.moviename, r.director
FROM movie_ratings r
RIGHT OUTER JOIN movie_awards a ON r.moviename = a.moviename
ORDER BY a.award_year;

Shows all awards, with movie details if available

4. Oracle FULL OUTER JOIN - All Movies and Awards

SELECT r.moviename, r.rating, a.award_name
FROM movie_ratings r
FULL OUTER JOIN movie_awards a ON r.moviename = a.moviename
ORDER BY r.moviename;

Combines all movies and all awards (shows movies without awards and awards without movies)

5. Oracle CROSS JOIN - All Possible Combinations

SELECT r.moviename, a.award_name
FROM movie_ratings r
CROSS JOIN movie_awards a
WHERE ROWNUM <= 10;  -- Limited for demonstration

Returns Cartesian product (every movie paired with every award)

6. Oracle SELF JOIN - Movies by Same Director

SELECT a.moviename AS movie1, b.moviename AS movie2, a.director
FROM movie_ratings a
JOIN movie_ratings b ON a.director = b.director AND a.moviename < b.moviename
ORDER BY a.director;

Finds pairs of movies made by the same director

7. Oracle NATURAL JOIN - Movies with Awards

SELECT moviename, rating, award_name
FROM movie_ratings
NATURAL JOIN movie_awards;

Automatically joins on columns with the same name (moviename)

8. Oracle JOIN with Multiple Conditions

SELECT r.moviename, r.released_year, a.award_name, a.award_year
FROM movie_ratings r
JOIN movie_awards a ON r.moviename = a.moviename 
    AND a.award_year > r.released_year
ORDER BY r.moviename;

Joins movies with awards won in years after release

9. Oracle JOIN with Aggregate Functions

SELECT r.director, COUNT(a.award_id) AS award_count, AVG(r.rating) AS avg_rating
FROM movie_ratings r
LEFT JOIN movie_awards a ON r.moviename = a.moviename
GROUP BY r.director
ORDER BY award_count DESC;

Shows directors with their movie counts and average ratings

10. Oracle JOIN with Subquery

SELECT r.moviename, r.rating, recent_awards.award_name
FROM movie_ratings r
JOIN (
    SELECT moviename, award_name 
    FROM movie_awards 
    WHERE award_year >= 2022
) recent_awards ON r.moviename = recent_awards.moviename
WHERE r.rating > 4.5;

Joins high-rated movies with awards from recent years

11. Oracle PARTITION OUTER JOIN

SELECT r.moviename, a.award_name
FROM movie_ratings r
LEFT OUTER JOIN movie_awards a PARTITION BY (a.moviename)
ON r.moviename = a.moviename
ORDER BY r.moviename;

Oracle-specific join that partitions the right table before joining

12. Oracle USING Clause for Joins

SELECT r.moviename, r.rating, a.award_name
FROM movie_ratings r
JOIN movie_awards a USING (moviename)
WHERE r.rating > 4.0;

Simplifies join syntax when column names are identical

Oracle Join Type Comparison

Join Type Oracle Syntax When to Use
INNER JOIN INNER JOIN or just JOIN When you only want records with matches in both tables
LEFT OUTER JOIN LEFT OUTER JOIN or LEFT JOIN When you want all main records plus optional related data
RIGHT OUTER JOIN RIGHT OUTER JOIN or RIGHT JOIN When you want all secondary records with matching primary data
FULL OUTER JOIN FULL OUTER JOIN When you want all records from both tables combined
CROSS JOIN CROSS JOIN When you need all possible combinations
NATURAL JOIN NATURAL JOIN When tables have columns with identical names to join on
PARTITION OUTER JOIN PARTITION BY with LEFT JOIN Oracle-specific join for partitioned data

Oracle PL/SQL Examples

Hover over each example to see PL/SQL code snippets.

1. Basic PL/SQL Block

DECLARE
    v_movie_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_movie_count 
    FROM movie_ratings 
    WHERE rating > 4.0;
    
    DBMS_OUTPUT.PUT_LINE('High-rated movies: ' || v_movie_count);
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

Simple PL/SQL block to count high-rated movies

2. PL/SQL Stored Procedure

CREATE OR REPLACE PROCEDURE update_movie_rating(
    p_moviename IN VARCHAR2,
    p_new_rating IN NUMBER
) AS
    v_old_rating NUMBER;
BEGIN
    -- Get current rating
    SELECT rating INTO v_old_rating
    FROM movie_ratings
    WHERE moviename = p_moviename;
    
    -- Update rating
    UPDATE movie_ratings
    SET rating = p_new_rating
    WHERE moviename = p_moviename;
    
    COMMIT;
    
    DBMS_OUTPUT.PUT_LINE('Updated ' || p_moviename || 
        ' from ' || v_old_rating || ' to ' || p_new_rating);
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        DBMS_OUTPUT.PUT_LINE('Movie not found');
    WHEN OTHERS THEN
        ROLLBACK;
        DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

-- Execute procedure
EXEC update_movie_rating('RRR', 4.9);

Stored procedure to update movie ratings with error handling

3. PL/SQL Function

CREATE OR REPLACE FUNCTION get_avg_rating(
    p_director IN VARCHAR2
) RETURN NUMBER AS
    v_avg_rating NUMBER;
BEGIN
    SELECT AVG(rating) INTO v_avg_rating
    FROM movie_ratings
    WHERE director = p_director;
    
    RETURN NVL(v_avg_rating, 0);
EXCEPTION
    WHEN OTHERS THEN
        RETURN -1; -- Error indicator
END;
/

-- Use the function
SELECT director, get_avg_rating(director) AS avg_rating
FROM movie_ratings
GROUP BY director;

Function to calculate average rating for a director

4. PL/SQL Cursor

DECLARE
    CURSOR c_movies IS
        SELECT moviename, rating 
        FROM movie_ratings
        WHERE rating > 4.5
        ORDER BY rating DESC;
        
    r_movie c_movies%ROWTYPE;
BEGIN
    OPEN c_movies;
    LOOP
        FETCH c_movies INTO r_movie;
        EXIT WHEN c_movies%NOTFOUND;
        
        DBMS_OUTPUT.PUT_LINE(r_movie.moviename || ': ' || r_movie.rating);
    END LOOP;
    CLOSE c_movies;
END;
/

Explicit cursor to process high-rated movies

5. PL/SQL Trigger

CREATE OR REPLACE TRIGGER trg_movie_audit
BEFORE INSERT OR UPDATE OR DELETE ON movie_ratings
FOR EACH ROW
DECLARE
    v_action VARCHAR2(10);
BEGIN
    IF INSERTING THEN
        v_action := 'INSERT';
    ELSIF UPDATING THEN
        v_action := 'UPDATE';
    ELSE
        v_action := 'DELETE';
    END IF;
    
    INSERT INTO movie_audit_log (
        log_id,
        moviename,
        action,
        change_date,
        old_rating,
        new_rating
    ) VALUES (
        audit_seq.NEXTVAL,
        :NEW.moviename,
        v_action,
        SYSDATE,
        :OLD.rating,
        :NEW.rating
    );
END;
/

Trigger to audit changes to movie ratings

Oracle Advanced Features

Key Oracle-specific capabilities:

  • Analytic Functions: RANK(), DENSE_RANK(), LEAD(), LAG()
  • Materialized Views: Pre-computed query results
  • Partitioning: Divide tables for better performance
  • Advanced Queuing: Message queue functionality
  • Flashback Query: Query historical data

Oracle Performance Tuning

Hover over each query to see Oracle-specific optimization techniques.

1. Explain Plan Analysis

EXPLAIN PLAN FOR
SELECT r.moviename, a.award_name
FROM movie_ratings r
JOIN movie_awards a ON r.moviename = a.moviename
WHERE r.rating > 4.0;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

Generates and displays execution plan for query optimization

2. Index Creation

CREATE INDEX idx_movie_rating ON movie_ratings(rating);

-- Function-based index
CREATE INDEX idx_movie_upper ON movie_ratings(UPPER(moviename));

-- Bitmap index for low-cardinality columns
CREATE BITMAP INDEX idx_movie_language ON movie_ratings(language);

Different index types for various query patterns

3. Optimizer Hints

SELECT /*+ INDEX(r idx_movie_rating) */ r.moviename, r.rating
FROM movie_ratings r
WHERE r.rating > 4.0;

SELECT /*+ FIRST_ROWS(10) */ moviename, rating
FROM movie_ratings
ORDER BY rating DESC;

Directing the optimizer with specific execution hints

4. Partitioning Example

-- Range partitioning by release year
CREATE TABLE movie_ratings_part (
    sno NUMBER PRIMARY KEY,
    moviename VARCHAR2(100),
    released_year NUMBER,
    rating NUMBER(3,1)
PARTITION BY RANGE (released_year) (
    PARTITION movies_pre2000 VALUES LESS THAN (2000),
    PARTITION movies_2000s VALUES LESS THAN (2010),
    PARTITION movies_2010s VALUES LESS THAN (2020),
    PARTITION movies_current VALUES LESS THAN (MAXVALUE)
);

Improving performance for large tables with partitioning

5. Materialized View

CREATE MATERIALIZED VIEW mv_movie_stats
REFRESH COMPLETE ON DEMAND
ENABLE QUERY REWRITE
AS
SELECT 
    director,
    COUNT(*) AS movie_count,
    AVG(rating) AS avg_rating,
    MIN(released_year) AS earliest_year,
    MAX(released_year) AS latest_year
FROM movie_ratings
GROUP BY director;

Pre-aggregated data for faster reporting queries

Oracle vs. MySQL Key Differences

Feature Oracle MySQL
String Concatenation || operator CONCAT() function or || (with setting)
Pagination ROWNUM or FETCH FIRST LIMIT clause
Auto-increment Sequences + Triggers or Identity columns AUTO_INCREMENT attribute
Date Format TO_DATE(), TO_CHAR() DATE_FORMAT(), STR_TO_DATE()
Full Outer Join Native FULL OUTER JOIN Emulated with UNION of left/right joins
Stored Procedures PL/SQL with rich features Limited procedural language
Analytic Functions Extensive support Limited in older versions

More Oracle Resources

Oracle PL/SQL MCQs

Test your PL/SQL knowledge with practice questions

Practice MCQs
Oracle Performance Tuning

Advanced optimization techniques

View Tips
Oracle Certification

Prepare for Oracle certification exams

Learn More
About NikhilLearnHub

Your one-stop destination for learning resources on technology, programming, databases, and more.

© 2023 NikhilLearnHub. All rights reserved.