-
Notifications
You must be signed in to change notification settings - Fork 62
/
SQL Cheatsheet
268 lines (202 loc) · 10.7 KB
/
SQL Cheatsheet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
SQL allows us to interact with the databases and bring out/manipulate data within them. Using SQL, we can create our own databases and then add data into these databases in the form of tables.
The following functionalities can be performed on a database using SQL:
• Create or Delete a Database.
• Create or Alter or Delete some tables in a Database.
• SELECT data from tables.
• INSERT data into tables.
• UPDATE data in tables.
• DELETE data from tables.
• Create Views in the database.
• Execute various aggregate functions.
SQL-Create Table:
We use the CREATE command to create a table. The table can be created with the following code:
CREATE TABLE student(
ID INT NOT NULL,
Name varchar(25),
Phone varchar(12),
Class INT
);
SQL-Delete Table:
To delete a table from a database, we use the DROP command.
DROP TABLE student;
SQL Commands
SQL Commands are instructions that are used by the user to communicate with the database, to perform specific tasks, functions and queries of data.
Types of SQL Commands:
The above image broadly shows the different types of SQL commands available in SQL in the form of a chart.
1. Data Definition Language(DDL): It changes a table’s structure by adding, deleting and altering its contents. Its changes are auto-committed(all changes are automatically permanently saved in the database). Some commands that are a part of DDL are:
• CREATE: Used to create a new table in the database.
Example:
CREATE TABLE STUDENT(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
• ALTER: Used to alter contents of a table by adding some new column or attribute, or changing some existing attribute.
Example:
ALTER TABLE STUDENT ADD(ADDRESS VARCHAR2(20));
ALTER TABLE STUDENT MODIFY (ADDRESS VARCHAR2(20));
• DROP: Used to delete the structure and record stored in the table.
Example:
DROP TABLE STUDENT;
• TRUNCATE: Used to delete all the rows from the table, and free up the space in the table.
Example:
TRUNCATE TABLE STUDENT;
2. Data Manipulation Language(DML): It is used for modifying a database, and is responsible for any form of change in a database. These commands are not auto-committed, i.e all changes are not automatically saved in the database. Some commands that are a part of DML are:
• INSERT: Used to insert data in the row of a table.
Example:
INSERT INTO STUDENT (Name, Subject) VALUES ("Shreya", "DSA");
In the above example, we insert the values “Shreya” and “DSA” in the columns Name and Subject in the STUDENT table.
• UPDATE: Used to update value of a table’s column.
Example:
UPDATE STUDENT
SET User_Name = 'Devansh'
WHERE Student_Id = '2'
In the above example, we update the name of the student, whose Student_ID is 2, to the User_Name = “Devansh”.
• DELETE: Used to delete one or more rows in a table.
Example:
DELETE FROM STUDENT
WHERE Name = "Sneha";
In the above example, the query deletes the row where the Name of the student is “Sneha” from the STUDENT table.
3. Data Control Language(DCL): These commands are used to grant and take back access/authority (revoke) from any database user. Some commands that are a part of DCL are:
• Grant: Used to grant a user access privileges to a database.
Example:
GRANT SELECT, UPDATE ON TABLE_1 TO USER_1, USER_2;
In the above example, we grant the rights to SELECT and UPDATE data from the table TABLE_1 to users - USER_1 and USER_2.
• Revoke: Used to revoke the permissions from an user.
Example:
REVOKE SELECT, UPDATE ON TABLE_1 FROM USER_1, USER_2;
In the above example we revoke the rights to SELECT and UPDATE data from the table TABLE_1 from the users- USER_1 and USER_2.
4. Transaction Control Language: These commands can be used only with DML commands in conjunction and belong to the category of auto-committed commands. Some commands that are a part of TCL are:
• COMMIT: Saves all the transactions made on a database.
Example:
DELETE FROM STUDENTS
WHERE AGE = 16;
COMMIT;
In the above database, we delete the row where AGE of the students is 16, and then save this change to the database using COMMIT.
• ROLLBACK: It is used to undo transactions which are not yet been saved.
Example:
DELETE FROM STUDENTS
WHERE AGE = 16;
ROLLBACK;
By using ROLLBACK in the above example, we can undo the deletion we performed in the previous line of code, because the changes are not committed yet.
• SAVEPOINT: Used to roll transaction back to a certain point without having to roll back the entirity of the transaction.
Example:
SAVEPOINT SAVED;
DELETE FROM STUDENTS
WHERE AGE = 16;
ROLLBACK TO SAVED;
In the above example, we have created a savepoint just before performing the delete operation in the table, and then we can return to that savepoint using the ROLLBACK TO command.
5. Data Query Language: It is used to fetch some data from a database. The command belonging to this category is:
• SELECT: It is used to retrieve selected data based on some conditions which are described using the WHERE clause. It is to be noted that the WHERE clause is also optional to be used here and can be used depending on the user’s needs.
Example:
SELECT Name
FROM Student
WHERE age >= 18;
Keys in SQL
A database consists of multiple tables and these tables and their contents are related to each other by some relations/conditions. To identify each row of these tables uniquely, we make use of SQL keys. A SQL key can be a single column or a group of columns used to uniquely identify the rows of a table. SQL keys are a means to ensure that no row will have duplicate values. They are also a means to establish relations between multiple tables in a database.
Types of Keys:
1. Primary Key: They uniquely identify a row in a table.
Properties:
• Only a single primary key for a table. (A special case is a composite key, which can be formed by the composition of 2 or more columns, and act as a single candidate key.)
• The primary key column cannot have any NULL values.
• The primary key must be unique for each row.
Example:
CREATE TABLE Student (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Class int,
PRIMARY KEY (ID)
);
2. Foreign Key: Foreign keys are keys that reference the primary keys of some other table. They establish a relationship between 2 tables and link them up.
Example: In the below example, a table called Orders is created with some given attributes and its Primary Key is declared to be OrderID and Foreign Key is declared to be PersonId referenced from the Person's table. A person's table is assumed to be created beforehand.
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
3. Super Key: It is a group of single or multiple keys which identifies row of a table.
4. Candidate Key: It is a collection of unique attributes that can uniquely identify tuples in a table.
5. Alternate Key: It is a column or group of columns that can identify every row in a table uniquely.
6. Compound Key: It is a collection of more than one record that can be used to uniquely identify a specific record.
7. Composite Key: Collection of more than one column that can uniquely identify rows in a table.
8. Surrogate Key: It is an artificial key that aims to uniquely identify each record.
Joins in SQL
Joins are a SQL concept that allows us to fetch data after combining multiple tables of a database.The following are the types of joins in SQL:
1. INNER JOIN: Returns any records which have matching values in both tables.
The SQL code will be as follows,
SELECT orders.order_id, products.product_name,customers.customer_name,products.price
FROM orders
INNER JOIN products ON products.product_id = order.product_id
INNER JOIN customers on customers.customer_id = order.customer_id;
2. NATURAL JOIN: It is a special type of inner join based on the fact that the column names and datatypes are the same on both tables.
Syntax:
Select * from table1 Natural JOIN table2;
Example:
Select * from Customers Natural JOIN Orders;
In the above example, we are merging the Customers and Orders table shown above using a NATURAL JOIN based on the common column customer_id.
Shortcut:
Select * from Customers , Orders;
-- join using ',' operator
3. RIGHT JOIN: Returns all of the records from the second table, along with any matching records from the first.
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
4. LEFT JOIN: Returns all of the records from the first table, along with any matching records from the second table.
We will apply Left Join on the above tables, as follows,
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
5. FULL JOIN: Returns all records from both tables when there is a match.
Applying Outer Join on the above 2 tables, using the code:
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Triggers in SQL
SQL codes automatically executed in response to a certain event occurring in a table of a database are called triggers. There cannot be more than 1 trigger with a similar action time and event for one table.
Syntax:
Create Trigger Trigger_Name
(Before | After) [ Insert | Update | Delete]
on [Table_Name]
[ for each row | for each column ]
[ trigger_body ]
Example:
CREATE TRIGGER trigger1
before INSERT
ON Student
FOR EACH ROW
SET new.total = (new.marks/ 10) * 100;
Here, we create a new Trigger called trigger1, just before we perform an INSERT operation on the Student table, we calculate the percentage of the marks for each row.
Some common operations that can be performed on triggers are:
• DROP: This operation will drop an already existing trigger from the table.
o Syntax:
DROP TRIGGER trigger name;
• SHOW: This will display all the triggers that are currently present in the table.
o Syntax:
SHOW TRIGGERS IN database_name;
Aggregate functions:
1) count:
syntax- select count(*) from table_name where some_condition;
2) sum:
syntax- select sum(cost) from table_name where some_condition;
3) avg:
syntax- select avg(cost) from table_name;
4) min:
syntax- select min(cost) from table_name;
5) max:
syntax- select max(cost) from table_name;
View in SQL
View is a database object created from a pre-existing table/s . View is basically a Virtual Table created by a query by joining one or more tables .
Syntax:
CREATE [OR REPLACE] VIEW [VIEW_Name] AS
SELECT [Table_columns]
FROM [Table_Name]
[WHERE conditions];
Example:
CREATE VIEW trainer AS
SELECT course_name, trainer
FROM courses;
Here a View is created to see course_name and trainer from table courses .