├── README.md
├── Schemas.sql
├── assets
├── data-integrity.png
├── many-to-many.png
├── one-to-many.png
├── one-to-one.png
├── star.png
├── system-integrity.png
└── table.png
├── important.md
├── sql-commands.md
└── sql-query-practice.md
/README.md:
--------------------------------------------------------------------------------
1 | # SQL Basics
2 |
3 | > *Click ★ if you like the project. Your contributions are heartily ♡ welcome.*
4 |
5 |
6 |
7 | ## Related Topics
8 |
9 | * *[SQL Commands](sql-commands.md)*
10 | * *[SQL Query Practice](sql-query-practice.md)*
11 |
12 |
13 |
14 | ## Table of Contents
15 |
16 | * [Introduction](#-1-introduction)
17 | * [SQL Data Types](#-2-sql-data-types)
18 | * [SQL Database](#-3-sql-database)
19 | * [SQL Table](#-4-sql-table)
20 | * [SQL Select](#-5-sql-select)
21 | * [SQL Clause](#-6-sql-clause)
22 | * [SQL Order By](#-7-sql-order-by)
23 | * [SQL Insert](#-8-sql-insert)
24 | * [SQL Update](#-9-sql-update)
25 | * [SQL Delete](#-10-sql-delete)
26 | * [SQL Keys](#-11-sql-keys)
27 | * [SQL Join](#-12-sql-join)
28 | * [SQL RegEx](#-13-sql-regex)
29 | * [SQL Indexes](#-14-sql-indexes)
30 | * [SQL Wildcards](#-15-sql-wildcards)
31 | * [SQL Date Format](#-16-sql-date-format)
32 | * [SQL Transactions](#-17-sql-transactions)
33 | * [SQL Functions](#-18-sql-functions)
34 | * [SQL View](#-19-sql-view)
35 | * [SQL Triggers](#-20-sql-triggers)
36 | * [SQL Cursors](#-21-sql-cursors)
37 | * [SQL Stored Procedures](#-22-sql-stored-procedures)
38 | * [Miscellaneous](#-23-miscellaneous)
39 |
40 |
41 |
42 | ## # 1. Introduction
43 |
44 |
45 |
46 | ## Q. What is a database?
47 |
48 | A database is a systematic or organized collection of related information that is stored in such a way that it can be easily accessed, retrieved, managed, and updated.
49 |
50 | **Syntax:**
51 |
52 | ```sql
53 | CREATE DATABASE
54 | ```
55 |
56 | **Example:**
57 |
58 | ```sql
59 | CREATE DATABASE Product
60 | ```
61 |
62 | ## Q. What is a database table?
63 |
64 | A database table is a structure that organises data into rows and columns – forming a grid.
65 |
66 | Tables are similar to a worksheets in spreadsheet applications. The rows run horizontally and represent each record. The columns run vertically and represent a specific field. The rows and columns intersect, forming a grid. The intersection of the rows and columns defines each cell in the table.
67 |
68 |
69 |
70 |
71 |
72 | **Syntax:**
73 |
74 | ```sql
75 | CREATE TABLE (ID INT, NAME VARCHAR(30) )
76 |
77 | DROP TABLE
78 |
79 | SELECT * FROM
80 | ```
81 |
82 |
85 |
86 | ## Q. What is a database relationship?
87 |
88 | Database relationships are associations between tables that are created using join statements to retrieve data. It helps improve table structures and reduce redundant data.
89 |
90 | Understanding relationship in databases is important as it allows you to fetch data from multiple tables simultaneously and helps ensure that data in databases are consistent and updated.
91 |
92 | **Types of Database Relationships:**
93 |
94 | **1. One-to-One:**
95 |
96 | A one-to-one relationship is a relationship between two tables where each table can have only one matching row in the other table.
97 |
98 |
99 |
100 |
101 |
102 | Using the above screenshot as an example, the business case is that each employee\'s pay details must be stored in a separate table to the employee\'s contact details. In such a case, there can only be one row in the Pay table that matches a given employee in the Employees table. This is a good candidate for a one-to-one relationship.
103 |
104 | **2. One-to-Many:**
105 |
106 | The one-to-many relationship is similar to the one-to-one relationship, except that it allows multiple matching rows in one of the tables.
107 |
108 |
109 |
110 |
111 |
112 | In the above example, each author can have many books, but each book can only have one author.
113 |
114 | Therefore, the Books table is allowed to contain multiple rows with the same AuthorId value. If an author has released five books, then there would be one row in Authors for that author, and five rows in Books, each with that author\'s AuthorId.
115 |
116 | **3. Many-to-Many:**
117 |
118 | In a many-to-many relationship, each side of the relationship can contain multiple rows.
119 |
120 |
121 |
122 |
123 |
124 | In this example, each book is allowed to have multiple authors. Therefore, I created a lookup table (also known as a "junction table") that stores both the AuthorId and the BookId.
125 |
126 | These two columns could be configured to be the primary key of the table (in which case they would be a "composite primary key" or simply "composite key"), or you could create a separate column to be the primary key.
127 |
128 | Note that the Books table doesn\'t have AuthorId in this case. That column has been moved to the AuthorBooks table so that we can have many AuthorIds for the same BookId.
129 |
130 |
133 |
134 | ## Q. What is data Integrity?
135 |
136 | Data Integrity defines the accuracy and consistency of data stored in a database. It can also define integrity constraints to enforce business rules on the data when it is entered into the application or database.
137 |
138 | **Classification of Data Integrity:**
139 |
140 | * a) System/Pre Defined Integrity
141 | * b) User-Defined Integrity
142 |
143 |
144 |
145 |
146 |
147 | **a) System/Pre Defined Integrity:**
148 |
149 |
150 |
151 |
152 |
153 | **1. Entity Integrity:**
154 |
155 | Entity integrity ensures each row in a table is a uniquely identifiable entity. We can apply Entity integrity to the Table by specifying a primary key, unique key, and not null.
156 |
157 | **2. Referential Integrity:**
158 |
159 | Referential integrity ensures the relationship between the Tables.
160 |
161 | We can apply this using a Foreign Key constraint.
162 |
163 | **3. Domain Integrity:**
164 |
165 | Domain integrity ensures the data values in a database follow defined rules for values, range, and format. A database can enforce these rules using Check and Default constraints.
166 |
167 | **b) User-Defined Integrity:**
168 |
169 | It comprises the rules defined by the operator to fulfill their specific requirements. Entity, referential, and domain integrity are not enough to refine and secure data. Time in time again, particular business rules must be considered and integrated into data integrity processes to meet enterprise standards.
170 |
171 |
174 |
175 | ## Q. What are the two principles of relational database model?
176 |
177 | The two principal rules for the relational model are as follows:
178 |
179 | - Entity integrity: this is used to maintain the integrity at entity level
180 | - Referential integrity: it is used to maintain integrity on all the values which have been referenced.
181 |
182 | The differences between them are as follows:
183 |
184 | - Entity integrity tells that in a database every entity should have a unique key; on the other hand referential integrity tells that in the database every table values for all foreign keys will remain valid.
185 | - Referential integrity is based on entity integrity but it is not the other way around.
186 | - For example: if a table is present and there is a set of column out of which one column has parent key set then to ensure that the table doesn'\t contain any duplicate values, a unique index is defined on the column that contains the parent key.
187 |
188 |
191 |
192 | ## Q. What are the relational operations that can be performed on the database?
193 |
194 | There are many relational operators that are used to perform actions on relational database. These operators are as follows:
195 |
196 | 1. Union operator that combines the rows of two relations and doesn'\t include any duplicate. It also removes the duplicates from the result.
197 | 2. Intersection operator provides a set of rows that two relations have in common.
198 | 3. Difference operator provide the output by taking two relations and producing the difference of rows from first that don'\t exist in second.
199 | 4. Cartesian product is done on two relations. It acts as a cross join operator.
200 |
201 |
204 |
205 | ## Q. What do you understand by database Normalization?
206 |
207 | - Normalization is very essential part of relational model.
208 | - Normal forms are the common form of normalization.
209 | - It helps in reducing redundancy to increase the information overall.
210 | - It has some disadvantages as it increases complexity and have some overhead of processing.
211 | - It consists of set of procedures that eliminates the domains that are non-atomic and redundancy of data that prevents data manipulation and loss of data integrity.
212 |
213 |
216 |
217 | ## Q. What are the different types of normalization that exists in the database?
218 |
219 | There are 9 normalizations that are used inside the database. These are as follows:
220 |
221 | 1. First normal form: in this table represents a relation that has no repeating groups.
222 | 2. Second normal form: non- prime attributes are not functional dependent on subset of any candidate key.
223 | 3. Third normal form: in a table every non- prime attribute is non-transitively dependent on every candidate key
224 | 4. Elementary key normal form: superkey dependency or elementary key dependency effects the functional dependency in a table.
225 | 5. Boyce codd normal form: “every non-trivial functional dependency in the table is dependent on superkey”.
226 | 6. Fourth normal form: “Every non-trivial multivalued dependency in the table is a dependent on a superkey”.
227 | 7. Fifth normal form (5NF): “Every non-trivial join dependency in the table is implied by the superkeys of the table”.
228 | 8. Domain/key normal form (DKNF): “Every constraint on the table is a logical consequence of the table's domain constraints and key constraints”.
229 | 9. Sixth normal form (6NF): “Table features no non-trivial join dependencies at all”.
230 |
231 |
234 |
235 | ## Q. How de-normalization is different from normalization?
236 |
237 | - Analytical processing databases are not very normalized. The operations which are used are read most databases.
238 | - It is used to extract the data that are ancient and accumulated over long period of time. For this purpose de-normalization occurs that provide smart business applications.
239 | - Dimensional tables in star schema are good example of de-normalized data.
240 | - The de-normalized form must be controlled while extracting, transforming, loading and processing.
241 | - There should be constraint that user should not be allowed to view the state till it is consistent.
242 | - It is used to increase the performance on many systems without RDBMS platform.
243 |
244 |
247 |
248 | ## Q. What is the type of de-normalization?
249 |
250 | Non-first normal form (NFA)
251 |
252 | – It describes the definition of the database design which is different from the first normal form.
253 | - It keeps the values in structured and specialized types with their own domain specific languages.
254 | - The query language used in this is extended to incorporate more support for relational domain values by adding more operators.
255 |
256 |
259 |
260 | ## Q. How many levels of data abstraction are available?
261 |
262 | There are three levels of data abstraction available in database model and these are as follows:
263 |
264 | 1. Physical level: It is the lowest level that describes how data is stored inside the database.
265 | 2. Logical level: It is the next higher level in the hierarchy that provides the abstraction. It describes what data are stored and the relationship between them.
266 | 3. View level: It is the highest level in hierarchy that describes part of the entire database. It allows user to view the database and do the query.
267 |
268 |
271 |
272 | ## Q. What do you understand by Data Independence?
273 |
274 | Data independence tells about the independence of the data inside the application. It usually deals with the storage structure and represents the ability to modify the schema definition. It doesn'\t affect the schema definition which is being written on the higher level.
275 |
276 | There are two types of data independence:
277 |
278 | 1. Physical data independence: It allows the modification to be done in physical level and doesn'\t affect the logical level.
279 | 2. Logical data independence: It allow the modification to be done at logical level and affects the view level.
280 |
281 | NOTE: Logical Data Independence is more difficult to achieve.
282 |
283 |
286 |
287 | ## Q. How view is related to data independence?
288 |
289 | - View is a virtual table that doesn'\t really exist, but it remains present so that user can view their data.
290 | - It is derived from the base table. The view is stored in the data dictionary and represents the file directly.
291 | - The base table updation or reconstruction is not being reflected in views.
292 | - It is related to the logical data independence as it is at the logical level and not at the physical level.
293 |
294 |
297 |
298 | ## Q. Why E-R models are used?
299 |
300 | E-R model stands for entity-relationship model and it is used to represent a model with their relationships. This is an object oriented approach and it is based on real world that consists of objects which are called entities and relationship between them. Entities are further used inside the database in the form of attributes.
301 |
302 |
305 |
306 | ## Q. What do you understand by cardinality and why it is used?
307 |
308 | - Cardinality is important and used to arrange the data inside the database.
309 | - It is related to the design part and need to be properly used in database.
310 | - It is used in E-R diagrams and used to show the relationship between entities/tables.
311 | - It has many forms like the basic is one to one, which associate one entity with another.
312 | - Second is one to many: which relates one entity with many entities in a table.
313 | - Third is many to many M: N that allows many entities to be related to many more.
314 | - Last is many to one that allows the many entities to be associated with one entity.
315 |
316 |
319 |
320 | ## Q. What is DDL, DML and DCL?
321 |
322 | SQL commands can be divided in three large subgroups.
323 |
324 | 1) DDL: The SQL commands which deals with database schemas and information of how the data will be generated in database are classified as Data Definition Language.
325 | -For example: CREATE TABLE or ALTER TABLE belongs to DDL.
326 |
327 | 2) DML: The SQL commands which deals with data manipulation are classified as Data Manipulation Language.
328 | For example: SELECT, INSERT, etc.
329 |
330 | 3) DCL: The SQL commands which deal with rights and permission over the database are classified as DCL.
331 | For example: GRANT, REVOKE
332 |
333 | ## Q. How to prevent from database SQL Injection?
334 |
335 | SQL Injection is a code-based vulnerability that allows an attacker to read and access sensitive data from the database. Attackers can bypass security measures of applications and use SQL queries to modify, add, update, or delete records in a database.
336 |
337 | **Simple SQL Injection Example:**
338 |
339 | ```sql
340 | SELECT id FROM users WHERE username='username' AND password='password' OR 1=1'
341 | ```
342 |
343 | Because of the **OR 1=1** statement, the **WHERE** clause returns the first **id** from the **users** table no matter what the **username** and **password** are. The first user id in a database is very often the administrator. In this way, the attacker not only bypasses authentication but also gains administrator privileges.
344 |
345 | **Prevent SQL Injections:**
346 |
347 | **1. Continuous Scanning and Penetration Testing:**
348 |
349 | The automated web application scanner has been the best choice to point out vulnerabilities within the web applications for quite some time now. Now, with SQL injections getting smarter in exploiting logical flaws, website security professionals should explore manual testing with the help of a security vendor.
350 |
351 | They can authenticate user inputs against a set of rules for syntax, type, and length. It helps to audit application vulnerabilities discreetly so that you can patch the code before hackers exploit it to their advantage.
352 |
353 | **2. Restrict Privileges:**
354 |
355 | It is more of a database management function, but enforcing specific privileges to specific accounts helps prevent blind SQL injection attacks. Begin with no privileges account and move on to "read-only", "edit", "delete" and similar privilege levels.
356 |
357 | Minimizing privileges to the application will ensure that the attacker, who gets into the database through the application, cannot make unauthorized use of specific data.
358 |
359 | **3. Use Query Parameters:**
360 |
361 | Dynamic queries create a lot of troubles for security professionals. They have to deal with variable vulnerabilities in each application, which only gets graver with updates and changes. It is recommended that you prepare parameterized queries.
362 |
363 | These queries are simple, easy to write, and only pass when each parameter in SQL code is clearly defined. This way, your info is supplied with weapons to differentiate between code and information inputs.
364 |
365 | **4. Instant Protection:**
366 |
367 | A majority of organizations fail the problems like outdated code, scarcity of resources to test and make changes, no knowledge of application security, and frequent updates in the application. For these, web application protection is the best solution.
368 |
369 | A managed web application firewall can be deployed for immediate mitigation of such attacks. It contains custom policies to block any suspicious input and deny information breach instantly. This way, you do not have to manually look for loopholes and mend problems afterward.
370 |
371 |
374 |
375 | ## Q. What are the non standard string types available in SQL?
376 |
377 | Following are Non-Standard string types:
378 |
379 | | Name | Max Length |
380 | |----------|------------|
381 | |TINYTEXT |255 bytes |
382 | |TEXT |65,535 bytes|
383 | |MEDIUMTEXT|16 MB |
384 | |LONGTEXT |4GB |
385 |
386 |
389 |
390 | ## # 2. SQL Data Types
391 |
392 |
393 |
394 | ## Q. What is difference between CHAR and VARCHAR in MySQL?
395 |
396 | Both of them are used for string type data. `char` has fixed length and if the inserted data is less than the defined length, required no. of blank spaces are added as padding. `varchar` has variable length and no padding is used to fill up the left out space. So technically, varchar will save space.
397 |
398 | ## Q. What are the string datatypes in SQL?
399 |
400 | A list of data types used in MySQL database. This is based on MySQL 8.0.
401 |
402 | |Data Types | Description |
403 | |----------------|---------------------------------------|
404 | |CHAR(Size) |It is used to specify a fixed length string that can contain numbers, letters, and special characters. Its size can be 0 to 255 characters. Default is 1.|
405 | |VARCHAR(Size) |It is used to specify a variable length string that can contain numbers, letters, and special characters. Its size can be from 0 to 65535 characters.|
406 | |BINARY(Size) |It is equal to CHAR() but stores binary byte strings. Its size parameter specifies the column length in the bytes. Default is 1.|
407 | |VARBINARY(Size) |It is equal to VARCHAR() but stores binary byte strings. Its size parameter specifies the maximum column length in bytes.|
408 | |TEXT(Size) |It holds a string that can contain a maximum length of 255 characters.|
409 | |TINYTEXT |It holds a string with a maximum length of 255 characters.|
410 | |MEDIUMTEXT |It holds a string with a maximum length of 16,777,215.|
411 | |LONGTEXT |It holds a string with a maximum length of 4,294,967,295 characters.
412 | |ENUM(val1, val2, val3,...)|It is used when a string object having only one value, chosen from a list of possible values. It contains 65535 values in an ENUM list. If you insert a value that is not in the list, a blank value will be inserted.|
413 | |SET( val1,val2,val3,....)|It is used to specify a string that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values at one time in a SET list.|
414 | |BLOB(size) |It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.|
415 |
416 |
419 |
420 | ## Q. What are the differences between the BLOB and TEXT datatypes in MySQL?
421 |
422 | BLOB stands for Binary Large Objects and as its name suggests, it can be used for storing binary data while TEXT is used for storing large number of strings. BLOB can be used to store **binary data** that means we can store pictures, videos, sounds and programs also.
423 |
424 | BLOB values behave like byte string and BLOB does not have a character set. Therefore, comparison and sorting is fully dependent upon numeric values of bytes.
425 |
426 | TEXT values behave like non-binary string or character string. TEXT has a character set and the comparison/ sorting fully depends upon the collection of character set.
427 |
428 | **Creating a table with TEXT data type:**
429 |
430 | ```sql
431 | mysql> create table TextTableDemo ( Address TEXT );
432 |
433 | mysql> DESC TextTableDemo;
434 | ```
435 |
436 | **Creating a table with BLOB type:**
437 |
438 | ```sql
439 | mysql> create table BlobTableDemo ( Images BLOB );
440 |
441 | mysql> desc BlobTableDemo;
442 | ```
443 |
444 |
447 |
448 | ## # 3. SQL Database
449 |
450 |
451 |
452 | #### Q. How to create a database using SQL?
453 |
454 | To create a database using SQL, you can use the `CREATE DATABASE` statement followed by the name of the database you want to create. Here's the basic syntax:
455 |
456 | ```sql
457 | CREATE DATABASE database_name;
458 | ```
459 | For example, if you want to create a database called "mydatabase", you can run the following SQL query:
460 |
461 | ```sql
462 | CREATE DATABASE mydatabase;
463 | ```
464 | Note that depending on your SQL environment, you may need to have appropriate permissions to create a database.
465 |
466 | ## # 4. SQL Table
467 |
468 |
469 |
470 | #### Q. How to create a table in SQL?
471 |
472 | To create a table in SQL, you can use the `CREATE TABLE` statement. The basic syntax for creating a table is as follows:
473 |
474 | ```sql
475 | CREATE TABLE table_name (
476 | column1 datatype constraint,
477 | column2 datatype constraint,
478 | column3 datatype constraint,
479 | ...
480 | columnN datatype constraint
481 | );
482 | ```
483 | Here's a breakdown of the syntax:
484 |
485 | . `CREATE TABLE` is the SQL keyword that specifies you want to create a table.
486 | . `table_name` is the name you want to give to your table.
487 | `(column1, column2, ..., columnN)` is a comma-separated list of column names you want to create in your table.
488 | .`datatype` is the data type you want to assign to each column.
489 | .`constraint` is an optional condition or rule that you want to set on a column.
490 |
491 | For example, if you want to create a simple table with two columns called `users` and `email`, where `users` is of type `VARCHAR(50)` and `email` is of type `VARCHAR(100)`, you can use the following SQL statement:
492 |
493 | ```sql
494 | CREATE TABLE user_info (
495 | users VARCHAR(50),
496 | email VARCHAR(100)
497 | );
498 | ```
499 | Note that different SQL database management systems may have slightly different syntax or rules for creating tables, so it's always a good idea to consult the documentation for the specific database you're using.
500 |
501 | #### Q. What are tables and Fields?
502 |
503 | In a relational database management system (RDBMS), a table is a collection of data organized in rows and columns. Tables are the primary means to store data in a relational database. Each table represents an entity, such as a customer, product, or transaction, and each row in the table represents a single instance or record of that entity. For example, a table named "Customers" might contain fields such as "CustomerID", "FirstName", "LastName", "Address", and "Phone".
504 |
505 | Fields, also known as columns or attributes, are the individual elements of a table that hold specific pieces of data for each row. Each field represents a specific characteristic or property of the entity the table represents. For example, in a table of customers, fields might include "CustomerID", "FirstName", "LastName", "Address", and "Phone". Each row in the table represents a single customer, and each field in that row contains a specific piece of information about that customer, such as their name or address.
506 |
507 | #### Q. How to delete a table in SQL Server?
508 |
509 | To delete a table in SQL Server, you can use the `DROP TABLE` statement. The syntax is as follows:
510 |
511 | ```sql
512 | DROP TABLE table_name;
513 | ```
514 | Here, `table_name` is the name of the table you want to delete.
515 |
516 | For example, to delete a table called "customers", you would use the following SQL statement:
517 |
518 | ```sql
519 | DROP TABLE customers;
520 | ```
521 | Keep in mind that when you delete a table, all the data stored in that table is also deleted, and it cannot be recovered. Therefore, make sure that you have a backup of the table and its data before deleting it.
522 |
523 | #### Q. What is the difference between DELETE TABLE and TRUNCATE TABLE commands?
524 |
525 | DELETE TABLE and TRUNCATE TABLE are both SQL commands used to remove data from a table, but there are differences between them:
526 |
527 | .DELETE TABLE is a DML (Data Manipulation Language) command that removes all rows from a table based on a condition, or removes all rows if no condition is specified. DELETE TABLE is slower than TRUNCATE TABLE because it maintains a transaction log, which can be rolled back in case of errors. DELETE TABLE is useful when you want to remove specific rows from a table.
528 |
529 | .TRUNCATE TABLE is a DDL (Data Definition Language) command that removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is faster than DELETE TABLE because it does not log every row deletion. TRUNCATE TABLE is useful when you want to remove all rows from a table, but preserve the table structure.
530 |
531 | In summary, DELETE TABLE is used to remove specific rows from a table and maintains a transaction log, while TRUNCATE TABLE is used to remove all rows from a table and does not maintain a transaction log.
532 |
533 | #### Q. What is the difference between TRUNCATE and DROP statements?
534 |
535 | TRUNCATE and DROP are both SQL statements used to remove data from a table, but they have different functionalities.
536 |
537 | TRUNCATE TABLE removes all data from the table, but leaves the table structure intact. It is a fast operation because it only deallocates the data pages used by the table, making it more efficient than using DELETE for large tables. However, it cannot be rolled back and it also resets the identity seed value of the table.
538 |
539 | DROP TABLE, on the other hand, removes the entire table along with its structure and data, so it is a more drastic operation than TRUNCATE. It is useful when you want to completely remove a table and all its dependencies from the database. Like TRUNCATE, it cannot be rolled back.
540 |
541 | In summary, TRUNCATE is a faster way to delete data from a table without destroying the table structure, while DROP TABLE is a more drastic way to remove a table and its dependencies from the database.
542 |
543 |
544 | #### Q. How to alter a table schema in SQL Server?
545 |
546 | To alter a table schema in SQL Server, you can use the `ALTER TABLE` statement along with various sub-commands to modify the table structure. Here is the basic syntax:
547 |
548 | ```sql
549 | ALTER TABLE table_name
550 | [ADD | DROP] column_name datatype [NULL | NOT NULL] [DEFAULT default_value]
551 | [ADD | DROP] CONSTRAINT constraint_name constraint_definition
552 | ```
553 |
554 | The `ALTER TABLE `statement allows you to add or remove columns from an existing table, modify the data type or size of an existing column, and add or remove constraints. Here are some examples:
555 |
556 | 1. Add a new column to a table:
557 |
558 | ```sql
559 | ALTER TABLE employees
560 | ADD email VARCHAR(255) NOT NULL;
561 | ```
562 |
563 | 2. Modify the data type of an existing column:
564 |
565 | ```sql
566 | ALTER TABLE employees
567 | ALTER COLUMN birthdate DATE;
568 | ```
569 |
570 | 3. Drop a column from a table:
571 |
572 | ```sql
573 | ALTER TABLE employees
574 | DROP COLUMN email;
575 | ```
576 |
577 | 4. Add a constraint to a table:
578 |
579 | ```sql
580 | ALTER TABLE employees
581 | ADD CONSTRAINT pk_employee PRIMARY KEY (employee_id);
582 | ```
583 |
584 | 5. Drop a constraint from a table:
585 |
586 | ```sql
587 | ALTER TABLE employees
588 | DROP CONSTRAINT pk_employee;
589 | ```
590 | Note that the specific syntax and options available for the `ALTER TABLE` statement may vary depending on the database management system you are using.
591 |
592 | #### Q. What are Heap tables in SQL?
593 |
594 | In SQL Server, a heap table is a table without a clustered index. In other words, it is a table that stores data without any particular order or structure. Instead of using a clustered index, a heap table uses a heap structure to store data.
595 |
596 | When data is inserted into a heap table, it is added to the end of the table, without any specific ordering. When data is queried from a heap table, the SQL Server Database Engine must scan the entire table to find the requested data. This can be slow and inefficient, especially as the table grows larger.
597 |
598 | Heap tables are useful for storing temporary or transient data that does not need to be stored in a specific order or accessed frequently. However, for large, frequently accessed tables, it is generally recommended to use a clustered index to improve performance.
599 |
600 |
601 |
604 |
605 | ## # 5. SQL Select
606 |
607 |
608 |
609 | #### Q. What are query types in a database?
610 |
611 | In a database, there are typically three main types of queries:
612 |
613 | 1. Select Query: This type of query is used to retrieve data from a table or a set of tables. The SELECT statement is used to specify the columns to be retrieved and the table(s) from which to retrieve the data. This type of query is used most frequently in database applications.
614 |
615 | 2. Insert Query: This type of query is used to insert new data into a table. The INSERT statement is used to specify the values to be inserted into each column of the table.
616 |
617 | 3. Update Query: This type of query is used to modify existing data in a table. The UPDATE statement is used to specify which columns to modify and the new values for those columns. The WHERE clause is used to specify which rows to update.
618 |
619 | There are also other types of queries, such as DELETE queries to delete data from a table, and JOIN queries to combine data from multiple tables, but these three are the most fundamental types of queries in a database.
620 |
621 | #### Q. What is the difference between UNION and UNION ALL?
622 |
623 | In SQL, `UNION` and `UNION ALL` are used to combine the results of two or more `SELECT` statements. The main difference between `UNION` and `UNION ALL` is that `UNION` removes any duplicate rows from the final result set, while `UNION` ALL retains all the rows, including duplicates.
624 |
625 | Here's an example to illustrate the difference:
626 |
627 | Suppose you have two tables, Table1 and Table2, with the following data:
628 |
629 | Table1:
630 |
631 | | Column1 | Column2 |
632 | |---------|---------|
633 | | A | 1 |
634 | | B | 2 |
635 | | C | 3 |
636 |
637 | Table2:
638 |
639 | | Column1 | Column2 |
640 | |---------|---------|
641 | | D | 4 |
642 | | B | 2 |
643 | | E | 5 |
644 |
645 | If you run the following `UNION` query:
646 |
647 | ```sql
648 | SELECT * FROM Table1
649 | UNION
650 | SELECT * FROM Table2
651 | ```
652 | The result will be:
653 |
654 | | Column1 | Column2 |
655 | |---------|---------|
656 | | A | 1 |
657 | | B | 2 |
658 | | C | 3 |
659 | | D | 4 |
660 | | E | 5 |
661 |
662 |
663 | Notice that the duplicate row with Column1 = B has been removed from the final result set.
664 |
665 | On the other hand, if you run the following `UNION ALL` query:
666 |
667 | ```sql
668 | SELECT * FROM Table1
669 | UNION ALL
670 | SELECT * FROM Table2
671 | ```
672 | The result will be:
673 |
674 | | Column1 | Column2 |
675 | |---------|---------|
676 | | A | 1 |
677 | | B | 2 |
678 | | C | 3 |
679 | | D | 4 |
680 | | B | 2 |
681 | | E | 5 |
682 |
683 | In this case, the duplicate row with Column1 = B has been retained in the final result set.
684 |
685 |
686 |
689 |
690 | ## Q. What is difference between Correlated subquery and nested subquery?
691 |
692 | **1. Correlated subqueries:**
693 |
694 | Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the outer query.
695 |
696 | A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.
697 |
698 | **Example:**
699 |
700 | ```sql
701 | --- Correlated Subquery
702 | SELECT e.EmpFirstName, e.Salary, e.DeptId
703 | FROM Employee e
704 | WHERE e.Salary = (SELECT max(Salary) FROM Employee ee WHERE ee.DeptId = e.DeptId)
705 | ```
706 |
707 | **2. Nested subqueries:**
708 |
709 | A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one another. A subquery is a SELECT statement that is nested within another SELECT statement and which return intermediate results. SQL executes innermost subquery first, then next level.
710 |
711 | **Example:**
712 |
713 | ```sql
714 | --- Nested Subquery
715 | SELECT EmpFirstName, Salary, DeptId
716 | FROM Employee
717 | WHERE (DeptId, Salary) IN (SELECT DeptId, max(Salary) FROM Employee group by DeptId)
718 | ```
719 |
720 |
723 |
724 | ## Q. Differentiate UNION, MINUS, UNION ALL and INTERSECT?
725 |
726 | - INTERSECT - It will give all the distinct rows from both select queries.
727 | - MINUS - It will give distinct rows returned by the first query but not by the second query.
728 | - UNION - It will give all distinct rows selected by either first query or second query.
729 | - UNION ALL - It will give all rows returned by either query with all duplicate records.
730 |
731 |
734 |
735 | ## Q. Explain SQL Operators?
736 |
737 | |Sl.No|Query | Description |
738 | |-----|------------------------------------------------|---------------------------------------------------|
739 | | 01. |SELECT c1 FROM t1 UNION [ALL] SELECT c1 FROM t2 |Select column c1 from a table named t1 and column c1 from a table named t2 and combine the rows from these two queries |
740 | | 02. |SELECT c1 FROM t1 INTERSECT SELECT c1 FROM t2 |Select column c1 from a table named t1 and column c1 from a table named t2 and return the intersection of two queries |
741 | | 03. |SELECT c1 FROM t1 MINUS SELECT c1 FROM t2 |Select column c1 from a table named t1 and column c1 from a table named t2 and subtract the 2nd result set from the 1st|
742 | | 04. |SELECT c1 FROM t WHERE c1 [NOT] LIKE pattern |Select column c1 from a table named t and query the rows using pattern matching % |
743 | | 05. |SELECT c1 FROM t WHERE c1 [NOT] in test_list |Select column c1 from a table name t and return the rows that are (or are not) in test_list |
744 | | 06. |SELECT c1 FROM t WHERE c1 BETWEEN min AND max |Select column c1 from a table named t and return the rows where c1 is between min and max|
745 | | 07. |SELECT c1 FROM t WHERE c1 IS [NOT] NULL|Select column c1 from a table named t and check if the values are NULL or not |
746 |
747 |
750 |
751 | #### Q. Explain correlated query work?
752 | #### Q. What is the SQL CASE statement used for?
753 |
754 | *ToDo*
755 |
756 | ## # 6. SQL Clause
757 |
758 |
759 |
760 | ## Q. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
761 |
762 | *ToDo*
763 |
764 |
767 |
768 | ## # 7. SQL Order By
769 |
770 |
771 |
772 |
775 |
776 | ## # 8. SQL Insert
777 |
778 |
779 |
780 |
783 |
784 | ## # 9. SQL Update
785 |
786 |
787 |
788 | ## Q. What are COMMIT and ROLLBACK in SQL?
789 |
790 | **COMMIT** statement is used to end the current transaction and once the COMMIT statement is exceucted the transaction will be permanent and undone.
791 |
792 | **Example:**:
793 |
794 | ```sql
795 | BEGIN
796 | UPDATE EmpDetails SET EmpName = "Arpit" where Dept = "Developer"
797 | COMMIT;
798 | END;
799 | ```
800 |
801 | **ROLLBACK** statement is used to end the current transaction and undone the changes which was made by that transaction.
802 |
803 | **Syntax:** ROLLBACK [TO] Savepoint_name;
804 |
805 | **Example:**:
806 |
807 | ```sql
808 | BEGIN
809 | Statement1;
810 | SAVEPOINT mysavepoint;
811 | BEGIN
812 | Statement2;
813 | EXCEPTION
814 | WHEN OTHERS THEN
815 | ROLLBACK TO mysavepoint;
816 | Statement5;
817 | END;
818 | END;
819 | ```
820 |
821 |
824 |
825 | ## Q. Explain data modification commands in SQL?
826 |
827 | |Sl.No|Query | Description |
828 | |-----|-----------------|---------------------------------------------------|
829 | | 01. |INSERT INTO t(column_list) VALUES(value_list)|Insert one row into a table named t|
830 | | 02. |INSERT INTO t(column_list) VALUES (value_list), (value_list), … |Insert multiple rows into a table named t|
831 | | 03. |INSERT INTO t1(column_list) SELECT column_list FROM t2 |Insert rows from t2 into a table named t1|
832 | | 04. |UPDATE tSET c1 = new_value |Update a new value in table t in the column c1 for all rows|
833 | | 05. |UPDATE tSET c1 = new_value, c2 = new_value WHERE condition|Update values in column c1 and c2 in table t that match the condition|
834 | | 06. |DELETE FROM t |Delete all the rows from a table named t|
835 | | 07. |DELETE FROM tWHERE condition |Delete all rows from that a table named t that match a certain condition|
836 |
837 |
840 |
841 | ## # 10. SQL Delete
842 |
843 |
844 |
845 | ## Q. What is difference between Truncate and Delete in SQL?
846 |
847 | * TRUNCATE is a DDL (data definition language) command whereas DELETE is a DML (data manipulation language) command.
848 | * We can'\t execute a trigger with TRUNCATE whereas with DELETE command, a trigger can be executed.
849 | * We can use any condition in WHERE clause using DELETE but it is not possible with TRUNCATE.
850 | * If table is referenced by any foreign key constraints then TRUNCATE cannot work.
851 | * TRUNCATE is faster than DELETE, because when you use DELETE to delete the data, at that time it store the whole data in rollback space from where you can get the data back after deletion, whereas TRUNCATE will not store data in rollback space and will directly delete it. You can'\t get the deleted data back when you use TRUNCATE.
852 |
853 |
856 |
857 | ## # 11. SQL Keys
858 |
859 |
860 |
861 | ## Q. What is the difference between primary and foreign key?
862 |
863 | * Primary key uniquely identify a relationship in a database, whereas foreign key is the key that is in other relation and it has been referenced from the primary key from other table.
864 |
865 | * Primary key remains one only for the table, whereas there can be more than one foreign key.
866 |
867 | * Primary key is unique and won'\t be shared between many tables, but foreign key will be shared between more than one table and will be used to tell the relationship between them.
868 |
869 |
872 |
873 | #### Q. What is a unique key?
874 | #### Q. What is a foreign key of a database?
875 | #### Q. What is a constraint in SQL?
876 | #### Q. How do I define constraints in SQL?
877 | #### Q. What is a candidate key?
878 | #### Q. What is the default index created on primary key in sql server?
879 |
880 | *ToDo*
881 |
882 |
885 |
886 | ## # 12. SQL Join
887 |
888 |
889 |
890 | ## Q. Explain JOIN Query in mySQL?
891 |
892 | A `JOIN` clause is used to combine rows from two or more tables, based on a related column between them.
893 | Take `users` table and `orders` table for example.
894 |
895 | **Users Table:**
896 |
897 | |user_id|name|mobile|
898 | |---|---|---|
899 | |1|John|123|
900 | |2|Joe|124|
901 |
902 | **Orders Table:**
903 |
904 | |order_id|user_id|total|created_at|
905 | |---|---|---|---|
906 | |1|1|500|2022-12-19 18:32:00|
907 | |2|1|800|2021-12-03 08:32:00|
908 | |3|2|50|2020-12-13 12:49:00|
909 | |4|1|80|2021-12-15 21:19:00|
910 |
911 | So to get the list of orders with names and mobile nos. for each order, we can join `orders` and `users` on the basis of `user_id`.
912 |
913 | ```sql
914 | SELECT
915 | o.*,
916 | u.name,
917 | u.mobile
918 | FROM
919 | ordes o
920 | JOIN users u ON o.user_id = u.user_id;
921 | ```
922 |
923 |
926 |
927 | ## Q. Explain the different types of joins?
928 |
929 | Using Join in a query, we can retrieve referenced columns or rows from multiple tables.
930 |
931 | Following are different types of Joins:
932 |
933 | 1. JOIN: Return details from tables if there is at least one matching row in both tables.
934 | 2. LEFT JOIN: It will return all rows from the left table, even if there are no matching row in the right table.
935 | 3. RIGHT JOIN: It will return all rows from the right table, even if there is no matching row in the left table.
936 | 4. FULL JOIN: It will return rows when there is a match in either of tables.
937 |
938 |
941 |
942 | ## Q. What are Self Join and Cross Join?
943 |
944 | * When we want to join a table to itself then SELF JOIN is used.
945 |
946 | * We can give one or more aliases to eliminate the confusion.
947 |
948 | * A self join can be used as any type, if both the tables are same.
949 |
950 | * The simple example where we can use SELF JOIN is if in a company have a hierarchal reporting structure and an employee reports to another.
951 |
952 | * A cross join give the number of rows in the first table multiplied by the number of rows in second table.
953 |
954 | * The simple example where we can use CROSS JOIJ is if in an organization wants to combine every Employee with family table to see each Employee with each family member.
955 |
956 |
959 |
960 | ## Q. How to query data from multiple tables?
961 |
962 | |Sl.No|Query | Description |
963 | |-----|-----------------|---------------------------------------------------|
964 | | 01. |SELECT c1, c2 FROM t1 INNER JOIN t2 on condition|Select columns c1 and c2 from a table named t1 and perform an inner join between t1 and t2 |
965 | | 02. |SELECT c1, c2 FROM t1 LEFT JOIN t2 on condition|Select columns c1 and c2 from a table named t1 and perform a left join between t1 and t2|
966 | | 03. |SELECT c1, c2 FROM t1 RIGHT JOIN t2 on condition|Select columns c1 and c2 from a table named t1 and perform a right join between t1 and t2|
967 | | 04. |SELECT c1, c2 FROM t1 FULL OUTER JOIN t2 on condition|Select columns c1 and c2 from a table named t1 and perform a full outer join between t1 and t2|
968 | | 05. |SELECT c1, c2 FROM t1 CROSS JOIN t2 |Select columns c1 and c2 from a table named t1 and produce a Cartesian product of rows in tables|
969 | | 06. |SELECT c1, c2 FROM t1, t2 |Select columns c1 and c2 from a table named t1 and produce a Cartesian product of rows in tables|
970 | | 07. |SELECT c1, c2 FROM t1 A INNER JOIN t2 B on condition |Select columns c1 and c2 from a table named t1 and joint it to itself using an INNER JOIN clause|
971 |
972 | ## Q. What is full join in SQL?
973 |
974 | A **FULL JOIN** (or **FULL OUTER JOIN**) in SQL returns all records when there is a match in either the left or right table. It combines the results of both LEFT JOIN and RIGHT JOIN. When there is no match, NULL values are returned for columns from the table that lacks a match.
975 |
976 | Example:
977 | ```sql
978 | SELECT *
979 | FROM TableA
980 | FULL JOIN TableB
981 | ON TableA.id = TableB.id;
982 | ```
983 |
984 | ## Q. What is an outer join in SQL?
985 |
986 | An **OUTER JOIN** in SQL refers to joins that return not only the rows with matching keys in both tables but also the rows with no corresponding key in one of the tables. There are three types of OUTER JOINS:
987 | - **LEFT OUTER JOIN**: Returns all rows from the left table, and the matched rows from the right table. If no match is found, NULL values are returned for columns from the right table.
988 | - **RIGHT OUTER JOIN**: Returns all rows from the right table, and the matched rows from the left table. If no match is found, NULL values are returned for columns from the left table.
989 | - **FULL OUTER JOIN**: Returns all rows when there is a match in either table, filling in NULLs when there are no matches.
990 |
991 | ## Q. What is an inner join in SQL?
992 |
993 | An **INNER JOIN** in SQL returns only the rows where there is a match in both tables. It excludes rows that do not have matching values in both tables.
994 |
995 | Example:
996 | ```sql
997 | SELECT *
998 | FROM TableA
999 | INNER JOIN TableB
1000 | ON TableA.id = TableB.id;
1001 | ```
1002 |
1003 | ## Q. What is left join in SQL Server?
1004 |
1005 | A **LEFT JOIN** (or **LEFT OUTER JOIN**) in SQL Server returns all records from the left table (TableA), and the matched records from the right table (TableB). If there is no match, the result is NULL on the side of the right table.
1006 |
1007 | Example:
1008 | ```sql
1009 | SELECT *
1010 | FROM TableA
1011 | LEFT JOIN TableB
1012 | ON TableA.id = TableB.id;
1013 | ```
1014 |
1015 | ## Q. What is a right join in SQL Server?
1016 |
1017 | A **RIGHT JOIN** (or **RIGHT OUTER JOIN**) in SQL Server returns all records from the right table (TableB), and the matched records from the left table (TableA). If there is no match, the result is NULL on the side of the left table.
1018 |
1019 | Example:
1020 | ```sql
1021 | SELECT *
1022 | FROM TableA
1023 | RIGHT JOIN TableB
1024 | ON TableA.id = TableB.id;
1025 | ```
1026 |
1027 | ## Q. What is the default join in SQL?
1028 |
1029 | The **default join** in SQL is the **INNER JOIN**. When you perform a JOIN without specifying the type, SQL assumes it to be an INNER JOIN, meaning it will only return rows where there is a match in both tables.
1030 |
1031 | Example:
1032 | ```sql
1033 | SELECT *
1034 | FROM TableA
1035 | JOIN TableB
1036 | ON TableA.id = TableB.id;
1037 | ```
1038 |
1039 |
1040 |
1043 |
1044 | ## # 13. SQL RegEx
1045 |
1046 |
1047 |
1048 | ## Q. How to use REGEXP in SQL Query?
1049 |
1050 |
1053 |
1054 | ## # 14. SQL Indexes
1055 |
1056 |
1057 |
1058 | ## Q. What are indexes in a Database?
1059 |
1060 | Indexing is a way to optimize the performance of a database by minimizing the number of disk accesses required when a query is processed. It is a data structure technique which is used to quickly locate and access the data in a database.
1061 |
1062 | Indexes are created using a few database columns
1063 |
1064 | * The first column is the **Search key** that contains a copy of the primary key or candidate key of the table. These values are stored in sorted order so that the corresponding data can be accessed quickly.
1065 |
1066 | * The second column is the **Data Reference** or **Pointer** which contains a set of pointers holding the address of the disk block where that particular key value can be found.
1067 |
1068 | |Sl.No|Query | Description |
1069 | |-----|------------------------------------|---------------------------------------------------|
1070 | | 01. |CREATE INDEX index_name ON t(c1, c2) |Create an index on columns c1 and c2 of the table t |
1071 | | 02. |CREATE UNIQUE INDEX index_name ON t(c3, c4) |Create a unique index on columns c3 and c4 of the table t |
1072 | | 03. |DROP INDEX index_name |Drop an index |
1073 |
1074 | **Example:**
1075 |
1076 | ```sql
1077 | -- Create Index
1078 | CREATE INDEX ON (column1, column2, ...)
1079 |
1080 | -- Show Index
1081 | SHOW INDEX FROM ;
1082 |
1083 | -- Alter Index
1084 | ALTER TABLE ADD INDEX(`column_name`);
1085 |
1086 | -- Drop Index
1087 | DROP INDEX index_name ON ;
1088 | ```
1089 |
1090 |
1093 |
1094 | ## Q. What is an index represent in relational database model?
1095 |
1096 | Index is a way to provide quick access to the data and structure. It has indexes maintain and can be created to combine attributes on a relation. Index allows the queries to filter out the searches faster and matching data can be found earlier with simplicity.
1097 |
1098 | For example: It is same as the book where by using the index you can directly jump to a defined section. In relational database there is a provision to give multiple indexing techniques to optimize the data distribution.
1099 |
1100 |
1103 |
1104 | #### Q. What is the difference between Cluster and Non-Cluster Index?
1105 | #### Q. How to create index in SQL Server?
1106 |
1107 |
1110 |
1111 | ## Q. What are the types of indexes in sql?
1112 |
1113 | **1. Clustered Index:**
1114 |
1115 | Clustered index is the type of indexing that establishes a physical sorting order of rows. Clustered index is like Dictionary; in the dictionary, sorting order is alphabetical and there is no separate index page.
1116 |
1117 | **2. Non-clustered:**
1118 |
1119 | Non-Clustered index is an index structure separate from the data stored in a table that reorders one or more selected columns. The non-clustered index is created to improve the performance of frequently used queries not covered by a clustered index. It\'s like a textbook; the index page is created separately at the beginning of that book.
1120 |
1121 |
1124 |
1125 | ## # 15. SQL Wildcards
1126 |
1127 |
1128 |
1129 | ## Q. What are the ways to use wildcards in sql?
1130 |
1131 |
1134 |
1135 | ## # 16. SQL Date Format
1136 |
1137 |
1138 |
1139 | ## Q. What is difference between timestamp and datetime in SQL?
1140 |
1141 | *ToDo*
1142 |
1143 |
1146 |
1147 | ## # 17. SQL Transactions
1148 |
1149 |
1150 |
1151 | ## Q. What is transactions in SQL?
1152 |
1153 | A SQL transaction is a grouping of one or more SQL statements that interact with a database. A transaction in its entirety can commit to a database as a single logical unit or rollback (become undone) as a single logical unit.
1154 |
1155 | In SQL, transactions are essential for maintaining database integrity. They are used to preserve integrity when multiple related operations are executed concurrently, or when multiple users interact with a database concurrently.
1156 |
1157 | **Properties of Transactions:**
1158 |
1159 | Transactions have the following four standard properties, usually referred to by the acronym ACID.
1160 |
1161 | * **Atomicity** − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state.
1162 |
1163 | * **Consistency** − ensures that the database properly changes states upon a successfully committed transaction.
1164 |
1165 | * **Isolation** − enables transactions to operate independently of and transparent to each other.
1166 |
1167 | * **Durability** − ensures that the result or effect of a committed transaction persists in case of a system failure.
1168 |
1169 | **Transaction Control:**
1170 |
1171 | The following commands are used to control transactions.
1172 |
1173 | * **COMMIT** − to save the changes.
1174 |
1175 | * **ROLLBACK** − to roll back the changes.
1176 |
1177 | * **SAVEPOINT** − creates points within the groups of transactions in which to ROLLBACK.
1178 |
1179 | * **SET TRANSACTION** − Places a name on a transaction.
1180 |
1181 | **Example:**
1182 |
1183 | ```sql
1184 | -- Exmaple - 01
1185 |
1186 | CREATE TABLE widgetInventory (
1187 | id SERIAL,
1188 | description VARCHAR(255),
1189 | onhand INTEGER NOT NULL
1190 | );
1191 |
1192 | CREATE TABLE widgetSales (
1193 | id SERIAL,
1194 | inv_id INTEGER,
1195 | quan INTEGER,
1196 | price INTEGER
1197 | );
1198 |
1199 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'rock', 25 );
1200 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'paper', 25 );
1201 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'scissors', 25 );
1202 |
1203 |
1204 | START TRANSACTION;
1205 | INSERT INTO widgetSales ( inv_id, quan, price ) VALUES ( 1, 5, 500 );
1206 | UPDATE widgetInventory SET onhand = ( onhand - 5 ) WHERE id = 1;
1207 | COMMIT;
1208 |
1209 | SELECT * FROM widgetInventory;
1210 | SELECT * FROM widgetSales;
1211 |
1212 | START TRANSACTION;
1213 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'toy', 25 );
1214 | ROLLBACK;
1215 | SELECT * FROM widgetInventory;
1216 | SELECT * FROM widgetSales;
1217 | ```
1218 |
1219 |
1222 |
1223 | ## Q. What is the purpose of acid properties?
1224 |
1225 | * ACID stands for Atomicity, Consistency, Isolation and durability and it plays an important role in the database.
1226 |
1227 | * These properties allow the database to be more convenient to access and use. This allows data to be shared more safely in between the tables.
1228 |
1229 | * If these properties are not being implemented then the data will become inconsistent and inaccurate.
1230 |
1231 | * It helps in maintaining the accuracy of the data in the database.
1232 |
1233 |
1236 |
1237 | ## Q. What is a NOLOCK?
1238 |
1239 | * NOLOCK is used to improve concurrency on a busy system.
1240 |
1241 | * On data read, no lock can be taken on SELECT statement.
1242 |
1243 | * When some other process is updating the data on the same time you are reading it is known as dirty read.
1244 |
1245 | * Read (Shared) locks are taken by SELECT Statements.
1246 |
1247 | * Simultaneous access of multiple SELECT statements is allowed in Shared lock but modification process is not allowed.
1248 |
1249 | * The result to your system is blocking.
1250 |
1251 | * Update will start on completion of all the reads.
1252 |
1253 |
1256 |
1257 | ## Q. What is a WITH(NOLOCK)?
1258 |
1259 | - WITH(NOLOCK) is used to unlock the data which is locked by the transaction that is not yet committed. This command is used before SELECT statement.
1260 | - When the transaction is committed or rolled back then there is no need to use NOLOCK function because the data is already released by the committed transaction.
1261 | - Syntax: WITH(NOLOCK)
1262 |
1263 | **Example:**:
1264 |
1265 | ```sql
1266 | SELECT * FROM EmpDetails WITH(NOLOCK)
1267 | WITH(NOLCOK) is similar as READ UNCOMMITTED.
1268 | ```
1269 |
1270 |
1273 |
1274 | #### Q. What are different transaction levels in SQL?
1275 | #### Q. What are the different locks in SQL?
1276 |
1277 | *ToDo*
1278 |
1279 |
1282 |
1283 | ## # 18. SQL Functions
1284 |
1285 |
1286 |
1287 | #### Q. What is a function in SQL Server?
1288 | #### Q. What are the different types of functions in SQL Server?
1289 | ## Q. What are the reporting aggregate functions available in SQL?
1290 |
1291 | In database management, an aggregate function is a function where the values of multiples rows are grouped to form a single value.
1292 |
1293 | |Sl.No |Function | Description |
1294 | |------|-----------|---------------------------------------------------|
1295 | | 01. |COUNT |Return the number of rows in a certain table/view |
1296 | | 02. |SUM |Accumulate the values|
1297 | | 03. |AVG |Returns the average for a group of values|
1298 | | 04. |MIN |Returns the smallest value of the group|
1299 | | 05. |MAX |Returns the largest value of the group|
1300 |
1301 | #### Q. What are aggregate and scalar functions?
1302 | #### Q. What are all the Common SQL Function?
1303 |
1304 |
1307 |
1308 | ## # 19. SQL View
1309 |
1310 |
1311 |
1312 | ## Q. What is View in SQL?
1313 |
1314 | A view is a virtual table that is a result of a query. They can be extremely useful and are often used as a security mechanism, letting users access the data through the view, rather than letting them access the underlying base table:
1315 |
1316 | **Syntax:**
1317 |
1318 | ```sql
1319 | CREATE VIEW view_name AS
1320 | SELECT column1, column2, ...
1321 | FROM table_name
1322 | WHERE condition;
1323 | ```
1324 |
1325 | **Example:**
1326 |
1327 | ```sql
1328 | --- Creating a View
1329 |
1330 | CREATE VIEW trackView AS
1331 | SELECT id, album_id, title, track_number, duration DIV 60 AS m, duration MOD 60 AS s
1332 | FROM track;
1333 | SELECT * FROM trackView;
1334 | ```
1335 |
1336 |
1339 |
1340 | ## # 20. SQL Triggers
1341 |
1342 |
1343 |
1344 | ## Q. What are the triggers in SQL?
1345 |
1346 | A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated.
1347 |
1348 | **Syntax:**
1349 |
1350 | ```sql
1351 | CREATE [OR REPLACE ] TRIGGER
1352 | {BEFORE | AFTER | INSTEAD OF }
1353 | {INSERT [OR] | UPDATE [OR] | DELETE}
1354 | ON
1355 | [FOR EACH ROW]
1356 | WHEN (condition)
1357 | [trigger_body]
1358 | ```
1359 |
1360 | **Example - 01:**
1361 |
1362 | ```sql
1363 | CREATE TRIGGER employee_name
1364 | after INSERT
1365 | on
1366 | employee
1367 | for each row
1368 | BEGIN
1369 | UPDATE employee set full_name = first_name || ' ' || last_name;
1370 | END;
1371 | ```
1372 |
1373 |
1376 |
1377 | #### Q. Why and when to use a trigger?
1378 | #### Q. What are the different types of triggers?
1379 | #### Q. How many TRIGGERS are possible in MySql?
1380 |
1381 | *ToDo*
1382 |
1383 |
1386 |
1387 | ## # 21. SQL Cursors
1388 |
1389 |
1390 |
1391 | ## Q. What is a cursor?
1392 |
1393 | When we execute any SQL operations, SQL Server opens a work area in memory which is called Cursor. When it is required to perform the row by row operations which are not possible with the set-based operations then cursor is used.
1394 |
1395 | There are two of cursors:
1396 |
1397 | **1. Implicit Cursor:**
1398 |
1399 | Implicit Cursors are also known as Default Cursors of SQL SERVER. These Cursors are allocated by SQL SERVER when the user performs DML operations.
1400 |
1401 | **2. Explicit Cursor:**
1402 |
1403 | * When the programmer wants to perform the row by row operations for the result set containing more than one row, then he explicitly declare a cursor with a name.
1404 |
1405 | * They are managed by OPEN, FETCH and CLOSE.
1406 |
1407 | * %FOUND, %NOFOUND, %ROWCOUNT and %ISOPEN attributes are used in both types of cursors.
1408 |
1409 | **1. Declare Cursor Object:**
1410 |
1411 | **Syntax:**
1412 |
1413 | ```sql
1414 | --- DECLARE cursor_name CURSOR FOR SELECT * FROM table_name
1415 | DECLARE s1 CURSOR FOR SELECT * FROM studDetails
1416 | ```
1417 |
1418 | **2. Open Cursor Connection:**
1419 |
1420 | ```sql
1421 | -- OPEN cursor_connection
1422 | OPEN s1
1423 | ```
1424 |
1425 | **3. Fetch Data from cursor:**
1426 |
1427 | There are total 6 methods to access data from cursor.
1428 |
1429 | * **FIRST** - is used to fetch only the first row from cursor table.
1430 | * **LAST** - is used to fetch only last row from cursor table.
1431 | * **NEXT** - is used to fetch data in forward direction from cursor table.
1432 | * **PRIOR** - is used to fetch data in backward direction from cursor table.
1433 | * **ABSOLUTE** - n is used to fetch the exact nth row from cursor table.
1434 | * **RELATIVE** - n is used to fetch the data in incremental way as well as decremental way.
1435 |
1436 | ```sql
1437 | FETCH FIRST FROM s1
1438 | FETCH LAST FROM s1
1439 | FETCH NEXT FROM s1
1440 | FETCH PRIOR FROM s1
1441 | FETCH ABSOLUTE 7 FROM s1
1442 | FETCH RELATIVE -2 FROM s1
1443 | ```
1444 |
1445 | **4. Close cursor connection:**
1446 |
1447 | ```sql
1448 | --- CLOSE cursor_name
1449 | CLOSE s1
1450 | ```
1451 |
1452 | **5. Deallocate cursor memory:**
1453 |
1454 | ```sql
1455 | --- DEALLOCATE cursor_name
1456 | DEALLOCATE s1
1457 | ```
1458 |
1459 |
1462 |
1463 | ## Q. When is the Explicit Cursor Used?
1464 |
1465 | ## # 22. SQL Stored Procedures
1466 |
1467 |
1468 |
1469 | ## Q. Why stored procedures are called as executable code?
1470 |
1471 | Stored procedure stored inside the database. This also includes the executable code that usually collects and customizes the operations like insert, encapsulation, etc. These stored procedures are used as APIs for simplicity and security purposes. The implementation of it allows the developers to have procedural extensions to the standard SQL syntax. Stored procedure doesn'\t come as a part of relational database model, but can be included in many implementations commercially.
1472 |
1473 |
1476 |
1477 | ## Q. What are the advantages of using Stored Procedures?
1478 |
1479 | - Procedure can reduce network traffic and latency, and can enhance application performance.
1480 | - Procedure execution plans can be reused, staying cached in the management tool's memory, reducing its overhead.
1481 | - Procedures provide the benefit of code reuse.
1482 | - The logic can be encapsulated using procedures and can help to change procedure's code without interacting to application.
1483 | - Procedures give more security to our data.
1484 |
1485 |
1488 |
1489 | ## Q. What is stored procedure in SQL?
1490 |
1491 | Stored Procedures are created to perform one or more DML operations on Database. It is nothing but the group of SQL statements that accepts some input in the form of parameters and performs some task and may or may not returns a value.
1492 |
1493 | **Syntax:**
1494 |
1495 | ```sql
1496 | CREATE or REPLACE PROCEDURE name(parameters)
1497 | IS
1498 | variables;
1499 | BEGIN
1500 | //statements;
1501 | END;
1502 | ```
1503 |
1504 | **Example:**
1505 |
1506 | ```sql
1507 | CREATE PROCEDURE SelectAllCustomers
1508 | AS
1509 | SELECT * FROM Customers
1510 | GO;
1511 | ```
1512 |
1513 | Execute the stored procedure above as follows:
1514 |
1515 | ```sql
1516 | EXEC SelectAllCustomers;
1517 | ```
1518 |
1519 |
1522 |
1523 | ## Q. What is Stored Routine in SQL?
1524 |
1525 | A stored routine is a set of SQL statements that are stored on the database server and can be used by any client
1526 | with permission to use them. This provides a number of benefits.
1527 |
1528 | 1. Database operations are normalized so various applications will operate uniformly, even when written in different
1529 | languages and operating on different platforms.
1530 | 2. Stored routines are easy to maintain, because they're all in one place rather than distributed among different applications.
1531 | 3. Traffic is reduced between the client and server, because data is processed on the server.
1532 | 4. security is enhanced by allowing clients to run with reduced permissions while still being able to perform necessary
1533 | database operations.
1534 |
1535 | There are two different kinds of stored routines.
1536 |
1537 | a) Stored functions return a value, and are used in the context of an expression.
1538 | b) Stored procedures are called separately, using the call statement, and may return result sets or set variables.
1539 |
1540 | **Example 01:** Stored Functions
1541 |
1542 | ```sql
1543 | DROP FUNCTION IF EXISTS track_len;
1544 |
1545 | CREATE FUNCTION track_len(seconds INT)
1546 | RETURNS VARCHAR(16) DETERMINISTIC
1547 | RETURN CONCAT_WS(':', seconds DIV 60, LPAD(seconds MOD 60, 2, '0' ));
1548 |
1549 | SELECT title, track_len(duration) FROM track;
1550 |
1551 | SELECT a.artist AS artist,
1552 | a.title AS album,
1553 | t.title AS track,
1554 | t.track_number AS trackno,
1555 | track_len(t.duration) AS length
1556 | FROM track AS t
1557 | JOIN album AS a
1558 | ON a.id = t.album_id
1559 | ORDER BY artist, album, trackno
1560 | ;
1561 | ```
1562 |
1563 | **Example 02:** Stored Procedures
1564 |
1565 | ```sql
1566 | DROP PROCEDURE IF EXISTS list_albums;
1567 |
1568 | DELIMITER //
1569 | CREATE PROCEDURE list_albums ()
1570 | BEGIN
1571 | SELECT * FROM album;
1572 | END
1573 | //
1574 |
1575 | DELIMITER ;
1576 | CALL list_albums();
1577 | ```
1578 |
1579 | **Example 03:** Stored Procedures with parameter
1580 |
1581 | ```sql
1582 | DROP PROCEDURE IF EXISTS list_albums;
1583 |
1584 | DELIMITER //
1585 | CREATE PROCEDURE list_albums (a VARCHAR(255))
1586 | BEGIN
1587 | SELECT a.artist AS artist,
1588 | a.title AS album,
1589 | t.title AS track,
1590 | t.track_number AS trackno,
1591 | track_len(t.duration) AS length
1592 | FROM track AS t
1593 | JOIN album AS a
1594 | ON a.id = t.album_id
1595 | WHERE a.artist LIKE a
1596 | ORDER BY artist, album, trackno
1597 | ;
1598 | END //
1599 |
1600 | DELIMITER ;
1601 | CALL list_albums('%hendrix%');
1602 | ```
1603 |
1604 | **Example 04:** Drop Stored Procedures & Stored Functions
1605 |
1606 | ```sql
1607 | DROP FUNCTION IF EXISTS track_len;
1608 | DROP PROCEDURE IF EXISTS total_duration;
1609 | ```
1610 |
1611 | #### Q. What is the difference between Stored Procedure and User Defined Function?
1612 | #### Q. How can you raise custom errors from stored procedure?
1613 |
1614 |
1617 |
1618 | ## # 23. Miscellaneous
1619 |
1620 |
1621 |
1622 | ## Q. How do you find third highest salary
1623 |
1624 | ```sql
1625 | SELECT * from employees order by salary limit 2,1;
1626 | ```
1627 |
1628 |
1631 |
1632 | ## Q. What is the STUFF function and how does it differ from the REPLACE function?
1633 |
1634 | - Using STUFF function we can overwrite the specified characters of a string.
1635 | The syntax of STUFF function is:
1636 | STUFF (stringToChange, startIndex, length, new_characters )
1637 |
1638 | where stringToChange is the string which will have the characters those we want to overwrite, startIndex is the starting position, length is the number of characters in the string that are to be overwrited, and new_characters are the new characters to write into the string.
1639 |
1640 | - While REPLACE function is used to replace specified character at all its existing occurrences.
1641 | - The syntax of REPLACE function is REPLACE (string_to_change, string_to_Replace, new_tring).
1642 | - Every occurrence of string_to_change will be replaced by new_string.
1643 |
1644 |
1647 |
1648 | ## Q. What is RANK function?
1649 |
1650 | - RANK function can be used to give a rank to each row returned from a SELECT statment.
1651 | - For using this function first specify the function name, followed by the empty parentheses.
1652 | - Then mention the OVER function. For this function, you have to pass an ORDER BY clause as an argument. The clause identifies the column on which you are going to apply the RANK function.
1653 |
1654 | For Example:
1655 | SELECT RANK() OVER(ORDER BY BirthDate DESC) AS [RowNumber], FirstName, BirthDate FROM EmpDetails
1656 | - In the result you will see that the eldest employee got the first rank and the youngest employee got the last rank. Here the rows with equal age will get same ranks.
1657 | - The rank depends on the row's position in the result set, but not on the sequential number of the row.
1658 |
1659 |
1662 |
1663 | ## Q. What are the reasons of poor performance of query?
1664 |
1665 | Following are the reasons for the poor performance of a query:
1666 |
1667 | * No indexes.
1668 | * Excess recompilations of stored procedures.
1669 | * Procedures and triggers without SET NOCOUNT ON.
1670 | * Poorly written query with unnecessarily complicated joins.
1671 | * Highly normalized database design.
1672 | * Excess usage of cursors and temporary tables.
1673 | * Queries with predicates that use comparison operators between different columns of the same table.
1674 | * Queries with predicates that use operators, and any one of the following are true:
1675 | * There are no statistics on the columns involved on either side of the operators.
1676 | * The distribution of values in the statistics is not uniform, but the query seeks a highly selective value set. This situation can be especially true if the operator is anything other than the equality (=) operator.
1677 | * The predicate uses the not equal to (!=) comparison operator or the NOT logical operator.
1678 | * Queries that use any of the SQL Server built-in functions or a scalar-valued, user-defined function whose argument is not a constant value.
1679 | * Queries that involve joining columns through arithmetic or string concatenation operators.
1680 | * Queries that compare variables whose values are not known when the query is compiled and optimized.
1681 |
1682 |
1685 |
1686 | ## Q. What are the MySQL Engines?
1687 |
1688 | **1. InnoDB:**
1689 |
1690 | The default storage engine in MySQL 8.0. InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL
1691 | that has commit, rollback, and crash-recovery capabilities to protect user data. InnoDB row-level locking
1692 | (without escalation to coarser granularity locks) and Oracle-style consistent nonlocking reads increase multi-user
1693 | concurrency and performance. InnoDB stores user data in clustered indexes to reduce I/O for common queries based on primary keys.
1694 |
1695 | To maintain data integrity, InnoDB also supports FOREIGN KEY referential-integrity constraints.
1696 |
1697 | **2. MyISAM:**
1698 |
1699 | These tables have a small footprint. Table-level locking limits the performance in read/write workloads, so it is often used in read-only or read-mostly workloads in Web and data warehousing configurations.
1700 |
1701 | **3. Memory:**
1702 |
1703 | Stores all data in RAM, for fast access in environments that require quick lookups of non-critical data. This engine
1704 | was formerly known as the HEAP engine. Its use cases are decreasing; InnoDB with its buffer pool memory area provides a
1705 | general-purpose and durable way to keep most or all data in memory, and NDBCLUSTER provides fast key-value lookups for huge distributed data sets.
1706 |
1707 | **4. CSV:**
1708 |
1709 | Its tables are really text files with comma-separated values. CSV tables let you import or dump data in CSV format, to exchange data with scripts and applications that read and write that same format. Because CSV tables are not indexed, you typically keep the data in InnoDB tables during normal operation, and only use CSV tables during the import or export stage.
1710 |
1711 | **5. Archive:**
1712 |
1713 | These compact, unindexed tables are intended for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information.
1714 |
1715 | **6. Blackhole:**
1716 |
1717 | The Blackhole storage engine accepts but does not store data, similar to the Unix /dev/null device. Queries always return an empty set. These tables can be used in replication configurations where DML statements are sent to slave servers, but the master server does not keep its own copy of the data.
1718 |
1719 | **7. NDB:**
1720 |
1721 | This clustered database engine is particularly suited for applications that require the highest possible degree
1722 | of uptime and availability.
1723 |
1724 | **8. Merge:**
1725 |
1726 | Enables a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as one object. Good for VLDB environments such as data warehousing.
1727 |
1728 | **9. Federated:**
1729 |
1730 | Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very good for distributed or data mart environments.
1731 |
1732 | **10. Example:**
1733 |
1734 | This engine serves as an example in the MySQL source code that illustrates how to begin writing new storage engines.
1735 | It is primarily of interest to developers. The storage engine is a “stub” that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them.
1736 |
1737 |
1740 |
1741 | #### Q. How to find the unique values if the value in the column is repeated?
1742 | #### Q. How to test performance of database?
1743 | #### Q. What is SQL Profiler?
1744 | #### Q. How to get @@ERROR and @@ROWCOUNT at the same time?
1745 | #### Q. Explain about buffer cash and log Cache in SQL Server?
1746 |
1747 |
1750 |
--------------------------------------------------------------------------------
/Schemas.sql:
--------------------------------------------------------------------------------
1 |
2 | CREATE TABLE Employee (
3 | EMPLOYEE_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
4 | FIRST_NAME CHAR(25),
5 | LAST_NAME CHAR(25),
6 | SALARY INT(15),
7 | JOINING_DATE DATETIME,
8 | DEPARTMENT CHAR(25),
9 | MANAGER_ID INT
10 | );
11 |
12 | INSERT INTO Employee
13 | (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT,MANAGER_ID) VALUES
14 | (001, 'James', 'Smith', 100000, '17-02-20 09.00.00', 'HR', 002),
15 | (002, 'Jessica', 'Kohl', 80000, '17-06-11 09.00.00', 'Admin', 005),
16 | (003, 'Alex', 'Garner', 300000, '17-02-20 09.00.00', 'HR', 011),
17 | (004, 'Pratik', 'Pandey', 500000, '17-02-20 09.00.00', 'Admin', 020),
18 | (005, 'Christine', 'Robinson', 500000, '17-06-11 09.00.00', 'Admin', 007),
19 | (006, 'Deepak', 'Gupta', 200000, '17-06-11 09.00.00', 'Account', 015),
20 | (007, 'Jennifer', 'Paul', 75000, '17-01-20 09.00.00', 'Account', 012),
21 | (008, 'Deepika', 'Sharma', 90000, '17-04-11 09.00.00', 'Admin', 017);
22 |
23 | CREATE TABLE Bonus (
24 | EMPLOYEE_REF_ID INT,
25 | BONUS_AMOUNT INT(10),
26 | BONUS_DATE DATETIME,
27 | FOREIGN KEY (EMPLOYEE_REF_ID)
28 | REFERENCES Employee(EMPLOYEE_ID)
29 | ON DELETE CASCADE
30 | );
31 |
32 | INSERT INTO Bonus
33 | (EMPLOYEE_REF_ID, BONUS_AMOUNT, BONUS_DATE) VALUES
34 | (001, 5000, '18-02-20'),
35 | (002, 3000, '18-06-11'),
36 | (003, 4000, '18-02-20'),
37 | (001, 4500, '18-02-20'),
38 | (002, 3500, '18-06-11');
39 |
40 | CREATE TABLE Title (
41 | EMPLOYEE_REF_ID INT,
42 | EMPLOYEE_TITLE CHAR(25),
43 | AFFECTED_FROM DATETIME,
44 | FOREIGN KEY (EMPLOYEE_REF_ID)
45 | REFERENCES Employee(EMPLOYEE_ID)
46 | ON DELETE CASCADE
47 | );
48 |
49 | INSERT INTO Title
50 | (EMPLOYEE_REF_ID, EMPLOYEE_TITLE, AFFECTED_FROM) VALUES
51 | (001, 'Manager', '2018-02-20 00:00:00'),
52 | (002, 'Executive', '2018-06-11 00:00:00'),
53 | (008, 'Executive', '2018-06-11 00:00:00'),
54 | (005, 'Manager', '2018-06-11 00:00:00'),
55 | (004, 'Asst. Manager', '2018-06-11 00:00:00'),
56 | (007, 'Executive', '2018-06-11 00:00:00'),
57 | (006, 'Lead', '2018-06-11 00:00:00'),
58 | (003, 'Lead', '2018-06-11 00:00:00');
59 |
60 |
61 | CREATE TABLE all_students (
62 | student_id INT NOT NULL PRIMARY KEY,
63 | school_id INT,
64 | grade_level INT,
65 | date_of_birth DATETIME,
66 | hometown CHAR(25)
67 | );
68 | CREATE TABLE attendance_events (
69 | date_event DATETIME,
70 | student_id INT,
71 | attendance CHAR(20),
72 | FOREIGN KEY (student_id)
73 | REFERENCES all_students(student_id)
74 | ON DELETE CASCADE
75 | );
76 |
77 | INSERT INTO attendance_events
78 | (date_event, student_id, attendance) VALUES
79 | ('2018-01-10', 110111, 'present'),
80 | ('2018-01-10', 110121, 'present' ),
81 | ('2018-01-12', 110115, 'absent'),
82 | ('2018-01-13', 110119, 'absent'),
83 | ('2018-01-13', 110121, 'present'),
84 | ('2018-01-14', 110125, 'present'),
85 | ('2018-02-05', 110111, 'absent'),
86 | ('2018-02-17', 110115, 'present'),
87 | ('2018-02-22', 110129, 'absent');
88 |
89 | INSERT INTO all_students
90 | (student_id, school_id, grade_level, date_of_birth, hometown) VALUES
91 | (110111, 205, 1, '2013-01-10', 'Pleasanton'),
92 | (110115, 205, 1, '2013-03-15', 'Dublin'),
93 | (110119, 205, 2, '2012-02-13', 'San Ramon'),
94 | (110121, 205, 3, '2011-01-13', 'Dublin'),
95 | (110125, 205, 2, '2012-04-25','Dublin'),
96 | (110129, 205, 3, '2011-02-22', 'San Ramon');
97 |
98 | CREATE TABLE login_info (
99 | user_id INT,
100 | login_time DATETIME
101 | );
102 |
103 | INSERT INTO login_info
104 | (user_id, login_time) VALUES
105 | (1, '2017-08-10 14:32:25'),
106 | (2, '2017-08-11 14:32:25'),
107 | (3, '2017-08-11 14:32:25'),
108 | (2, '2017-08-13 14:32:25'),
109 | (3, '2017-08-14 14:32:25'),
110 | (4, '2017-08-15 14:32:25'),
111 | (5, '2017-08-12 14:32:25'),
112 | (2, '2017-08-18 14:32:25'),
113 | (1, '2017-08-11 14:32:25'),
114 | (1, '2017-08-12 14:32:25'),
115 | (1, '2017-08-13 14:32:25'),
116 | (1, '2017-08-14 14:32:25'),
117 | (1, '2017-08-15 14:32:25'),
118 | (1, '2017-08-16 14:32:25'),
119 | (1, '2017-08-17 14:32:25'),
120 | (3, '2017-08-20 14:32:25'),
121 | (5, '2017-08-16 14:32:25'),
122 | (2, '2017-08-21 14:32:25'),
123 | (3, '2017-08-22 14:32:25');
124 |
125 | CREATE TABLE USER_ACTION (
126 | user_id_who_sent INT,
127 | user_id_to_whom INT,
128 | date_action DATETIME,
129 | action CHAR(25)
130 | );
131 |
132 | INSERT INTO USER_ACTION
133 | (user_id_who_sent, user_id_to_whom, date_action, action) VALUES
134 | (20251, 28272, '2018-05-24','accepted'),
135 | (19209, 64638,'2018-06-13' , 'sent'),
136 | (43744, 16373, '2018-04-15' ,'accepted'),
137 | (20251, 18171, '2018-05-19' , 'sent'),
138 | (54875, 36363, '2018-01-11' ,'rejected'),
139 | (38292, 16373, '2018-05-24','accepted'),
140 | (19209, 26743, '2018-06-12' ,'accepted'),
141 | (27623, 28272, '2018-05-24','accepted'),
142 | (20251, 37378, '2018-03-17','rejected'),
143 | (43744, 18171, '2018-05-24' ,'accepted');
144 |
145 | CREATE TABLE all_users(
146 | user_id INT NOT NULL PRIMARY KEY,
147 | user_name CHAR(25),
148 | registration_date DATETIME,
149 | active_last_month BOOLEAN
150 | );
151 |
152 | INSERT INTO all_users
153 | (user_id, user_name, registration_date, active_last_month) VALUES
154 | (1, 'sam', '2018-01-21', 1),
155 | (2, 'phelp', '2018-01-15', 1),
156 | (3, 'peyton', '2018-03-12', 1),
157 | (4, 'ryan', '2018-02-17', 0),
158 | (5, 'james', '2018-01-21', 0),
159 | (6, 'christine', '2018-02-27', 1),
160 | (7, 'bolt', '2018-02-28', 0),
161 | (8, 'jessica', '2018-01-11', 1),
162 | (9, 'paul', '2018-04-23', 1),
163 | (10, 'brian', '2018-03-12', 0);
164 |
165 |
166 | CREATE TABLE sport_accounts(
167 | sport_player_id INT,
168 | sport_player CHAR(25),
169 | sport_category CHAR(25),
170 | FOREIGN KEY (sport_player_id)
171 | REFERENCES all_users(user_id)
172 | ON DELETE CASCADE
173 | );
174 |
175 | INSERT INTO sport_accounts
176 | (sport_player_id, sport_player, sport_category) VALUES
177 | (2, 'phelp', 'swimming'),
178 | (7, 'bolt', 'running'),
179 | (8,'jessica', 'swimming'),
180 | (9, 'paul', 'basketball'),
181 | (10, 'brian', 'cricket'),
182 | (5, 'james', 'cricket');
183 |
184 |
185 |
186 | CREATE TABLE follow_relation(
187 | follower_id INT,
188 | target_id INT,
189 | following_date DATETIME,
190 | FOREIGN KEY (follower_id)
191 | REFERENCES all_users(user_id)
192 | ON DELETE CASCADE,
193 | FOREIGN KEY (target_id)
194 | REFERENCES all_users(user_id)
195 | ON DELETE CASCADE
196 | );
197 |
198 | INSERT INTO follow_relation
199 | (follower_id, target_id, following_date) VALUES
200 | (1,8, '2018-01-02'),
201 | (5,2,'2018-01-02'),
202 | (9,10, '2018-01-02'),
203 | (10,8, '2018-01-02'),
204 | (8,3, '2018-01-02'),
205 | (4, 6, '2018-01-02'),
206 | (2,8, '2018-01-02'),
207 | (6,9, '2018-01-02'),
208 | (1,7, '2018-01-02'),
209 | (10,2, '2018-01-02'),
210 | (1,2, '2018-01-02');
211 |
212 | CREATE TABLE ad_accounts(
213 | account_id INT,
214 | date DATETIME,
215 | account_status CHAR(15)
216 | );
217 |
218 | INSERT INTO ad_accounts
219 | (account_id, date, account_status) VALUES
220 | (101, '2019-01-21', 'active'),
221 | (102, '2019-01-17', 'active'),
222 | (117, '2019-02-06', 'active'),
223 | (112, '2019-01-16', 'active'),
224 | (110, '2019-03-22', 'fraud'),
225 | (115, '2019-04-28', 'fraud'),
226 | (103, '2019-02-07', 'close'),
227 | (112, '2019-04-15', 'fraud'),
228 | (101, '2019-04-28', 'fraud'),
229 | (117, '2019-04-22', 'fraud'),
230 | (102, '2019-03-19', 'fraud'),
231 | (106, '2019-04-28', 'fraud'),
232 | (105, '2019-03-02', 'active'),
233 | (110, '2019-04-28', 'fraud');
234 |
235 | CREATE TABLE user_details(
236 | date DATETIME,
237 | session_id INT,
238 | user_id INT
239 | );
240 |
241 | CREATE TABLE event_session_details(
242 | date DATETIME,
243 | session_id INT,
244 | timespend_sec INT,
245 | user_id INT
246 | );
247 |
248 | INSERT INTO user_details
249 | (date, session_id, user_id) values
250 | ('2019-01-10', 201, 6),
251 | ('2019-01-10', 202, 7),
252 | ('2019-01-10', 203, 6),
253 | ('2019-01-11', 204, 8),
254 | ('2019-01-10', 205, 6),
255 | ('2019-01-11', 206, 8),
256 | ('2019-01-12', 207, 9);
257 |
258 | INSERT INTO event_session_details
259 | (date, session_id, timespend_sec, user_id) VALUES
260 | ('2019-01-10', 201, 1200, 6),
261 | ('2019-01-10', 202, 100, 7),
262 | ('2019-01-10', 203, 1500, 6),
263 | ('2019-01-11', 204, 2000, 8),
264 | ('2019-01-10', 205, 1010, 6),
265 | ('2019-01-11', 206, 1780, 8),
266 | ('2019-01-12', 207, 2500, 9),
267 | ('2019-01-12', 208, 500, 9),
268 | ('2019-01-21', 209, 2798, 15),
269 | ('2019-01-25', 210, 1278, 18);
270 |
271 | CREATE TABLE messages_detail(
272 | user_id INT NOT NULL PRIMARY KEY,
273 | messages_sent INT,
274 | date DATE
275 | );
276 |
277 | INSERT INTO messages_detail
278 | (user_id, messages_sent, date) VALUES
279 | (1, 120, '2014-04-27'),
280 | (2,50 , '2014-04-27'),
281 | (3, 222, '2014-04-27'),
282 | (4, 70, '2014-04-27'),
283 | (5, 250, '2014-04-27'),
284 | (6, 246,'2014-04-27'),
285 | (7, 179, '2014-04-27'),
286 | (8, 116, '2014-04-27'),
287 | (9, 84 , '2014-04-27'),
288 | (10, 215,'2014-04-27'),
289 | (11, 105, '2014-04-27'),
290 | (12, 174, '2014-04-27'),
291 | (13, 158, '2014-04-27'),
292 | (14, 30, '2014-04-27'),
293 | (15, 48, '2014-04-27');
294 |
295 | CREATE TABLE user_name (
296 | full_names CHAR(30)
297 | );
298 |
299 | INSERT INTO user_name
300 | (full_names) VALUES
301 | ('Jessica Taylor'),
302 | ('Erin Russell'),
303 | ('Amanda Smith'),
304 | ('Sam Brown'),
305 | ('Robert Kehrer');
306 |
307 |
308 | CREATE TABLE DIALOGLOG(
309 | user_id INT,
310 | app_id CHAR(5),
311 | type CHAR(15),
312 | date TIMESTAMP
313 | );
314 |
315 | INSERT INTO DIALOGLOG
316 | (user_id, app_id, type, date) VALUES
317 | (1, 'a', 'impression', '2019-02-04'),
318 | (2, 'a', 'impression', '2019-02-04'),
319 | (2, 'a', 'click', '2019-02-04'),
320 | (3, 'b', 'impression', '2019-02-04'),
321 | (4, 'c', 'click', '2019-02-04'),
322 | (4, 'd', 'impression', '2019-02-04'),
323 | (5, 'd', 'click', '2019-02-04'),
324 | (6, 'd', 'impression', '2019-02-04'),
325 | (6, 'e', 'impression', '2019-02-04'),
326 | (3, 'a', 'impression', '2019-02-04'),
327 | (3, 'b', 'click', '2019-02-04');
328 |
329 | CREATE TABLE friend_request(
330 | requestor_id INT,
331 | sent_to_id INT,
332 | time DATE
333 | );
334 |
335 | INSERT INTO friend_request
336 | (requestor_id, sent_to_id, time) VALUES
337 | (1, 2, '2018-06-03'),
338 | (1, 3, '2018-06-08'),
339 | (1, 3, '2018-06-08'),
340 | (2, 4, '2018-06-09'),
341 | (3, 4, '2018-06-11'),
342 | (3, 5, '2018-06-11'),
343 | (3, 5, '2018-06-12');
344 |
345 | CREATE TABLE request_accepted(
346 | acceptor_id INT,
347 | requestor_id INT,
348 | time DATE
349 | );
350 |
351 | INSERT INTO request_accepted VALUES
352 | (2, 1, '2018-08-01'),
353 | (3, 1, '2018-08-01'),
354 | (3, 1, '2018-08-01'),
355 | (4, 2, '2018-08-02'),
356 | (5, 3, '2018-08-03'),
357 | (5, 3, '2018-08-03'),
358 | (5, 3, '2018-08-04');
359 |
360 | CREATE TABLE new_request_accepted(
361 | acceptor_id INT,
362 | requestor_id INT,
363 | accept_date DATE
364 | );
365 |
366 | INSERT INTO new_request_accepted
367 | (acceptor_id, requestor_id, accept_date) Values
368 | (2, 1, '2018-05-01'),
369 | (3, 1, '2018-05-02'),
370 | (4, 2, '2018-05-02'),
371 | (5, 3, '2018-05-03'),
372 | (3, 4, '2018-05-04');
373 |
374 | CREATE TABLE count_request(
375 | country_code CHAR(10),
376 | count_of_requests_sent INT,
377 | percent_of_request_sent_failed CHAR(10),
378 | sent_date DATE
379 | );
380 |
381 | INSERT INTO count_request
382 | (country_code, count_of_requests_sent, percent_of_request_sent_failed, sent_date) VALUES
383 | ('AU', 23676, '5.2%', '2018-09-07'),
384 | ('NZ', 12714, '2.1%', '2018-09-08'),
385 | ('IN', 24545, '4.6%', '2018-09-09'),
386 | ('IN', 34353, '5.3%', '2018-09-10'),
387 | ('AU', 24255, '1.7%', '2018-09-11'),
388 | ('NZ', 23131, '2.9%', '2018-09-12'),
389 | ('US', 49894, '5.3%','2018-09-13'),
390 | ('IN', 19374, '2.4%', '2018-09-14'),
391 | ('AU', 18485, '2.7%','2018-09-15'),
392 | ('IN', 38364, '3.5%', '2018-09-16');
393 |
394 |
395 | CREATE TABLE confirmed_no(
396 | phone_number CHAR(15)
397 | );
398 |
399 | INSERT INTO confirmation_no
400 | (phone_number) VALUES
401 | ('232-473-3433'),
402 | ('545-038-2294'),
403 | ('647-294-1837'),
404 | ('492-485-9727'),
405 | ('545-383-7837'),
406 | ('184-483-9575'),
407 | ('493-420-4902'),
408 | ('282-595-8373'),
409 | ('594-9594-2948');
410 |
411 | INSERT INTO confirmed_no
412 | (phone_number) VALUES
413 | ('492-485-9727'),
414 | ('545-383-7837'),
415 | ('184-483-9575'),
416 | ('493-420-4902');
417 |
418 | CREATE TABLE user_interaction(
419 | user_1 CHAR(5),
420 | user_2 CHAR(5),
421 | date DATE
422 | );
423 |
424 | INSERT INTO user_interaction
425 | (user_1, user_2, date) VALUES
426 | ('A', 'B', '2019-03-23'),
427 | ('A', 'C', '2019-03-23'),
428 | ('B', 'D', '2019-03-23'),
429 | ('B', 'F', '2019-03-23'),
430 | ('C', 'D', '2019-03-23'),
431 | ('A', 'D', '2019-03-23'),
432 | ('B','C', '2019-03-23'),
433 | ('A','E', '2019-03-23');
434 |
435 | create table salesperson(
436 | id INT,
437 | name CHAR(25),
438 | age INT,
439 | salary INT
440 | );
441 |
442 | insert into salesperson
443 | (id, name, age, salary) values
444 | (1, 'Abe', 61, 140000),
445 | (2, 'Bob', 34, 44000),
446 | (5, 'Chris', 34, 40000),
447 | (7, 'Dan', 41, 52000),
448 | (8, 'Ken', 57, 115000),
449 | (11, 'Joe', 38, 38000);
450 |
451 | create table customer(
452 | id INT,
453 | name char(25),
454 | city char(25),
455 | industry_type char(1)
456 | );
457 |
458 | insert into customer
459 | (id, name, city, industry_type) values
460 | (4, 'Samsonic', 'pleasant', 'J'),
461 | (6, 'Panasung', 'oaktown', 'J'),
462 | (7, 'Samsony', 'jackson', 'B'),
463 | (9, 'Orange', 'jackson', 'B');
464 |
465 | create table orders(
466 | number int,
467 | order_date date,
468 | cust_id int,
469 | salesperson_id int,
470 | amount int
471 | );
472 |
473 | insert into orders
474 | (number, order_date, cust_id, salesperson_id, amount) values
475 | (10, '1996-02-08', 4, 2, 540),
476 | (20, '1999-01-30', 4, 8, 1800),
477 | (30, '1995-07-14', 9, 1, 460),
478 | (40, '1998-01-29', 7, 2, 2400),
479 | (50, '1998-02-03', 6, 7, 600),
480 | (60, '1998-03-02', 6, 7, 720),
481 | (70, '1998-05-06', 6, 7, 150);
482 |
483 | create table event_log(
484 | user_id INT,
485 | event_date_time INT #Using plain INT column type to store unix timestamp is the most trivial option.
486 | );
487 |
488 | Insert into event_log
489 | (user_id, event_date_time) values
490 | (7494212, 1535308430),
491 | (7494212, 1535308433),
492 | (1475185, 1535308444),
493 | (6946725, 1535308475),
494 | (6946725, 1535308476),
495 | (6946725, 1535308477);
496 |
--------------------------------------------------------------------------------
/assets/data-integrity.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/data-integrity.png
--------------------------------------------------------------------------------
/assets/many-to-many.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/many-to-many.png
--------------------------------------------------------------------------------
/assets/one-to-many.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/one-to-many.png
--------------------------------------------------------------------------------
/assets/one-to-one.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/one-to-one.png
--------------------------------------------------------------------------------
/assets/star.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/star.png
--------------------------------------------------------------------------------
/assets/system-integrity.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/system-integrity.png
--------------------------------------------------------------------------------
/assets/table.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/sql-basics/2e63eaa8ab0fe95c01aad656bc4c047f01a4613e/assets/table.png
--------------------------------------------------------------------------------
/important.md:
--------------------------------------------------------------------------------
1 | # Important SQL Interview Questions
2 |
3 |
4 |
5 | ## Q. What is difference between Correlated subquery and nested subquery?
6 |
7 | **1. Correlated subqueries:**
8 |
9 | Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the outer query.
10 |
11 | A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.
12 |
13 | **Example:**
14 |
15 | ```sql
16 | --- Correlated Subquery
17 | SELECT e.EmpFirstName, e.Salary, e.DeptId
18 | FROM Employee e
19 | WHERE e.Salary = (SELECT max(Salary) FROM Employee ee WHERE ee.DeptId = e.DeptId)
20 | ```
21 |
22 | **2. Nested subqueries:**
23 |
24 | A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one another. A subquery is a SELECT statement that is nested within another SELECT statement and which return intermediate results. SQL executes innermost subquery first, then next level.
25 |
26 | **Example:**
27 |
28 | ```sql
29 | --- Nested Subquery
30 | SELECT EmpFirstName, Salary, DeptId
31 | FROM Employee
32 | WHERE (DeptId, Salary) IN (SELECT DeptId, max(Salary) FROM Employee group by DeptId)
33 | ```
34 |
35 |
38 |
39 | ## Q. What are indexes in a Database?
40 |
41 | Indexing is a way to optimize the performance of a database by minimizing the number of disk accesses required when a query is processed. It is a data structure technique which is used to quickly locate and access the data in a database.
42 |
43 | Indexes are created using a few database columns
44 |
45 | * The first column is the **Search key** that contains a copy of the primary key or candidate key of the table. These values are stored in sorted order so that the corresponding data can be accessed quickly.
46 |
47 | * The second column is the **Data Reference** or **Pointer** which contains a set of pointers holding the address of the disk block where that particular key value can be found.
48 |
49 | |Sl.No|Query | Description |
50 | |-----|------------------------------------|---------------------------------------------------|
51 | | 01. |CREATE INDEX index_name ON t(c1, c2) |Create an index on columns c1 and c2 of the table t |
52 | | 02. |CREATE UNIQUE INDEX index_name ON t(c3, c4) |Create a unique index on columns c3 and c4 of the table t |
53 | | 03. |DROP INDEX index_name |Drop an index |
54 |
55 | **Example:**
56 |
57 | ```sql
58 | -- Create Index
59 | CREATE INDEX ON (column1, column2, ...)
60 |
61 | -- Show Index
62 | SHOW INDEX FROM ;
63 |
64 | -- Alter Index
65 | ALTER TABLE ADD INDEX(`column_name`);
66 |
67 | -- Drop Index
68 | DROP INDEX index_name ON ;
69 | ```
70 |
71 |
74 |
75 | ## Q. What are the types of indexes in sql?
76 |
77 | **1. Clustered Index:**
78 |
79 | Clustered index is the type of indexing that establishes a physical sorting order of rows. Clustered index is like Dictionary; in the dictionary, sorting order is alphabetical and there is no separate index page.
80 |
81 | **2. Non-clustered:**
82 |
83 | Non-Clustered index is an index structure separate from the data stored in a table that reorders one or more selected columns. The non-clustered index is created to improve the performance of frequently used queries not covered by a clustered index. It\'s like a textbook; the index page is created separately at the beginning of that book.
84 |
85 |
88 |
89 | ## Q. What is transactions in SQL?
90 |
91 | A SQL transaction is a grouping of one or more SQL statements that interact with a database. A transaction in its entirety can commit to a database as a single logical unit or rollback (become undone) as a single logical unit.
92 |
93 | In SQL, transactions are essential for maintaining database integrity. They are used to preserve integrity when multiple related operations are executed concurrently, or when multiple users interact with a database concurrently.
94 |
95 | **Properties of Transactions:**
96 |
97 | Transactions have the following four standard properties, usually referred to by the acronym ACID.
98 |
99 | * **Atomicity** − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state.
100 |
101 | * **Consistency** − ensures that the database properly changes states upon a successfully committed transaction.
102 |
103 | * **Isolation** − enables transactions to operate independently of and transparent to each other.
104 |
105 | * **Durability** − ensures that the result or effect of a committed transaction persists in case of a system failure.
106 |
107 | **Transaction Control:**
108 |
109 | The following commands are used to control transactions.
110 |
111 | * **COMMIT** − to save the changes.
112 |
113 | * **ROLLBACK** − to roll back the changes.
114 |
115 | * **SAVEPOINT** − creates points within the groups of transactions in which to ROLLBACK.
116 |
117 | * **SET TRANSACTION** − Places a name on a transaction.
118 |
119 | **Example:**
120 |
121 | ```sql
122 | -- Exmaple - 01
123 |
124 | CREATE TABLE widgetInventory (
125 | id SERIAL,
126 | description VARCHAR(255),
127 | onhand INTEGER NOT NULL
128 | );
129 |
130 | CREATE TABLE widgetSales (
131 | id SERIAL,
132 | inv_id INTEGER,
133 | quan INTEGER,
134 | price INTEGER
135 | );
136 |
137 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'rock', 25 );
138 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'paper', 25 );
139 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'scissors', 25 );
140 |
141 |
142 | START TRANSACTION;
143 | INSERT INTO widgetSales ( inv_id, quan, price ) VALUES ( 1, 5, 500 );
144 | UPDATE widgetInventory SET onhand = ( onhand - 5 ) WHERE id = 1;
145 | COMMIT;
146 |
147 | SELECT * FROM widgetInventory;
148 | SELECT * FROM widgetSales;
149 |
150 | START TRANSACTION;
151 | INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'toy', 25 );
152 | ROLLBACK;
153 | SELECT * FROM widgetInventory;
154 | SELECT * FROM widgetSales;
155 | ```
156 |
157 |
160 |
161 | ## Q. What is Views in SQL?
162 |
163 | A view is a virtual table that is a result of a query. They can be extremely useful and are often used as a security mechanism, letting users access the data through the view, rather than letting them access the underlying base table:
164 |
165 | **Syntax:**
166 |
167 | ```sql
168 | CREATE VIEW view_name AS
169 | SELECT column1, column2, ...
170 | FROM table_name
171 | WHERE condition;
172 | ```
173 |
174 | **Example:**
175 |
176 | ```sql
177 | --- Creating a View
178 |
179 | CREATE VIEW trackView AS
180 | SELECT id, album_id, title, track_number, duration DIV 60 AS m, duration MOD 60 AS s
181 | FROM track;
182 | SELECT * FROM trackView;
183 | ```
184 |
185 |
188 |
189 | ## Q. What are the triggers in SQL?
190 |
191 | A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated.
192 |
193 | **Syntax:**
194 |
195 | ```sql
196 | CREATE [OR REPLACE ] TRIGGER
197 | {BEFORE | AFTER | INSTEAD OF }
198 | {INSERT [OR] | UPDATE [OR] | DELETE}
199 | ON
200 | [FOR EACH ROW]
201 | WHEN (condition)
202 | [trigger_body]
203 | ```
204 |
205 | **Example - 01:**
206 |
207 | ```sql
208 | CREATE TRIGGER employee_name
209 | after INSERT
210 | on
211 | employee
212 | for each row
213 | BEGIN
214 | UPDATE employee set full_name = first_name || ' ' || last_name;
215 | END;
216 | ```
217 |
218 |
221 |
222 | ## Q. What is a cursor?
223 |
224 | When we execute any SQL operations, SQL Server opens a work area in memory which is called Cursor. When it is required to perform the row by row operations which are not possible with the set-based operations then cursor is used.
225 |
226 | There are two of cursors:
227 |
228 | **1. Implicit Cursor:**
229 |
230 | Implicit Cursors are also known as Default Cursors of SQL SERVER. These Cursors are allocated by SQL SERVER when the user performs DML operations.
231 |
232 | **2. Explicit Cursor:**
233 |
234 | * When the programmer wants to perform the row by row operations for the result set containing more than one row, then he explicitly declare a cursor with a name.
235 |
236 | * They are managed by OPEN, FETCH and CLOSE.
237 |
238 | * %FOUND, %NOFOUND, %ROWCOUNT and %ISOPEN attributes are used in both types of cursors.
239 |
240 | **1. Declare Cursor Object:**
241 |
242 | **Syntax:**
243 |
244 | ```sql
245 | --- DECLARE cursor_name CURSOR FOR SELECT * FROM table_name
246 | DECLARE s1 CURSOR FOR SELECT * FROM studDetails
247 | ```
248 |
249 | **2. Open Cursor Connection:**
250 |
251 | ```sql
252 | -- OPEN cursor_connection
253 | OPEN s1
254 | ```
255 |
256 | **3. Fetch Data from cursor:**
257 |
258 | There are total 6 methods to access data from cursor.
259 |
260 | * **FIRST** - is used to fetch only the first row from cursor table.
261 | * **LAST** - is used to fetch only last row from cursor table.
262 | * **NEXT** - is used to fetch data in forward direction from cursor table.
263 | * **PRIOR** - is used to fetch data in backward direction from cursor table.
264 | * **ABSOLUTE** - n is used to fetch the exact nth row from cursor table.
265 | * **RELATIVE** - n is used to fetch the data in incremental way as well as decremental way.
266 |
267 | ```sql
268 | FETCH FIRST FROM s1
269 | FETCH LAST FROM s1
270 | FETCH NEXT FROM s1
271 | FETCH PRIOR FROM s1
272 | FETCH ABSOLUTE 7 FROM s1
273 | FETCH RELATIVE -2 FROM s1
274 | ```
275 |
276 | **4. Close cursor connection:**
277 |
278 | ```sql
279 | --- CLOSE cursor_name
280 | CLOSE s1
281 | ```
282 |
283 | **5. Deallocate cursor memory:**
284 |
285 | ```sql
286 | --- DEALLOCATE cursor_name
287 | DEALLOCATE s1
288 | ```
289 |
290 |
293 |
294 | ## Q. What is stored procedure in SQL?
295 |
296 | Stored Procedures are created to perform one or more DML operations on Database. It is nothing but the group of SQL statements that accepts some input in the form of parameters and performs some task and may or may not returns a value.
297 |
298 | **Syntax:**
299 |
300 | ```sql
301 | CREATE or REPLACE PROCEDURE name(parameters)
302 | IS
303 | variables;
304 | BEGIN
305 | //statements;
306 | END;
307 | ```
308 |
309 | **Example:**
310 |
311 | ```sql
312 | CREATE PROCEDURE SelectAllCustomers
313 | AS
314 | SELECT * FROM Customers
315 | GO;
316 | ```
317 |
318 | Execute the stored procedure above as follows:
319 |
320 | ```sql
321 | EXEC SelectAllCustomers;
322 | ```
323 |
324 |
327 |
--------------------------------------------------------------------------------
/sql-commands.md:
--------------------------------------------------------------------------------
1 | # SQL Commands
2 |
3 | ## ALTER TABLE
4 |
5 | ```sql
6 | ALTER TABLE table_name ADD column datatype;
7 | ```
8 |
9 | `ALTER TABLE` lets you add columns to a table in a database.
10 |
11 |
14 |
15 | ## AND
16 |
17 | ```sql
18 | SELECT column_name(s)
19 | FROM table_name
20 | WHERE column_1 = value_1
21 | AND column_2 = value_2;
22 | ```
23 |
24 | `AND` is an operator that combines two conditions. Both conditions must be true for the row to be included in the result set.
25 |
26 |
29 |
30 | ## AS
31 |
32 | ```sql
33 | SELECT column_name AS 'Alias'
34 | FROM table_name;
35 | ```
36 |
37 | `AS` is a keyword in SQL that allows you to rename a column or table using an *alias*.
38 |
39 |
42 |
43 | ## AVG
44 |
45 | ```sql
46 | SELECT AVG(column_name)
47 | FROM table_name;
48 |
49 | ```
50 |
51 | `AVG()` is an aggregate function that returns the average value for a numeric column.
52 |
53 |
56 |
57 | ## BETWEEN
58 |
59 | ```sql
60 | SELECT column_name(s)
61 | FROM table_name
62 | WHERE column_name BETWEEN value_1 AND value_2;
63 | ```
64 |
65 | The `BETWEEN` operator is used to filter the result set within a certain range. The values can be numbers, text or dates.
66 |
67 |
70 |
71 | ## COUNT
72 |
73 | ```sql
74 | SELECT COUNT(column_name)
75 | FROM table_name;
76 | ```
77 |
78 | `COUNT()` is a function that takes the name of a column as an argument and counts the number of rows where the column is not `NULL`.
79 |
80 |
83 |
84 | ## CREATE TABLE
85 |
86 | ```sql
87 | CREATE TABLE table_name (column_1 datatype, column_2 datatype, column_3 datatype);
88 | ```
89 |
90 | `CREATE TABLE` creates a new table in the database. It allows you to specify the name of the table and the name of each column in the table.
91 |
92 |
95 |
96 | ## DELETE
97 |
98 | ```sql
99 | DELETE FROM table_name WHERE some_column = some_value;
100 | ```
101 |
102 | `DELETE` statements are used to remove rows from a table.
103 |
104 |
107 |
108 | ## GROUP BY
109 |
110 | ```sql
111 | SELECT COUNT(*)
112 | FROM table_name
113 | GROUP BY column_name;
114 | ```
115 |
116 | `GROUP BY` is a clause in SQL that is only used with aggregate functions. It is used in collaboration with the `SELECT` statement to arrange identical data into groups.
117 |
118 |
121 |
122 | ## INNER JOIN
123 |
124 | ```sql
125 | SELECT column_name(s) FROM table_1
126 | JOIN table_2
127 | ON table_1.column_name = table_2.column_name;
128 | ```
129 |
130 | An inner join will combine rows from different tables if the *join condition* is true.
131 |
132 |
135 |
136 | ## INSERT
137 |
138 | ```sql
139 | INSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2', value_3);
140 | ```
141 |
142 | `INSERT` statements are used to add a new row to a table.
143 |
144 |
147 |
148 | ## LIKE
149 |
150 | ```sql
151 | SELECT column_name(s)
152 | FROM table_name
153 | WHERE column_name LIKE pattern;
154 | ```
155 |
156 | `LIKE` is a special operator used with the `WHERE` clause to search for a specific pattern in a column.
157 |
158 |
161 |
162 | ## LIMIT
163 |
164 | ```sql
165 | SELECT column_name(s)
166 | FROM table_name
167 | LIMIT number;
168 | ```
169 |
170 | `LIMIT` is a clause that lets you specify the maximum number of rows the result set will have.
171 |
172 |
175 |
176 | ## MAX
177 |
178 | ```sql
179 | SELECT MAX(column_name)
180 | FROM table_name;
181 | ```
182 |
183 | `MAX()` is a function that takes the name of a column as an argument and returns the largest value in that column.
184 |
185 |
188 |
189 | ## MIN
190 |
191 | ```sql
192 | SELECT MIN(column_name)
193 | FROM table_name;
194 | ```
195 |
196 | `MIN()` is a function that takes the name of a column as an argument and returns the smallest value in that column.
197 |
198 |
201 |
202 | ## OR
203 |
204 | ```sql
205 | SELECT column_name
206 | FROM table_name
207 | WHERE column_name = value_1
208 | OR column_name = value_2;
209 | ```
210 |
211 | `OR` is an operator that filters the result set to only include rows where either condition is true.
212 |
213 |
216 |
217 | ## ORDER BY
218 |
219 | ```sql
220 | SELECT column_name
221 | FROM table_name
222 | ORDER BY column_name ASC|DESC;
223 | ```
224 |
225 | `ORDER BY` is a clause that indicates you want to sort the result set by a particular column either alphabetically or numerically.
226 |
227 |
230 |
231 | ## OUTER JOIN
232 |
233 | ```sql
234 | SELECT column_name(s) FROM table_1
235 | LEFT JOIN table_2
236 | ON table_1.column_name = table_2.column_name;
237 | ```
238 |
239 | An outer join will combine rows from different tables even if the the join condition is not met. Every row in the *left* table is returned in the result set, and if the join condition is not met, then `NULL` values are used to fill in the columns from the *right* table.
240 |
241 |
244 |
245 | ## ROUND
246 |
247 | ```sql
248 | SELECT ROUND(column_name, integer)
249 | FROM table_name;
250 | ```
251 |
252 | `ROUND()` is a function that takes a column name and an integer as an argument. It rounds the values in the column to the number of decimal places specified by the integer.
253 |
254 |
257 |
258 | ## SELECT
259 |
260 | ```sql
261 | SELECT column_name FROM table_name;
262 | ```
263 |
264 | `SELECT` statements are used to fetch data from a database. Every query will begin with SELECT.
265 |
266 |
269 |
270 | ## SELECT DISTINCT
271 |
272 | ```sql
273 | SELECT DISTINCT column_name FROM table_name;
274 | ```
275 |
276 | `SELECT DISTINCT` specifies that the statement is going to be a query that returns unique values in the specified column(s).
277 |
278 |
281 |
282 | ## SUM
283 |
284 | ```sql
285 | SELECT SUM(column_name)
286 | FROM table_name;
287 | ```
288 |
289 | `SUM()` is a function that takes the name of a column as an argument and returns the sum of all the values in that column.
290 |
291 |
294 |
295 | ## UPDATE
296 |
297 | ```sql
298 | UPDATE table_name
299 | SET some_column = some_value
300 | WHERE some_column = some_value;
301 | ```
302 |
303 | `UPDATE` statments allow you to edit rows in a table.
304 |
305 |
308 |
309 | ## WHERE
310 |
311 | ```sql
312 | SELECT column_name(s)
313 | FROM table_name
314 | WHERE column_name operator value;
315 | ```
316 |
317 | `WHERE` is a clause that indicates you want to filter the result set to include only rows where the following *condition* is true.
318 |
319 |
322 |
323 | ## Basic Queries
324 |
325 | **01. Import ".sql" file from command prompt:**
326 |
327 | ```sql
328 | SOURCE C://database.sql;
329 | ```
330 |
331 |
334 |
335 | **02. MySQL Performance Queries:**
336 |
337 | ```sql
338 | OPTIMIZE TABLE table_name;
339 |
340 | --Displays description of the table
341 | SHOW TABLE STATUS;
342 | DESC table_name;
343 | SHOW VARIABLES;
344 | SHOW STATUS;
345 | SHOW GLOBAL STATUS;
346 | SHOW TABLES FROM INFORMATION_SCHEMA;
347 | EXPLAIN SELECT * FROM table_name
348 | SHOW TABLE STATUS FROM database_name;
349 |
350 | --Shows you which threads are running
351 | SHOW FULL PROCESSLIST;
352 |
353 | --IP Address of the Mysql Host
354 | SHOW VARIABLES WHERE Variable_name = 'hostname';
355 | ```
356 |
357 |
360 |
361 | **04. Table Related Queries:**
362 |
363 | ```sql
364 | SELECT max(RIGHT(`field_name`,4)) FROM `table_name`;
365 |
366 | -- Converts to upper case
367 | SELECT UCASE(column_name) FROM table_name;
368 |
369 | --Select nearest value
370 | SELECT * FROM TABLE ORDER BY ABS(VALUE - $MYVALUE) LIMIT 1
371 | SELECT sentence, wordcount(sentence) as "Words" from test;
372 |
373 | --Useful in pagination
374 | SELECT * FROM table_name ORDER BY field_name LIMIT 5 OFFSET 5;
375 |
376 | --Find duplicate entries
377 | SELECT *, COUNT(field_name) FROM table_name GROUP BY field_name HAVING ( COUNT(field_name) > 1 )
378 |
379 | ALTER TABLE table_name AUTO_INCREMENT =1
380 | ALTER TABLE `table_name` DROP PRIMARY KEY
381 | ALTER TABLE `table_name` ENGINE = InnoDB
382 | ALTER TABLE table_name CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT
383 | ALTER TABLE `table_name` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
384 | ALTER TABLE table_name ADD column_name datatype AFTER column_name
385 | ALTER TABLE table_name DROP COLUMN column_name
386 | ALTER TABLE table_name MODIFY column_name datatype
387 | ALTER TABLE table_name CHANGE oldname newname datatype
388 |
389 | RENAME TABLE `table_name_old` TO `table_name_new`
390 |
391 | --Update particular character
392 | UPDATE mytable SET city = REPLACE(city, 'ï', 'i')
393 |
394 | --Swaping field value
395 | UPDATE swap_test SET x=y, y=@temp where @temp:=x;
396 |
397 | --COPYING
398 | UPDATE table_name SET field_name1=field_name2;
399 | UPDATE table_name SET field_name = UPPER(field_name)
400 |
401 | TRUNCATE TABLE table_name;
402 | DROP TABLE table_name;
403 | ```
404 |
405 |
408 |
409 | **05. Date and time:**
410 |
411 | ```sql
412 | SHOW VARIABLE LIKE '%time_zone%';
413 |
414 | --Current timestamp
415 | SELECT NOW();
416 |
417 | --Current day
418 | SELECT DAYNAME(NOW());
419 |
420 | --Subtract time
421 | SELECT SUBTIME('1:30:00', '00:15:00');
422 |
423 | --Date Format
424 | SELECT DATE_FORMAT(NOW(), '%W, %D of %M, %Y');
425 | SELECT TIMEDIFF('2007-10-05 12:10:18','2007-10-05 16:14:59') AS length;
426 | SELECT * FROM `table_name` WHERE DATE_FORMAT(field_name, "%Y-%m-%d") = '2010-01-01'"
427 | ```
428 |
429 |
432 |
433 | **06. MySQL Miscellaneous Queries:**
434 |
435 | ```sql
436 | --Use to generate unique id
437 | SELECT uuid();
438 |
439 | --Get numeric values
440 | SELECT * FROM `TABLENAME` WHERE `field` REGEXP '^-?[0-9]+$'
441 |
442 | --w3resource.com
443 | SELECT CONCAT('w3resource','.','com');
444 |
445 | --bit datatype
446 | CREATE TABLE table_bit (id SERIAL, a BIT(3), b BIT(8), c BIT(16));
447 |
448 | --Enum datatype
449 | CREATE TABLE table_enum (id SERIAL, status ENUM('Active', 'Deactive'));
450 |
451 | --Get the length
452 | SELECT CHAR_LENGTH(field_name) AS Length FROM `table_name`;
453 | SELECT * FROM `table_name` WHERE LENGTH(field_name) < 10
454 |
455 | --Copying the previous rows to the next rows
456 | INSERT INTO table_name (`col1`, `col2`, `col3`, `...`, `coln`) SELECT `col1`, `col2`, `col3`, `...`, `coln` FROM table_name
457 | SELECT COUNT(DISTINCT column) FROM table;
458 | SELECT field_name, LEFT(field_name, 3), RIGHT(field_name, 3), MID(field_name, 2, 3) FROM `table_name`;
459 |
460 | --Flow control with CASE
461 | SELECT CASE WHEN a THEN 'true' ELSE 'false' END AS boolA, CASE WHEN b THEN 'true' ELSE 'false' END AS boolB FROM table_name;
462 | ```
463 |
464 |
467 |
--------------------------------------------------------------------------------
/sql-query-practice.md:
--------------------------------------------------------------------------------
1 | # SQL Query Practice
2 |
3 | ## Q. Write a SQL Query to remove duplicates from Table?
4 |
5 | ```sql
6 | Input:
7 |
8 | CREATE TABLE Employee
9 | (
10 | [ID] INT identity(1, 1),
11 | [FirstName] Varchar(100),
12 | [LastName] Varchar(100),
13 | [Country] Varchar(100),
14 | )
15 | GO
16 |
17 | Insert into Employee ([FirstName], [LastName], [Country] ) values
18 | ('Raj','Gupta','India'),
19 | ('Raj','Gupta','India'),
20 | ('Mohan','Kumar','USA'),
21 | ('James','Barry','UK'),
22 | ('James','Barry','UK'),
23 | ('James','Barry','UK')
24 | ```
25 |
26 | Answer
27 |
28 | ```sql
29 | -- SQL delete duplicate Rows using Group By and having clause
30 | SELECT [FirstName],
31 | [LastName],
32 | [Country],
33 | COUNT(*) AS CNT
34 | FROM [SampleDB].[dbo].[Employee]
35 | GROUP BY [FirstName],
36 | [LastName],
37 | [Country]
38 | HAVING COUNT(*) > 1;
39 | ```
40 |
41 |
42 |
43 |
46 |
47 | ## Q. Write a SQL query to find the 3th highest salary from employee table?
48 |
49 | ```js
50 | Input: 100, 90, 90, 80, 80, 75
51 | Output: 80
52 | ```
53 |
54 | Answer
55 |
56 | ```sql
57 | -- Return 3rd highest salary with distincation. Limiting to 1 result.
58 | SELECT *
59 | FROM `employee`
60 | WHERE
61 | `Salary` = (SELECT DISTINCT `Salary`
62 | FROM `employee`
63 | ORDER BY `salary` DESC
64 | LIMIT 1 OFFSET 2
65 | )
66 | LIMIT 1
67 | ;
68 | ```
69 |
70 | **⚝ [Try this example on DB Fiddle](https://www.db-fiddle.com/f/kypbSttwBuXHzC7AFEfmMJ/1)**
71 |
72 |
73 |
74 |
77 |
78 | ## Q. SQL queries
79 |
80 | ```sql
81 | -- 2> Write a SQL query to find top n records?
82 | -- Example: finding top 5 records from employee table
83 | select * from employee order by salary desc limit 5;
84 |
85 | -- 3> Write a SQL query to find the count of employees working in department 'Admin'
86 | select count(*) from employee where department = 'Admin';
87 |
88 | -- 4> Write a SQL query to fetch department wise count employees sorted by department count in desc order.
89 | select * from employee;
90 |
91 | select department, count(*) as employeecount
92 | from employee
93 | group by department
94 | order by employeecount desc;
95 |
96 | -- 5> Write a query to fetch only the first name(string before space) from the FullName column of user_name table.
97 | select distinct(substring_index(full_names, ' ', 1)) first_name from user_name;
98 |
99 | -- 6> Write a SQL query to find all the employees from employee table who are also managers
100 | select e1.first_name, e2.last_name from employee e1
101 | join employee e2
102 | on e1.employee_id = e2.manager_id;
103 |
104 | -- 7> Write a SQL query to find all employees who have bonus record in bonus table
105 | select * from employee;
106 | select * from bonus;
107 |
108 | select * from employee where employee_id in (select employee_ref_id from bonus where employee.employee_id = bonus.employee_ref_id);
109 | -- This can also be used using left join.
110 | select e.* from employee e join bonus b on e.employee_id = b.employee_ref_id;
111 |
112 | -- 8> Write a SQL query to find only odd rows from employee table
113 | select * from employee where MOD(employee_id,2)<>0;
114 |
115 | -- 9> Write a SQL query to fetch first_name from employee table in upper case
116 | select upper(first_name) as First_Name from employee;
117 |
118 | -- 10> Write a SQL query to get combine name (first name and last name) of employees from employee table
119 | select concat(first_name, ' ' ,last_name) as Name from employee;
120 |
121 | -- 11> Write a SQL query to print details of employee of employee 'Jennifer' and 'James'.
122 | select * from employee where first_name in ('Jennifer', 'James');
123 |
124 | -- 12> Write a SQL query to fetch records of employee whose salary lies between
125 | select first_name, last_name, salary from employee where salary between 100000 and 500000;
126 |
127 | -- 13> Write a SQL query to get records of employe who have joined in Jan 2017
128 | select * from employee;
129 |
130 | select first_name, last_name, joining_date from employee where year(joining_date)=2017 and month(joining_date) = 1;
131 | -- incase you have an index on the joining_date column, it will not be used as index is not used when the indexed column is used in a function.
132 | -- So, prefer this query instead which will use a range scan.
133 | select first_name, last_name, joining_date from employee where joining_date between '2017-01-01' and '2017-02-01';
134 |
135 | -- 14> Write a SQL query to get the list of employees with the same salary
136 | select e1.first_name, e2.last_name from employee e1, employee e2 where e1.salary = e2.salary and e1.employee_id != e2.employee_id;
137 |
138 | -- 15> Write a SQL query to show all departments along with the number of people working there.
139 | select * from employee;
140 |
141 | select department, count(*) as 'Number of employees' from employee
142 | group by department
143 | order by count(department);
144 |
145 | -- 16> Write a SQL query to show the last record from a table.
146 | select * from employee where employee_id = (select max(employee_id) from employee);
147 |
148 | -- 17> Write a SQL query to show the first record from a table.
149 | select * from employee where employee_id = (select min(employee_id) from employee);
150 |
151 | -- 18> Write a SQL query to get last five records from a employee table.
152 | (select * from employee order by employee_id desc limit 5) order by employee_id;
153 |
154 | -- 19> Write a SQL query to find employees having the highest salary in each department.
155 | select first_name, last_name, department, max(salary) as 'Max Salary'from employee group by department order by max(salary);
156 |
157 | -- 20> Write a SQL query to fetch three max salaries from employee table.
158 | select distinct salary from employee order by salary desc limit 3 ;
159 | -- OR-----
160 | select distinct Salary from employee e1 WHERE 3 >= (SELECT count(distinct Salary) from employee e2 WHERE e1.Salary <= e2.Salary) order by e1.Salary desc;
161 |
162 | -- 21> Write a SQL query to fetch departments along with the total salaries paid for each of them.
163 | select department, sum(salary) as 'Total Salary' from employee group by department order by sum(salary);
164 |
165 | -- 22> Write a SQL query to find employee with highest salary in an organization from employee table.
166 | select first_name, last_name from employee where salary = (select max(salary) from employee);
167 |
168 | -- 23> Write an SQL query that makes recommendations using the pages that your friends liked.
169 | -- Assume you have two tables: a two-column table of users and their friends, and a two-column table of
170 | -- users and the pages they liked. It should not recommend pages you already like.
171 |
172 | -- 24> write a SQL query to find employee (first name, last name, department and bonus) with highest bonus.
173 | select first_name, last_name, department, max(bonus_amount) from employee e
174 | join bonus b
175 | on e.employee_id = b.employee_ref_id
176 | group by department
177 | order by max(bonus_amount) desc limit 1;
178 |
179 | -- 25> write a SQL query to find employees with same salary
180 | select e1.first_name, e1.last_name, e1.salary from employee e1, employee e2
181 | where e1.salary = e2.salary
182 | and e1.employee_id != e2.employee_id;
183 |
184 | -- 26> Write SQL to find out what percent of students attend school on their birthday from attendance_events and all_students tables?
185 | select * from all_students;
186 | select * from attendance_events;
187 |
188 | select (count(attendance_events.student_id) * 100 / (select count(student_id) from attendance_events)) as Percent
189 | from attendance_events
190 | join all_students
191 | on all_students.student_id = attendance_events.student_id
192 | where month(attendance_events.date_event) = month(all_students.date_of_birth)
193 | and day(attendance_events.date_event) = day(all_students.date_of_birth);
194 |
195 | -- 27> Given timestamps of logins, figure out how many people on Facebook were active all seven days
196 | -- of a week on a mobile phone from login info table?
197 |
198 | select * from login_info;
199 |
200 | select a.login_time, count(distinct a.user_id) from
201 | login_info a
202 | Left join login_info b
203 | on a.user_id = b.user_id
204 | where a.login_time = b.login_time - interval 1 day
205 | group by 1;
206 |
207 | -- 28> Write a SQL query to find out the overall friend acceptance rate for a given date from user_action table.
208 | select * from user_action;
209 |
210 | select count(a.user_id_who_sent)*100 / (select count(user_id_who_sent) from user_action) as percent
211 | from user_action a
212 | join user_action b
213 | on a.user_id_who_sent = b.user_id_who_sent and a.user_id_to_whom = b.user_id_to_whom
214 | where a.date_action = '2018-05-24' and b.action = "accepted";
215 |
216 | -- 29> How many total users follow sport accounts from tables all_users, sport_accounts, follow_relation?
217 | select * from all_users;
218 | select * from sport_accounts;
219 | select * from follow_relation;
220 |
221 | select count(distinct c.follower_id) as count_all_sports_followers
222 | from sport_accounts a
223 | join all_users b
224 | on a.sport_player_id = b.user_id
225 | join follow_relation c
226 | on b.user_id = c.target_id;
227 |
228 | -- 30> How many active users follow each type of sport?
229 |
230 | select b.sport_category, count(a.user_id)
231 | from all_users a
232 | join sport_accounts b
233 | on a.user_id = b.sport_player_id
234 | join follow_relation c
235 | on a.user_id = c.follower_id
236 | where a.active_last_month =1
237 | group by b.sport_category;
238 |
239 | -- 31> What percent of active accounts are fraud from ad_accounts table?
240 | select * from ad_accounts;
241 |
242 | select count(distinct a.account_id)/(select count(account_id) from ad_accounts where account_status= "active") as 'percent'
243 | from ad_accounts a
244 | join ad_accounts b
245 | on a.account_id = b.account_id
246 | where a.account_status = 'fraud' and b.account_status='active';
247 |
248 | -- 32> How many accounts became fraud today for the first time from ad_accounts table?
249 |
250 | select count(account_id) 'First time fraud accounts' from (
251 | select distinct a.account_id, count(a.account_status)
252 | from ad_accounts a
253 | join ad_accounts b
254 | on a.account_id = b.account_id
255 | where b.date = curdate() and a.account_status = 'fraud'
256 | group by account_id
257 | having count(a.account_status) = 1) ad_accnt;
258 |
259 | -- 33> Write a SQL query to determine avg time spent per user per day from user_details and event_session_details
260 | select * from event_session_details;
261 | select * from user_details;
262 |
263 | select date, user_id, sum(timespend_sec)/count(*) as 'avg time spent per user per day'
264 | from event_session_details
265 | group by 1,2
266 | order by 1;
267 |
268 | -- or --
269 |
270 | select date, user_id, avg(timespend_sec)
271 | from event_session_details
272 | group by 1,2
273 | order by 1;
274 |
275 | -- 34> write a SQL query to find top 10 users that sent the most messages from messages_detail table.
276 | select * from messages_detail;
277 |
278 | select user_id, messages_sent
279 | from messages_detail
280 | order by messages_sent desc
281 | limit 10;
282 |
283 | -- 35> Write a SQL query to find disctinct first name from full user name from usere_name table
284 | select * from user_name;
285 |
286 | select distinct(substring_index(full_names, ' ', 1)) first_name from user_name;
287 |
288 | -- 36> You have a table with userID, appID, type and timestamp. type is either 'click' or 'impression'.
289 | -- Calculate the click through rate from dialoglog table. Now do it in for each app.
290 | -- click through rate is defined as (number of clicks)/(number of impressions)
291 | select * from dialoglog;
292 |
293 | select app_id
294 | , ifnull(sum(case when type = 'click' then 1 else 0 end)*1.0
295 | / sum(case when type = 'impression' then 1 else 0 end), 0 )AS 'CTR(click through rate)'
296 | from dialoglog
297 | group by app_id;
298 |
299 | -- 37> Given two tables Friend_request (requestor_id, sent_to_id, time),
300 | -- Request_accepted (acceptor_id, requestor_id, time). Find the overall acceptance rate of requests.
301 | -- Overall acceptate rate of requests = total number of acceptance / total number of requests.
302 | select * from friend_request;
303 | select * from request_accepted;
304 |
305 | select ifnull(round(
306 | (select count(*) from (select distinct acceptor_id, requestor_id from request_accepted) as A)
307 | /
308 | (select count(*) from (select distinct requestor_id, sent_to_id from friend_request ) as B), 2),0
309 | ) as basic;
310 |
311 | -- 38> from a table of new_request_accepted, find a user with the most friends.
312 | select * from new_request_accepted;
313 |
314 | select id from
315 | (
316 | select id, count(*) as count
317 | from (
318 | select requestor_id as id from new_request_accepted
319 | union all
320 | select acceptor_id as id from new_request_accepted) as a
321 | group by 1
322 | order by count desc
323 | limit 1) as table1;
324 |
325 | -- 39> from the table count_request, find total count of requests sent and total count of requests sent failed
326 | -- per country
327 | select * from count_request;
328 |
329 | select country_code, Total_request_sent, Total_percent_of_request_sent_failed,
330 | cast((Total_request_sent*Total_percent_of_request_sent_failed)/100 as decimal) as Total_request_sent_failed
331 | from
332 | (
333 | select country_code, sum(count_of_requests_sent) as Total_request_sent,
334 | cast(replace(ifnull(sum(percent_of_request_sent_failed),0), '%','') as decimal(2,1)) as Total_percent_of_request_sent_failed
335 | from count_request
336 | group by country_code
337 | ) as Table1;
338 |
339 | -- 40> create a histogram of duration on x axis, no of users on y axis which is populated by volume in each bucket
340 | -- from event_session_details
341 | select * from event_session_details;
342 |
343 | select floor(timespend_sec/500)*500 as bucket,
344 | count(distinct user_id) as count_of_users
345 | from event_session_details
346 | group by 1;
347 |
348 | -- 41> Write SQL query to calculate percentage of confirmed messages from two tables :
349 | -- confirmation_no (phone numbers that facebook sends the confirmation messages to) and
350 | -- confirmed_no (phone numbers that confirmed the verification)
351 |
352 | select round((count(confirmed_no.phone_number)/count(confirmation_no.phone_number))*100, 2)
353 | from confirmation_no
354 | left join confirmed_no
355 | on confirmed_no.phone_number= confirmation_no.phone_number;
356 |
357 | -- 42> Write SQL query to find number of users who had 4 or more than 4 interactions on 2013-03-23 date
358 | -- from user_interaction table (user_1, user_2, date).
359 | -- assume there is only one unique interaction between a pair of users per day
360 |
361 | select * from user_interaction;
362 |
363 | select table1.user_id, sum(number_of_interactions) as Number_of_interactions
364 | from
365 | (
366 | select user_1 as user_id, count(user_1) as number_of_interactions from user_interaction
367 | group by user_1
368 | union all
369 | select user_2 as user_id, count(user_2) as number_of_interactions from user_interaction
370 | group by user_2) table1
371 | group by table1.user_id
372 | having sum(number_of_interactions) >= 4;
373 |
374 | -- 43> write a sql query to find the names of all salesperson that have order with samsonic from
375 | -- the table: salesperson, customer, orders
376 |
377 | select s.name
378 | from salesperson s
379 | join orders o on s.id = o.salesperson_id
380 | join customer c on o.cust_id = c.id
381 | where c.name = 'Samsonic';
382 |
383 | -- 44> write a sql query to find the names of all salesperson that do not have any order with Samsonic from the table: salesperson, customer, orders
384 |
385 | select s.Name
386 | from Salesperson s
387 | where s.ID NOT IN(
388 | select o.salesperson_id from Orders o, Customer c
389 | where o.cust_id = c.ID
390 | and c.Name = 'Samsonic');
391 |
392 | -- 45> Wrie a sql query to find the names of salespeople that have 2 or more orders.
393 | select s.name as 'salesperson', count(o.number) as 'number of orders'
394 | from salesperson s
395 | join orders o on s.id = o.salesperson_id
396 | group by s.name
397 | having count(o.number)>=2;
398 |
399 | -- 46> Given two tables: User(user_id, name, phone_num) and UserHistory(user_id, date, action),
400 | -- write a sql query that returns the name, phone number and most recent date for any user that has logged in
401 | -- over the last 30 days
402 | -- (you can tell a user has logged in if action field in UserHistory is set to 'logged_on')
403 |
404 | select user.name, user.phone_num, max(userhistory.date)
405 | from user,userhistory
406 | where user.user_id = userhistory.user_id
407 | and userhistory.action = 'logged_on'
408 | and userhistory.date >= date_sub(curdate(), interval 30 day)
409 | group by user.name;
410 |
411 | -- 47> Given two tables: User(user_id, name, phone_num) and UserHistory(user_id, date, action),
412 | -- Write a SQL query to determine which user_ids in the User table are not contained in the UserHistory table
413 | -- (assume the UserHistory table has a subset of the user_ids in User table). Do not use the SQL MINUS statement.
414 | -- Note: the UserHistory table can have multiple entries for each user_id.
415 | select user.user_id
416 | from user
417 | left join userhistory
418 | on user.user_id = userhistory.user_id
419 | where userhistory.user_id is null;
420 |
421 | -- 48> from a given table compare(numbers int(4)), write a sql query that will return the maximum value
422 | -- from the numbers without using
423 | -- sql aggregate like max or min
424 |
425 | select numbers
426 | from compare
427 | order by numbers desc
428 | limit 1;
429 |
430 | -- 49> Write a SQL query to find out how many users inserted more than 1000 but less than 2000 images in their presentations from event_log table
431 | -- There is a startup company that makes an online presentation software and they have event_log table that records every time a user inserted
432 | -- an image into a presentation. one user can insert multiple images
433 |
434 | select count(*) from
435 | (select user_id, count(event_date_time) as image_per_user
436 | from event_log
437 | group by user_id) as image_per_user
438 | where image_per_user <2000 and image_per_user>1000;
439 |
440 | -- 50> select the most recent login time by values from the login_info table
441 |
442 | select * from login_info
443 | where login_time in (select max(login_time) from login_info
444 | group by user_id)
445 | order by login_time desc limit 1;
446 | ```
447 |
448 |
451 |
452 | ## Q. Count the Employees
453 |
454 | The data for the numner employed at several famous IT companies is maintained in the COMPANY table. Write a query to print the IDs of the companies that have more than 10000 employees, in ascending order of ID.
455 |
456 | **Input Format:**
457 |
458 | | Name | Type | Description |
459 | |---------|---------|-------------|
460 | | ID | Integer | A company ID in the inclusive range, [1, 1000]. This is the primay key.|
461 | | NAME | String | A company name. This field contans between 1 and 100 characters (inclusive).|
462 | |EMPLOYEES| Integer | The total number of employees in the company. |
463 |
464 | **Output Format:**
465 |
466 | The result should contain the IDs of all the companies that have more than 10000 employees, in scending order in the follwing format:
467 |
468 | ```sql
469 | COMPANY.ID
470 | ```
471 |
472 | **Sample Input:**
473 |
474 | | ID | NAME |EMPLOYEES|
475 | |----|------------|-------|
476 | | 1 | Adobe | 28085 |
477 | | 2 | Flipkart | 35543 |
478 | | 3 | Amazon | 1089 |
479 | | 4 | Paytm | 9982 |
480 | | 5 | BookMyShow | 5589 |
481 | | 6 | Oracle | 4003 |
482 | | 7 | NIIT | 57782 |
483 | | 8 | Samsung | 2000 |
484 | | 9 | TCS | 10046 |
485 | | 10 | Wipro | 3500 |
486 |
487 | **Sample Output:**
488 |
489 | ```js
490 | 1
491 | 2
492 | 7
493 | 9
494 | ```
495 |
496 | **Explanation:**
497 |
498 | Adobe, Filpkart, NIIT and TCS have greater then 10000 employees, so their IDs are printed.
499 |
500 | Answer
501 |
502 | ```sql
503 |
504 | ```
505 |
506 |
507 |
508 |
511 |
--------------------------------------------------------------------------------