0% found this document useful (0 votes)
3 views

SQL examples

Uploaded by

jixefej261
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)
3 views

SQL examples

Uploaded by

jixefej261
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
You are on page 1/ 8

Dr.

Shweta

SQL
(Structured Query Language)

SQL (Structured Query Language) is the standard language used to communicate with
databases. It allows users to retrieve, insert, update, and delete data stored in a relational
database.

Relational Database Concept

A relational database organizes data into tables (rows and columns), where each row
represents a record and each column represents a field. Tables are related to each other by
unique identifiers, often called primary keys.

Data Types in SQL


Before creating a table, understanding data types is essential because each field must be
assigned a specific data type.

Common Data Types in SQL

1. INT: Used for storing integer values (e.g., 10, 200).


2. VARCHAR(n): Stores variable-length strings, where ‘n’ is the maximum length (e.g.,
names, emails).
3. CHAR(n): Stores fixed-length strings.
4. FLOAT: Used for decimal numbers (e.g., 10.5, 200.75).
5. DATE: Used to store dates in the format YYYY-MM-DD.
6. BOOLEAN: Stores TRUE or FALSE values.

Creating Tables
Syntax for Creating a Table
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);

Example
CREATE TABLE Students (

0
Dr. Shweta

StudentID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
BirthDate DATE
);

Inserting Data into Tables


INSERT INTO Students (StudentID, FirstName, LastName, BirthDate)
VALUES (1, 'Seema', 'chhikara', '2000-05-10');

Inserting Multiple Rows


INSERT INTO Students (StudentID, FirstName, LastName, BirthDate)
VALUES
(2, 'Happy', 'chhikara', '1999-07-20'),
(3, 'Parikshit', 'chhikara', '2001-01-15');

Checking structure of table:


Describe students;
Desc students;

Retrieving Data with SELECT

SELECT * FROM Students;


This query retrieves all columns from the Students table.

SELECT FirstName, LastName FROM Students;


Retrieving Specific Columns

Filtering Data with WHERE Clause

SELECT * FROM Students


WHERE BirthDate > '2000-01-01';

1
Dr. Shweta

SELECT * FROM Students


WHERE FirstName = 'happy' AND LastName = 'chhikara';

Updating Data in Tables


To modify existing data, the UPDATE statement is used.

UPDATE Students
SET LastName = 'Sheoran'
WHERE StudentID = 3;

Deleting Data

DELETE FROM Students


WHERE StudentID = 3;

Deleting All Rows


DELETE FROM Students;

Now check
select * from students;

Using Aggregate Functions


SQL provides several aggregate functions to summarize data.

Common Aggregate Functions:

1. COUNT(): Returns the number of rows.


2. SUM(): Returns the total sum of a numeric column.
3. AVG(): Returns the average value of a numeric column.
4. MAX(): Returns the largest value.
5. MIN(): Returns the smallest value.

2
Dr. Shweta

Example: Using COUNT


SELECT COUNT(*) FROM Students;

Using AVG
SELECT AVG(StudentID) FROM Students;

Grouping Data with GROUP BY


The GROUP BY clause groups rows that have the Time values in specified columns.

Syntax for GROUP BY


SELECT column, aggregate_function(column)
FROM table_name
GROUP BY column;

Example: Grouping by Last Name


SELECT LastName, COUNT(*)
FROM Students
GROUP BY LastName;

This counts how many students share the Time last name.

Joining Tables
JOIN is used to combine rows from two or more tables.

Types of JOINs

1. INNER JOIN: Returns rows with matching values in both tables.


2. LEFT JOIN: Returns all rows from the left table, and matched rows from the right
table.
3. RIGHT JOIN: Returns all rows from the right table, and matched rows from the left
table.

Syntax for JOIN


SELECT columns
FROM table1

3
Dr. Shweta

JOIN table2
ON table1.column = table2.column;

Example: Joining Two Tables

Suppose we have another table called Courses:

CREATE TABLE Courses (

CourseID INT,

CourseName VARCHAR(50)

);

Now, we can join Students and Courses:

SELECT Students.FirstName, Students.LastName, Courses.CourseName

FROM Students

JOIN Courses

ON Students.StudentID = Courses.CourseID;

Subqueries
A subquery is a query inside another query.

Example of a Subquery

SELECT * FROM Students

WHERE StudentID IN (SELECT StudentID FROM Courses);

Example: Combining Multiple Queries

SELECT Students.FirstName, COUNT(Courses.CourseID)

FROM Students

4
Dr. Shweta

JOIN Courses ON Students.StudentID = Courses.CourseID

GROUP BY Students.FirstName;

SQL Constraints
Constraints are rules applied to table columns to ensure the validity, consistency, and
accuracy of the data.

Types of Constraints

1. NOT NULL: Ensures that a column cannot have a NULL value.


2. UNIQUE: Ensures that all values in a column are unique.
3. PRIMARY KEY: Uniquely identifies each record in a table.
4. FOREIGN KEY: Links two tables and ensures referential integrity.
5. CHECK: Ensures that a column’s value satisfies a specific condition.
6. DEFAULT: Sets a default value for a column if none is specified.

Creating the Students Table

CREATE TABLE Students (


StudentID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
DateOfBirth DATE,
CourseID INT,
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);

Creating the Courses Table


CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL,
Credits INT CHECK (Credits > 0)
);

Inserting Data into the Courses Table

INSERT INTO Courses (CourseID, CourseName, Credits)

VALUES

5
Dr. Shweta

(1, 'Mathematics', 3),

(2, 'Physics', 4),

(3, 'Chemistry', 3),

(4, 'Computer Science', 5);

Inserting Data into the Students Table


INSERT INTO Students (StudentID, FirstName, LastName, Email, DateOfBirth, CourseID)

VALUES

(1, 'Dennis', 'Ritchie', '[email protected]', '2001-04-10', 1),

(2, 'Bill', 'Gates', '[email protected]', '2000-07-22', 4),

(3, 'Tim', 'Berners', '[email protected]', '2002-03-18', 2),

(4, 'Charles', 'Babbage ', 'Charles.Babbage @example.com', '2001-11-12', 3),

(5, 'Vinton', 'Gray', '[email protected]', '1999-09-30', 1);

SQL Constraints with Students Table


1. NOT NULL Constraint

This constraint ensures that a column (e.g., FirstName and LastName) cannot contain
NULL values.

Example: Querying Students with Non-NULL Last Names

SELECT * FROM Students

WHERE LastName IS NOT NULL;

UNIQUE Constraint

Ensures that no duplicate values exist in a column, like Email.

Example: Trying to Insert a Duplicate Email (This Will Fail)

6
Dr. Shweta

INSERT INTO Students (StudentID, FirstName, LastName, Email, DateOfBirth, CourseID)

VALUES (6, 'James’', 'Gosling', '[email protected]', '2003-05-21', 2);

Since Email must be unique, this query will raise an error.

Foreign Key Constraints


A Foreign Key links the Students table to the Courses table, ensuring that students can only
enroll in valid courses.

Example: Inserting a Student with an Invalid Course ID

INSERT INTO Students (StudentID, FirstName, LastName, Email, DateOfBirth, CourseID)

VALUES (6, 'James’', 'Gosling', '[email protected]', '2003-05-21', 10);

ORDER BY Clause to Sort Students by Last Name


SELECT * FROM Students
ORDER BY LastName ASC;

Modifying the Students Table


1. Adding a New Column to the Students Table
ALTER TABLE Students
ADD PhoneNumber VARCHAR(15);

Updating Data in the Students Table


Let’s say we want to update Tim Berners’s email address.

UPDATE Students
SET Email = '[email protected]'
WHERE StudentID = 3;

You might also like