SQL Queries

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Relational Database is a collection of logically related relations/tables.

Table/Relation is a collection of logically related rows.


(The name 'relation' because columns and rows are all logically related)
Row/record/tuple is a collection of logically related columns.
Column/field/attribute/key contains a data values i.e. one piece of information.
Structured information is a tabular information wherein information is properly laid out or classified or segregated. It allows
an easy access to the information.
Folio Name Clas DOJ
s
123 Abcd 11C 20200812
456 Xyz 12A 20190728
...
Relational Database Management System (RDBMS) is a software that is used to create and manage a database and its
objects. e.g. MySQL, Oracle, MSSQL
SQL (Structured Query Language) is a language that is used by an RDBMS to create and manage database and its objects.
Typical work flow of creating and managing a database using SQL queries
 Create a database (just once)
 Use the database (every time while working on tables)
 Create a table (set the table structure - define column names, their data types, sizes and constraints)(SQL datatypes
include – int, decimal, char, varchar, date)
 Insert rows (add or input data into the tables)
 Select rows (display records)
 Update rows (change data values)
 Change (alter) the table structure (by adding or removing columns)
 Delete rows (remove the data values from the table)
 Drop table and database (remove the containers)
Prerequisites of working with SQL
 Download and install XAMPP (just once)
 To start working with SQL, everytime, in CMD type the following command to start the MySQL server
C:\xampp\mysql\bin>mysql -u root –p
Enter password when prompted for
(type cd C:\xampp\mysql\bin at command the prompt to go to bin subdirectory)
To create a MySQl server user 'u1' with password 'p1'
GRANT ALL PRIVILEGES ON *.* TO 'u1'@'localhost' IDENTIFIED BY 'p1'
 Type SQL queries to perform RDBMS related tasks in front of MYSQL prompt (something like MariaDB [d1]>
where 'd1' is the database name, initially the prompt will read as MariaDB [(none)] indicating that no database is
in use.)
 Type 'exit' to close the MySQL server
SQL Queries
1. Create a new database (just once!)
CREATE DATABASE mydatabase;
2. Open an existing database (so that one can create or use existing tables in it)
USE mydatabase;
3. Create a table 'student' with the following columns:
roll, name, house, class, gender, dob, doj, fee, marks, garde, result
#primary key ensures that values are unique
CREATE TABLE student(
roll INT PRIMARY KEY,
name VARCHAR(30),
house VARCHAR(30),
class VARCHAR(3),
gender CHAR,
dob DATE,
doj DATE,
fee DECIMAL(10,2),
marks INT,
garde VARCHAR(2),
result VARCHAR(30)
);
4. Insert a new record into the table student.
(for INT/DECIMAL/DATE – write values without quotes and for VARCHAR/CHAR – write values within quotes)
INSERT INTO student VALUES(1, 'Ritul', 'Pant', '11A', 'F', 20010322, 20180413,
54000.00, 78, 'B1', 'PASS');
or
INSERT INTO student(name,roll,house,class) VALUES('Ritul',1,'Pant','11A');
5. Insert/Add a new field city into the table student.
ALTER TABLE student ADD COLUMN city VARCHAR(30); #changes table structure
...and update the city for all the existing rows e.g. as:
UPDATE student SET city='Delhi' WHERE roll=123; #changes data values
6. List/Display/show/print all records from the table student. ('*' means all columns) (If not using WHERE clause,
query picks up all the rows)
SELECT * FROM student; #* means all columns and NOT using WHERE means all rows
7. Change/update the class of a student.
UPDATE student SET class='12A' WHERE roll=1;
8. Shift all class 10A students to 11A.
UPDATE student SET class='11A' WHERE class='10A';
9. List the number of students coming from Delhi.
SELECT count(*) FROM student WHERE city='DELHI';
10. List the students coming from Delhi.
SELECT * FROM student WHERE city='DELHI';
11. List the student records if name starts with 'Kumar'.
SELECT * FROM student WHERE name LIKE 'Kumar%';
12. List the student records if name ends with 'Kumar'.
SELECT * FROM student WHERE name LIKE '%Kumar';
13. List the student records if name contains the word 'Kumar'.
SELECT * FROM student WHERE name LIKE '%Kumar%';
14. List the students who have joined after 1st of April 2018. DATE FORMAT => YYYYMMDD
SELECT name FROM student WHERE doj > 20180401;
15. List students if they have joined the school in 2015.
SELECT * FROM student WHERE YEAR(doj) = 2015;
16. List students if they have joined the school in April of 2015.
SELECT * FROM student WHERE MONTH(doj) = 4 AND YEAR(doj) = 2015;
17. List the classes in the school.
SELECT DISTINCT class FROM student;
18. Display the cities, the school has students from. (How many cities we have the students from?)
SELECT DISTINCT city FROM student;
19. Display the class 11A students.
SELECT * FROM student WHERE class='11A';
20. Display the class 11 students......Display the class 11A and 11C students.
SELECT * FROM student WHERE class='11A' AND OR class='11C';
OR
SELECT * FROM student WHERE class IN('11A','11C')
or
SELECT * FROM student WHERE class LIKE '11%';
21. Display the class 11A students of Tilak house.
SELECT *FROM student WHERE house='Tilak' AND class='11A';
22. Display the class 11A students of Tilak house if their marks are less than 40.
SELECT * FROM student WHERE house='Tilak' AND class='11A'
AND marks < 40;
marks between 40 and 60
23. Remove/delete the student record if class is 11C.
DELETE FROM student WHERE class='11C';
Remove/delete the student record if roll is 23.
DELETE FROM student WHERE roll=23;
24. Upgrade the class of all class 10 students.
UPDATE student SET class='11' WHERE class LIKE '10%';
25. Display the first 3 characters of each student name.
SELECT LEFT(name, 3) FROM student;
26. Display the last 3 characters of each student name.
SELECT RIGHT(name, 3) FROM student;
27. Display the number of characters in each student name.
SELECT name, LENGTH(name) FROM student;
28. List the students who have scored marks between 80 and 90.
SELECT * FROM student WHERE marks BETWEEN 80 AND 90;
or
SELECT * FROM student WHERE marks >=80 AND OR marks<=90;
29. Display the student names if 4th & 5th characters are 'JA'.
SELECT name FROM student WHERE MID(name,4,2)='JA';
30. Display the name if it contains at least 5 characters.
SELECT name FROM student WHERE LENGTH(name)>=5;
or
SELECT name FROM student WHERE name LIKE '_ _ _ _ _%'; WILD CARDS
31. Display the student records if name if lengthier than 20 characters.
SELECT * FROM student WHERE LENGTH(name)>20;
32. Round off the fee of each student. Also find the square root of fee.
SELECT ROUND(fee), SQRT(fee) FROM student;
33. Round off the fee of each student, to two places.
SELECT ROUND(fee,2) FROM student;
34. Display the student records if their marks are even numbers.
SELECT * FROM student WHERE MOD(marks, 2)=0;
35. Drop the table student.
DROP TABLE student; USE IT WITH EXTRA CAUTION!!!
36. Increase the marks of every student by 10.
UPDATE student SET marks=marks+10;
37. Increase the marks of every student by 10% if it is less than 40.
UPDATE student SET marks=marks+marks*10/100 WHERE marks < 40;
38. Change the city name to New Delhi if it is Delhi.
UPDATE student SET city='New Delhi' WHERE city='Delhi';
39. Count the number of students.
SELECT COUNT(*) FROM student;
and
SELECT COUNT(name) FROM student; (this might give a different count!)
40. Count the number of students class-wise.
SELECT class, COUNT(class) FROM student GROUP BY class;
41. Display the table structure.
DESC student;
42. Display the tables in a database.
SHOW TABLES;
43. Delete all records of Delhi students.
DELETE FROM student WHERE city='Delhi';
DELETE FROM student will remove all the records, so be careful
44. Open the database named d123.
USE d123;
45. Display student names alphabetically.
SELECT name FROM student ORDER BY name;
46. Display student records house wise (in ascending order) and class wise (in descending order).
SELECT name FROM student ORDER BY house asc, class desc;
47. Remove the database d123.
DROP DATABASE d123;
48. Create a table s1 with roll and name where roll is a primary key.
CREATE TABLE s1(roll INT PRIMARY KEY, name VARCHAR(30));
49. Add the primary key constraint to the roll column of an existing table s2.
ALTER TABLE s2 ADD CONSTRAINT pk PRIMARY KEY (roll);
50. Remove the primary key constraint from the table s2.
ALTER TABLE s2 DROP PRIMARY KEY;
51. Create table s3 with following constraints - roll PK, name not null, age >0, folio unique, class default 10A.
CREATE TABLE s3(roll int PRIMARY KEY, name varchar(30) NOT NULL, age INT
CHECK(age>0), folio int UNIQUE, class VARCHAR(3) DEFAULT '10A');

AGGREGATE FUNCTIONS
Multiple Row Functions or Aggregate Functions operate on a set of rows to return a single value.
52. Find the highest and lowest marks scored in the database table and display it as 'Highest Marks' and 'Lowest Marks'.
SELECT MAX(marks) as 'Highest Marks', MIN(marks) as 'Lowest Marks' FROM
student;
53. Find the average marks.
SELECT AVG(marks) as 'Average Marks' FROM student;
54. Find the total fee collected.
SELECT SUM(fee) as 'Total Fee' FROM student;
55. Find the number of students in the table.
SELECT COUNT(*) as 'No. of Students' FROM student;
56. Find the number of students in the table if their result has been declared.
SELECT COUNT(result) as 'No. of Results Generated' FROM student;
or
SELECT COUNT(*) as 'No. of Results Generated' FROM student WHERE result IS NOT
NULL;
57. Find the number of students in the table whose result has not been declared.
SELECT COUNT(*) as 'No. of Results NOT Generated' FROM student WHERE result IS
NULL;
QUERYING DATA USING GROUP BY, HAVING, ORDER BY
58. Find the number of students in each class.
SELECT class, COUNT(class) FROM student GROUP BY class;
59. Find the number of students in classes '6A', '7A', and '8A'.
(DON'T USE WHERE, INSTEAD USE HAVING TO CHECK A CONDITION WHILE USING GROUP BY)
SELECT class, COUNT(class) FROM student GROUP BY class HAVING class
IN('6A','7A','8A');
60. Find the number of students in classes other than '6A', '7A', and '8A'.
SELECT class, COUNT(class) FROM student GROUP BY class HAVING class NOT
IN('6A','7A','8A');
61. Display the student records class-wise.
SELECT * FROM student ORDER BY class;
62. Display the student records class-wise arranged alphabetically based on their names.
SELECT * FROM student ORDER BY class, name;
63. Display the student records in descending order of class, arranged alphabetically based on their names.
SELECT * FROM student ORDER BY class DESC, name ASC;
Single Row Functions in MySQL
Single Row Functions operate on a single value and return a single value. They can accept one or more arguments but return
only one result per row. When applied on a table, they return a single result for every row of the queried table.
Single row functions can further be categorized as – Numeric functions, String functions and Date and Time functions.
NUMERIC FUNCTIONS
Numeric functions perform operations on numeric values and return numeric values.
POWER(X,Y) returns the value of X raised to the power of Y.
SELECT POW(2,4); 16
SELECT POW(2,-2); 0.25
SELECT POW(-2,3); -8
SELECT id,num1,POWER(num1,2) FROM t1;
ROUND(X,D) or ROUND(X) rounds the argument X to D decimal places. If number of decimal places is not specified or is
zero, the number rounds to the nearest integer OR (0 decimal places). If negative value is specified for precision, it counts off
that value left from the decimal point – rounds off the value to the nearest tens, hundred , thousand and so on. If positive value
is specified for precision, it counts off that value right from the decimal point.
SELECT ROUND(-1.23); -1
SELECT ROUND(-1.58); -2
SELECT ROUND(1.43); 1
SELECT ROUND(6.298, 1); 6.3
SELECT ROUND(6.235, 0); 6
SELECT ROUND(56.235, -1); 60
SELECT id,ROUND(num1,0) FROM t1;
TRUNCATE(X,D) returns the number X, truncated to D decimal places. If D is 0, the result has no decimal point or fractional
part. If D is negative, it causes D digits left of the decimal point of the value X to become zero. TRUNCATE does not round a
number. It simply chops off digits from a number.
SELECT TRUNCATE(7.543,1); 7.5
SELECT TRUNCATE(4.567,0); 4
SELECT TRUNCATE(-7.45,1); -7.4
SELECT TRUNCATE(346,-2); 300
SELECT id,TRUNCATE(num1,0) FROM employee;
MOD(n1, n2) or n1 MOD n2 or n1%n2 returns the remainder of a number divided by another number.
SELECT MOD(18, 4);
or
SELECT 18 MOD 4;
or
SELECT 18 % 4;
STRING (or CHARACTER) FUNCTIONS
String functions operate on character type data. String functions are used to extract, change, format or alter character strings.
These functions return either character or numeric values.
LENGTH(str) returns the length of a column or a string in bytes.
SELECT LENGTH('Informatics'); 11
SELECT LENGTH(name) FROM student;
CONCAT(str1,str2,...) returns the string that results from concatenating the arguments.
SELECT CONCAT('My', 'S', 'QL'); 'MySQL'
SELECT CONCAT('Class', NULL, 'XI'); NULL
SELECT CONCAT(roll,'',name) FROM student;
INSTR(str,substr) returns the position of the first occurrence of substring substr in string str.
SELECT INSTR ('Informatics', 'for'); 3
SELECT INSTR('Computers', 'pet'); 0
SELECT INSTR(name,'Kumar') FROM student;
LOWER(str) or LCASE(str) returns the argument 'str' in lowercase i.e. it changes all the characters of the passed string to
lowercase.
SELECT LOWER('INFORMATICS'); 'informatics'
SELECT LOWER(name) FROM student;
UPPER(str) or UCASE(str) returns the argument in uppercase. i.e. it changes all the characters of the passed string to
uppercase.
SELECT UPPER('Informatics'); 'INFORMATICS'
SELECT UPPER(name) FROM student;
LEFT(str,n) returns the specified number of characters (n)from the left side of string str.
SELECT LEFT('Informatics', 3); 'Inf'
select LEFT(name,3)FROM student;
RIGHT(str,n) returns the specified number of characters (n) from the right side of string str.
SELECT RIGHT('Informatics', 4); 'tics'
SELECT RIGHT(name,3) FROM student;
LTRIM(str) removes leading spaces i.e. removes spaces from the left side of the string str.
SELECT LTRIM(' Informatics'); 'Informatics'
SELECT LTRIM(name) FROM student;
RTRIM(str) removes trailing spaces i.e. removes spaces from the right side of the string str.
SELECT RTRIM('Informatics '); 'Informatics'
SELECT RTRIM(name) FROM student;
TRIM(str) removes both leading and trailing spaces from the string str.
SELECT TRIM(' Informatics '); 'Informatics'
SELECT TRIM(name) FROM student;
SUBSTRING(str,m,n) or MID(str,m,n) or SUBSTR(str,m,n) returns the specified number of characters from the middle of
the string. There are three arguments. The first argument is the source string. The second argument is the position of first
character to be displayed. The third argument is the number of characters to be displayed. If the third argument is missing, then
starting from the position specified, the rest of the string is returned. A negative value for the second argument i.e. the position
(pos) means, the beginning of the substring is pos characters from the end of the string, SUBSTR is the same as SUBSTRING.
SELECT SUBSTRING('Informatics',3); 'formatics'
SELECT SUBSTRING('Informatics' FROM 4); 'ormatics'
SELECT SUBSTRING('Informatics',3,4); 'form'
SELECT SUBSTRING('Computers', -3); 'ers'
SELECT SUBSTRING('Computers', -5, 3); 'ute'
SELECT SUBSTRING('Computers' FROM -4 FOR 2); 'te'
SELECT MID('Informatics',3,4); 'form'
select MID(name,3,2) FROM student;
ASCII(str) returns the ASCII value of the leftmost character of the string str. Returns 0 if str is an empty string. Returns
NULL if str is NULL.
SELECT ASCII('2'); 50(ASCII value of character '2')
SELECT ASCII('dx'); 100(ASCII value of d)
SELECT ASCII('A'); 65(ASCII value of 'A')
DATE AND TIME FUNCTIONS
Date and Time functions perform various tasks on or manipulate Date type data. The default date format in MySQL is 'YYYY-
MM-DD' or YYYYMMDD.
CURDATE() returns the current date in YYYY-MM-DD format or YYYYMMDD format, depending on whether the function
is used in a string or numeric context.
SELECT CURDATE();
'2010-02-26'
DATE(expr) extracts the date part of a date or datetime expression.
SELECT DATE('2010-02-26 01:02:03');
'2010-02-26'
SELECT DATE('2009-10-16 01:02:03')
'2009-10-16'
DAYOFMONTH(date) or DAY(date) returns the day of the month for a given date; returns a number in the range 0 to 31.
SELECT DAYOFMONTH('2009-07-21'); 21
SELECT name, dayofmonth(doj) FROM student;
MONTH(date) returns the numeric month from the date passed, in the range 0 to 12. It returns 0 for dates such as '0000-
00-00' or '2010-00-00' that have a zero month part.
SELECT MONTH('2010-02-26'); 2
SELECT name, month(doj) FROM student;
MONTHNAME() returns the name of the month (January, February....) for a given date.
SELECT MONTHNAME("2017-06-15 09:34:21");
SELECT MONTHNAME(CURDATE());
SELECT name, monthname(doj) FROM student;
YEAR(date) returns the year for date passed in the range 0 to 9999. Returns values like 1998, 2010,1996 and so on.
SELECT YEAR('2010-02-26'); 2010
SELECT name, year(doj) FROM student;
DAYNAME(date) returns the name of the weekday (Sunday, Monday....) for the date passed.
SELECT DAYNAME('2010-02-26');
SELECT name, dayname(doj) FROM student;
DAYOFWEEK(date) returns the day of week in number as 1 for Sunday, 2 for Monday and so on.
SELECT DAYOFWEEK('2009-07-21'); 3
SELECT name, dayofweek(doj) FROM student;
DAYOFYEAR(date) returns the day of the year for the given date in numeric format in the range 1 to 366. e.g. 1 st Feb is the
32nd day of the year.
SELECT DAYOFYEAR('2009-07-21'); 202
SELECT DAYOFYEAR('2009-01-01'); 1
SELECT name, dayofyear(doj) FROM student;
NOW() returns the current date and time in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format,
depending on whether the function is used in a string or numeric context.
SELECT NOW();
'2010-02-26 21:30:26'
SYSDATE() returns the current date and time in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHM MSS.uuuuuu format,
depending on whether the function is used in a string or numeric context. It returns the time at which the function executes.
SYSDATE() differs from NOW() which returns a constant time that indicates the time at which the statement began to
execute.
SELECT SYSDATE();
'2010-02-26 21:30:26'
SELECT SYSDATE() + 0;
20100226213026.000000
Difference between NOW() and SYSDATE()
The sleep(arg) function pauses for the number of seconds given by the argument.
NOW() Even after a pause of 20 seconds induced by sleep(20),now() shows the same time ie. the time at which the
statement began to execute.
SELECT now(), sleep(20), now();
'2010-05-08 14:57:12' 0 '2010-05-08 14:57:12'
SYSDATE() After 20 seconds induced by sleep(20), sysdate() shows time incremented by 20 seconds.
SELECT sysdate(), sleep(20), sysdate();
'2010-05-08 14:57:12' 0 '2010-05-08 14:57:32'

You might also like