Docsity

SQL Complete Notes with MySQL Labs — Functions, Joins, Subqueries (BCA/B.Tech), Study Guides, Projects, Research of Database Management Systems (DBMS)

Partial preview of the text

Download SQL Complete Notes with MySQL Labs — Functions, Joins, Subqueries (BCA/B.Tech) and more Study Guides, Projects, Research Database Management Systems (DBMS) in PDF only on Docsity!

DBMS UNIT 2

DBMS MASTERY

SQL Complete Guide with MySQL Labs

SQL Fundamentals · Functions · Joins · Subqueries · MySQL Labs

For BCA · B.Tech CSE/IT · B.Sc CS · MCA Indian University Syllabus Aligned · Exam-Ready Notes MySQL Practical Examples · Diagrams · Question Bank Edition 2026

About These Notes

Complete SQL guide for BCA, B.Tech, and MCA students. Learn SELECT, INSERT, UPDATE, DELETE, joins, subqueries, aggregate functions with 50+ MySQL examples and a practical lab.

Topics covered

 (^) SQL sub-languages — DDL, DML, DQL, DCL, TCL  CREATE, ALTER, DROP, TRUNCATE  INSERT, SELECT, UPDATE, DELETE  WHERE, DISTINCT, ORDER BY, LIMIT  String, numeric, and date functions  COUNT, SUM, AVG, MIN, MAX  GROUP BY and HAVING  INNER, LEFT, RIGHT, FULL, CROSS, SELF joins  Subqueries — IN, ANY, ALL, EXISTS, correlated

Who these notes are for

 BCA students preparing for semester exams.  B.Tech CSE and IT students in the DBMS course.  B.Sc Computer Science students.  MCA students revising for exams or interviews.  Freshers preparing for SQL rounds in placement interviews.

How to use these notes

  1. Read every chapter opener story first — it sets the concept in a real college context.
  2. Study the KEY IDEA boxes twice — these are your one-line viva answers.
  3. Type every SQL query in MySQL Workbench. Do not just read them.
  4. Finish the Practice Assignment at the end of each chapter.

Chapter 5 — SQL

Fundamentals

P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

THE DAY SQL FINALLY MADE SENSE

Sneha was in her second year. She had passed the theory paper on databases. She could write the definition of a primary key. She could draw an ER diagram in her sleep. But the day she opened MySQL Workbench and saw a blinking cursor, her mind went blank. She typed SELECT and waited. Nothing happened. Her senior looked over her shoulder and laughed. "You are treating this like Java. It is not Java. It is a sentence. A very small sentence. Verb. What. From where. Where." He typed: SELECT name FROM students WHERE marks > 80; He said it aloud like a sentence. "Select name, from students, where marks are greater than 80." That was the moment SQL finally made sense. Not a syntax. A sentence.

K E Y I D E A SQL is closer to English than any other language you will ever use. Read your query out loud. If it makes sense in English, it will run. ◆ This chapter turns you from a person who knows about SQL into a person who writes SQL. Every example runs on MySQL. Copy them, run them, and change them. That is the only way SQL sticks. ◆ ◆ ◆

“The best way to learn SQL is to break a table and fix it. Twice.”

CHAPTER LEARNING OBJECTIVES P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 By the end of this chapter, you should be able to:  Explain what SQL is and list its main features.  Identify SQL sub-languages — DDL, DML, DQL, DCL, and TCL.  Use common SQL data types.  Create, alter, drop, and truncate tables.  Insert, select, update, and delete rows.  Filter, sort, and limit results.  Use arithmetic, comparison, and logical operators.  Use BETWEEN, IN, LIKE, IS NULL, and DISTINCT.  Add comments to SQL scripts.

T R Y T H I S Memorize the five categories and two commands from each. Small effort. Big returns in every SQL question. 5.3 SQL DATA TYPES P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 Every column has a data type. Data types tell the database what kind of value to expect and how much space to reserve.

5.3.1 NUMERIC TYPES

Type Use for INT (^) Whole numbers (marks, IDs). BIGINT (^) Very large integers. DECIMAL(p,s) (^) Exact numbers with fixed decimals (fees, salaries). FLOAT, DOUBLE Approximate numbers (scientific values).

5.3.2 STRING TYPES

Type Use for CHAR(n) (^) Fixed-length strings (postal codes). VARCHAR(n) (^) Variable-length strings (names, emails). TEXT (^) Long free text (bios, descriptions).

5.3.3 DATE AND TIME

Type Use for DATE (^) Date only (2026-09-13). TIME (^) Time only (14:35:00). DATETIME (^) Date + time. TIMESTAMP (^) Automatically tracks the current time.

5.3.4 OTHER TYPES

Type Use for BOOLEAN (or TINYINT(1) in MySQL) True or false. BLOB (^) Binary data like images.

K E Y I D E A Choose the smallest type that can hold your data. Wrong type today, slow database tomorrow. 5.4 CREATING AND SELECTING A DATABASE P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 -- Create a new database CREATE DATABASE college_db; -- Switch to it USE college_db; Line-by-line:  CREATE DATABASE college_db; — makes a new empty database called college_db.  USE college_db; — tells MySQL to run all following commands inside this database. 5.5 CREATING TABLES (DDL) P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 CREATE TABLE students ( student_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, department VARCHAR(50), marks INT, admitted_on DATE ); Line-by-line:  CREATE TABLE students ( — start defining a table called students.  student_id INT PRIMARY KEY — an integer that uniquely identifies each row.

K E Y I D E A ALTER TABLE on a live production database can lock the table for minutes. Practice on test data first. Always. 5.7 DROP AND TRUNCATE P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

DROP TABLE

DROP TABLE students; Removes the table completely — structure and data.

TRUNCATE TABLE

TRUNCATE TABLE students; Removes all rows but keeps the table structure. Faster than DELETE for wiping a table.

QUICK COMPARISON

Feature DROP TRUNCATE DELETE Removes rows Yes Yes Yes Removes structure Yes No No Can use WHERE No No Yes Speed Fast Very fast Slowest Logged for each row No No Yes K E Y I D E A DROP removes the whole table. TRUNCATE empties the table. DELETE removes chosen rows. Pick the right one for the job. 5.8 INSERT (DML) P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

INSERT ONE ROW

INSERT INTO students (student_id, name, department, marks, admitted_on) VALUES (101, 'Amit', 'CSE', 85, '2024-07-15');

INSERT MANY ROWS

INSERT INTO students (student_id, name, department, marks, admitted_on) VALUES (102, 'Neha', 'IT', 92, '2024-07-15'), (103, 'Ravi', 'CSE', 78, '2024-07-16'), (104, 'Priya', 'ECE', 88, '2024-07-16'); Line-by-line:  INSERT INTO students (...) — the columns you are filling.  VALUES (...) — the values, in the same order.  Rows are separated by commas. T R Y T H I S Insert your own name and details as student_id = 999. Every command in this chapter should be one you have actually run once. 5.9 SELECT (DQL) P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 SELECT is the star of SQL.

SELECT EVERYTHING

SELECT * FROM students;

SELECT SOME COLUMNS

SELECT name, marks FROM students;

THE UPDATE-WITHOUT-WHERE MISTAKE

-- DO NOT run this on real data UPDATE students SET marks = 0; Without WHERE, this sets every row's marks to 0. This mistake has ended more than one internship. K E Y I D E A Every UPDATE and DELETE deserves a moment of silence before you press Enter. And a WHERE clause. Always a WHERE clause. 5.11 DELETE (DML) P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 DELETE FROM students WHERE student_id = 103; Deletes the row where student_id = 103.

DELETE ALL ROWS (RARE)

DELETE FROM students; This deletes every row but keeps the table. Use TRUNCATE if you want the same effect faster. 5.12 WHERE, DISTINCT, ORDER BY, LIMIT, ALIASES P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

WHERE

Filters rows. SELECT * FROM students WHERE department = 'CSE';

DISTINCT

Removes duplicate rows in the result. SELECT DISTINCT department FROM students;

ORDER BY

Sorts the result. SELECT name, marks FROM students ORDER BY marks DESC, name ASC; DESC = descending. ASC = ascending (default).

LIMIT

Restricts the number of rows returned. SELECT * FROM students ORDER BY marks DESC LIMIT 5;

ALIASES

Give a column or table a temporary name. SELECT name AS student_name, marks AS total_marks FROM students AS s WHERE s.marks > 80; Line-by-line:  AS student_name — the output column is labelled student_name.  AS s — inside the query, students can be called s. T R Y T H I S Combine three of these in one query — a WHERE, an ORDER BY, and a LIMIT. That is 80 percent of the SELECT you will ever write.

5.14 BETWEEN, IN, LIKE, IS NULL P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

BETWEEN

Range check (inclusive). SELECT name FROM students WHERE marks BETWEEN 70 AND 90;

IN

Matches any of a list. SELECT name FROM students WHERE department IN ('CSE', 'IT', 'ECE');

LIKE

Pattern matching.  % — any sequence of characters.  _ — exactly one character. -- Names starting with 'A' SELECT name FROM students WHERE name LIKE 'A%'; -- Names ending in 'a' SELECT name FROM students WHERE name LIKE '%a'; -- Names of exactly 4 characters SELECT name FROM students WHERE name LIKE '____';

IS NULL

Check for missing values. SELECT name FROM students WHERE department IS NULL; K E Y I D E A = NULL never works in SQL. Use IS NULL. This one rule saves you two marks in every SQL paper.

5.15 SQL COMMENTS P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 -- This is a single-line comment SELECT * FROM students; /* This is a multi-line comment */ Use comments to explain why you wrote a tricky query. Your future self and your teammates will thank you. 5.16 COMPLETE PRACTICAL MYSQL LAB P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 Do this end-to-end. Every line.

STEP 1 — CREATE THE DATABASE

CREATE DATABASE college_db; USE college_db;

STEP 2 — CREATE THE TABLE

CREATE TABLE students ( student_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, department VARCHAR(50), marks INT, admitted_on DATE );

5.17 COMMON SQL ERRORS P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5 Error Meaning Fix Table 'students' doesn't exist You did not create the table (or used the wrong database). Check USE college_db; Unknown column 'marx' in 'field list' Typo in a column name. Fix the spelling. Duplicate entry '101' for key 'PRIMARY' Inserting a duplicate primary key. Use a new key. Cannot add or update a child row: foreign key constraint fails Referring to a non-existent parent row. Insert parent first. You have an error in your SQL syntax Missing comma, quote, or semicolon. Read the query slowly, line by line. K E Y I D E A Every SQL error message is one line long and tells you exactly what to fix. Read it. Do not panic. 5.18 COMMON MISTAKES P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5  Mistake 1 — Running UPDATE or DELETE without WHERE.  Mistake 2 — Using = NULL instead of IS NULL.  Mistake 3 — Confusing single quotes and double quotes. In MySQL, string literals use single quotes.  Mistake 4 — Forgetting USE database_name; and running commands on the wrong database.  Mistake 5 — Using SELECT * in production code. Always list columns you actually need. 5.19 EXAM QUESTIONS P A R T I I I · S Q L I N A C T I O N · C H A P T E R 5

SHORT-ANSWER QUESTIONS

Q1. What is SQL? SQL is Structured Query Language, the standard language used to define, manipulate, and query data in relational databases. Q2. Name the five sub-languages of SQL. DDL, DML, DQL, DCL, TCL. Q3. Difference between DELETE and TRUNCATE. DELETE removes selected rows and can be filtered with WHERE. TRUNCATE removes all rows quickly and cannot be filtered. DELETE is logged per row; TRUNCATE is not. Q4. What does DISTINCT do? It removes duplicate rows from the result set. Q5. What is the use of LIMIT? It restricts the number of rows returned by a query.

LONG-ANSWER QUESTIONS

Q6. Explain any five common data types in SQL with examples. INT for whole numbers such as roll numbers, VARCHAR(n) for names and short text, DATE for admission or birth dates, DECIMAL(p,s) for exact money values like fees, and BOOLEAN for flags such as active or inactive. Q7. Explain the use of WHERE, ORDER BY, and LIMIT with one example. WHERE filters rows based on a condition. ORDER BY sorts the filtered rows. LIMIT restricts how many are returned. Example — top three CSE students by marks: SELECT name, marks FROM students WHERE department = 'CSE' ORDER BY marks DESC LIMIT 3; Q8. Write SQL to:  Add a phone column.  Update Amit's marks to 90.  (^) Delete students with marks below 50.  List names of students whose name starts with 'R'.