SQL 3: CURD

5 min readCURD Operation

Select Statement

โœ… 1. Selecting All Columns

SELECT * FROM actor
๐ŸŸฆ Explanation: The * wildcard selects all columns from the actors table. ๐Ÿ”Ž Useful when you need the entire row for each record.

โœ… 2. Selecting Specific Columns

SELECT first_name, last_name FROM actor LIMIT 1
๐ŸŸฆ Explanation: Fetches only the first_name and last_name columns from the table. ๐Ÿ”Ž More efficient and readable when you don’t need all columns.

โœ… 3. Using Literal Values

SELECT 'Hello World'
๐ŸŸฆ Explanation: Returns the literal string 'Hello World!' as a result. ๐Ÿ”Ž Often used to test queries or return hardcoded values. Similar to console.log

โœ… 4. Aliasing Columns

SELECT first_name AS FName, last_name AS LName FROM actor LIMIT 1;
๐ŸŸฆ Explanation: Renames output columns using the AS keyword. ๐Ÿ”Ž Useful for shorter names, custom formatting, or frontend display.

๐Ÿ”„ Optional: Combine Concepts

SELECT 
	first_name AS FName,
    last_name AS LName,
    'Actor' AS Role
FROM actor LIMIT 2
๐ŸŸฆ Explanation:
  • Aliases with spaces using quotes
  • Adds a literal value ('Actor') to every row

DISTINCT Keyword

โœ… 1. DISTINCT on One Column

SELECT DISTINCT customer_name FROM purchases;
๐ŸŸฐ Shows each unique customer.

โœ… 2. DISTINCT on Two Columns (Pair)

SELECT DISTINCT customer_name, product_name FROM purchases
๐ŸŸฐ Shows each unique (customer, product) combination. Combination should be unique

โœ… 3. DISTINCT with All Columns

SELECT DISTINCT * FROM purchases

๐Ÿงจ Why You See “Duplicates” Even With DISTINCT *

  • Every row has a unique id.
  • Even if other fields are the same, the id column makes each row distinct.
DISTINCT * means “distinct across all columns” โ€” and since id is always different, every row is distinct.

โœ… 4. DISTINCT with ORDER BY

SELECT DISTINCT product_name FROM purchases ORDER BY product_name ASC;
๐ŸŸฐ Lists distinct products in alphabetical order.

โœ… 5. DISTINCT Inside Aggregates

You can use it inside aggregate functions:
SELECT COUNT(DISTINCT product_name) AS unique_product FROM purchases;
๐ŸŸฐ Counts how many different products were purchased.

โœ… 6. DISTINCT ON (…) (PostgreSQL only)

To get the first product per customer:
SELECT DISTINCT ON (customer_name) customer_name, product_name, amount
FROM purchases
ORDER BY customer_name, amount DESC;
๐ŸŸฐ Returns one row per customer, choosing the product with the highest amount. ๐Ÿ”ธ Not supported in MySQL or SQLite directly.

Where Clause

The WHERE clause is used to filter rows returned by a SELECT, UPDATE, or DELETE query based on specific conditions

โœ… 1. Basic Usage

SELECT * FROM film WHERE rating = 'PG-13'
๐Ÿ”น Explanation: Filters the films table to return only rows where the rating is 'PG-13'.

โœ… 2. Using AND, OR, and NOT

SELECT * FROM film WHERE rating = 'PG-13' AND release_year = 2007 LIMIT 2
๐Ÿ”น Returns films that are both 'PG-13' and released in 2012.
SELECT * FROM film WHERE rating = 'PG-13' OR rating = 'G' LIMIT 2
๐Ÿ”น Returns films that are either 'PG-13' or 'G'.
SELECT * FROM film WHERE NOT rating = 'G' LIMIT 2
๐Ÿ”น Returns films that are not rated 'R'.

โœ… 3. Comparison Operators

SELECT * FROM film WHERE length > 50 AND length < 80 LIMIT 2
๐Ÿ”น Use =, != or <>, <, >, <=, >= for comparing values.

โœ… 4. Range Filtering with BETWEEN

SELECT * FROM film WHERE release_year BETWEEN 2006 AND 2007 LIMIT 2
๐Ÿ”น Returns films released between 2010 and 2020 (inclusive).

โœ… 5. Set Filtering with IN

SELECT * FROM film WHERE rating IN ('G', 'PG', 'PG-13') LIMIT 2
๐Ÿ”น Filters rows where rating matches any value in the list.
SELECT * FROM film WHERE rating NOT IN('G', 'PG-13', 'PG') LIMIT 2
๐Ÿ”น Excludes rows matching values in the list.

โœ… 6. Pattern Matching with LIKE

SELECT * FROM actor WHERE last_name LIKE 's%' LIMIT 2
๐Ÿ”น Finds actors whose last names start with 'S' or 's' case insensitive.
SELECT * FROM actor WHERE first_name LIKE '%an%' LIMIT 2
๐Ÿ”น Finds names containing 'an'.
SymbolMeaning
%Zero or more characters
_Exactly one character

โœ… 7. IS NULL and IS NOT NULL

SELECT * FROM customer WHERE email IS NULL LIMIT 1
๐Ÿ”น Returns customers without email addresses.
SELECT * FROM customer WHERE email IS NOT NULL LIMIT 1
๐Ÿ”น Returns customers with phone numbers.

โœ… 8. Subqueries in WHERE

SELECT * FROM film_actor WHERE actor_id IN (SELECT actor_id FROM actor) LIMIT 2
๐Ÿ”น Filters orders based on nested query from another table.

โœ… 9. Arithmetic in WHERE

SELECT * FROM product WHERE price*quantity > 13000
๐Ÿ”น Filters based on a calculated expression.

๐Ÿ“Œ Bonus: WHERE with UPDATE and DELETE

UPDATE users SET is_active = 0 WHERE last_login < '2023-01-01';
DELETE FROM sessions WHERE is_expired = true;

๐Ÿ“˜ SQL Comparison Operators Reference

Comparison operators are used in the WHERE, HAVING, ON, and CASE clauses to compare values and filter rows.
OperatorDescriptionExampleResult
=Equal toprice = 100Matches rows where price is exactly 100
!=Not equal to (ANSI SQL)status != ‘inactive’Matches rows where status is not ‘inactive’
<>Not equal to (standard)rating <> ‘R’Matches rows where rating is not ‘R’
<Less thanquantity < 50Matches rows where quantity is less than 50
>Greater thanprice > 500Matches rows where price is more than 500
<=Less than or equal toage <= 18Matches rows where age is 18 or younger
>=Greater than or equal toscore >= 90Matches rows where score is 90 or higher
IS NULLIs null valueemail IS NULLMatches rows where email is missing or undefined
IS NOT NULLIs not null valueemail IS NOT NULLMatches rows with a defined email
BETWEENWithin a rangeprice BETWEEN 100 AND 200Matches prices including 100 and 200
IN (…)Matches any in liststatus IN (‘new’, ‘open’)Matches rows where status is either ‘new’ or ‘open’
NOT IN (…)Not in listid NOT IN (1, 2, 3)Excludes rows with those id values
LIKEPattern match (text)name LIKE ‘A%’Matches names starting with “A”
NOT LIKENot matching patternemail NOT LIKE ‘%.edu’Excludes emails ending with .edu

๐Ÿ” Usage in WHERE Clause

SELECT * FROM employees WHERE salary > 60000;
SELECT * FROM customers WHERE status IN ('active', 'pending');
SELECT * FROM products WHERE name LIKE '%Phone%';

๐Ÿง  Notes:

  • Use != or <> for not equal to โ€” both work in most SQL dialects.
SELECT * FROM film WHERE rating != 'PG-13' LIMIT 1
SELECT * FROM film WHERE rating <> 'PG-13' LIMIT 1
SELECT * FROM film WHERE NOT rating = 'PG-13' LIMIT 1
  • IS NULL and IS NOT NULL are special comparisons for NULL values โ€” do not use = NULL.
  • LIKE supports % (wildcard for any number of characters) and _ (one character).
Would you like this in Markdown or a cheat sheet format (PDF or printable)? Ask ChatGPT

Scalar Function

CategoryDescriptionExample Functions
String FunctionsOperate on string valuesLENGTH(), LOWER(), UPPER(), SUBSTRING(), CONCAT(), TRIM(), REPLACE()
Numeric FunctionsPerform operations on numbersMOD(), ROUND(), CEIL(), FLOOR(), ABS(), POWER(), SQRT()
Date/Time FunctionsOperate on date and time valuesNOW(), DATE_ADD(), DATEDIFF(), CURDATE(), YEAR(), MONTH(), DAY()
Conversion FunctionsConvert data from one type to anotherCAST(), CONVERT(), TO_CHAR(), TO_DATE()
MiscellaneousOther utility functionsCOALESCE(), IFNULL(), NULLIF(), ISNULL(), GREATEST(), LEAST()

ORDER BY Clause

The ORDER BY clause is used to sort the result set of a query by one or more columns, either in ascending (ASC) or descending (DESC) order.

โœ… Syntax:

SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
  • ASC = Ascending (default)
  • DESC = Descending

๐Ÿ”น 1. Sort by a Single Column

SELECT * FROM film
ORDER BY rental_duration DESC;
๐ŸŸฆ Explanation: Sorts the films in descending order of rental duration โ€” longest rentals first.

๐Ÿ”น 2. Sort by Multiple Columns

SELECT * FROM film
ORDER BY title, release_year;
๐ŸŸฆ Explanation: First sorts by title (ascending by default), and then for films with the same title, sorts by release_year.

๐Ÿ”น 3. Explicit Order for Each Column

SELECT * FROM film
ORDER BY rating DESC, release_year ASC;
๐ŸŸฆ Explanation: Sorts by rating from high to low, and then by release_year from old to new within the same rating group.

๐Ÿ”น 4. Sort by Column Index (Not Recommended)

SELECT * FROM film ORDER BY 2 ASC LIMIT 10;
๐ŸŸฆ Explanation: Sorts by the second selected column (rental_duration) in descending order. โš ๏ธ Not recommended โ€” column names are safer and clearer.

๐Ÿ”น 5. Combine with LIMIT for Top/Bottom Results

SELECT title, rental_rate FROM film
ORDER BY rental_rate DESC
LIMIT 5;
๐ŸŸฆ Explanation: Returns the top 5 highest rental rate films.

UPDATE, DELETE, TRUNCATE, and DROP Explained

  1. UPDATE Command: Used to modify existing records. UPDATE table_name SET column_name = value WHERE condition;
  2. DELETE Command: Removes rows from a table. DELETE FROM table_name WHERE condition;
  3. DROP Command: Removes the entire table from the database. DROP TABLE table_name;
  4. TRUNCATE Command: Removes all data from a table but retains the table structure. TRUNCATE TABLE table_name;
  • Safe Mode: In MySQL, “safe mode” enforces the use of a WHERE clause for UPDATE and DELETE statements .
โšก Open This Article in DevScribe

Want to save this?
Open in DevScribe

Save this article directly to DevScribe and work on it offline. Edit, annotate, run code examples, and keep all your developer notes in one place.

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the Conversation

Stay Updated with Us

At Devscribe, we promote a lively space for developers to share insights and experiences. Our blog is not just a source of useful articles, but a gathering place where you can connect with like-minded individuals. Join us as we explore trending topics and collaborate on solutions.
Ready to make your voice heard?

By clicking Join Now, you agree to our Terms and Conditions.