本段 140 题 | 来源:fullstack + general + design | 知识点:数据库
702. What is a Replica Set in MongoDB?
MongoDB中的副本集是什么?
- 知识点: 数据库 (主题: mongodb, nosql, database;标签: interviewbit, mongodb, topic-specific, nosql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37bd558d557c902bb4d1b | 官方: 否 | 付费: 否
答案:
To keep identical copies of your data on multiple servers, we use replication. It is recommended for all production deployments. Use replication to keep your application running and your data safe, even if something happens to one or more of your servers.
为了在多个服务器上保留数据的相同副本,我们使用复制。建议所有生产环境部署都使用此功能。即使一个或多个服务器发生问题,使用复制也能保持应用程序运行和数据安全。
Such replication can be created by a replica set with MongoDB. A replica set is a group of servers with one primary, the server taking writes, and multiple secondaries, servers that keep copies of the primary’s data. If the primary crashes, the secondaries can elect a new primary from amongst themselves.
这种复制可以通过 MongoDB 的副本集来创建。副本集是一组服务器,其中有一个主节点(负责写入)和多个从节点(保留主节点数据的副本)。如果主节点崩溃,从节点可以自行选举出新的主节点。
703. Explain the Replication Architecture in MongoDB.
解释 MongoDB 中的复制架构。
- 知识点: 数据库 (主题: mongodb, nosql, database;标签: interviewbit, mongodb, topic-specific, nosql, database)
- 类型: technical | 难度: hard | 子类型: system-design
- 分类: fullstack
- id: 69b37bd558d557c902bb4d1e | 官方: 否 | 付费: 否
答案:
The following diagram depicts the architecture diagram of a simple replica set cluster with only three server nodes – one primary node and two secondary nodes:
下图展示了仅包含三个服务器节点的简单副本集集群的架构图——一个主节点和两个从节点:
- In the preceding model, the PRIMARY database is the only active replica set member that receives write operations from database clients. The PRIMARY database saves data changes in the Oplog. Changes saved in the Oplog are sequential—that is, saved in the order that they are received and executed.
- The SECONDARY database is querying the PRIMARY database for new changes in the Oplog. If there are any changes, then Oplog entries are copied from PRIMARY to SECONDARY as soon as they are created on the PRIMARY node.
- Then, the SECONDARY database applies changes from the Oplog to its own datafiles. Oplog entries are applied in the same order they were inserted in the log. As a result, datafiles on SECONDARY are kept in sync with changes on PRIMARY.
- Usually, SECONDARY databases copy data changes directly from PRIMARY. Sometimes a SECONDARY database can replicate data from another SECONDARY. This type of replication is called Chained Replication because it is a two-step replication process. Chained replication is useful in certain replication topologies, and it is enabled by default in MongoDB.
704. What are some utilities for backup and restore in MongoDB?
MongoDB 中有哪些用于备份和恢复的工具?
- 知识点: 数据库 (主题: mongodb, nosql, database;标签: interviewbit, mongodb, topic-specific, nosql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37bd558d557c902bb4d21 | 官方: 否 | 付费: 否
答案:
The mongo shell does not include functions for exporting, importing, backup, or restore. However, MongoDB has created methods for accomplishing this, so that no scripting work or complex GUIs are needed. For this, several utility scripts are provided that can be used to get data in or out of the database in bulk. These utility scripts are: - mongoimport
mongo shell 不包含导出、导入、备份或恢复的功能。然而,MongoDB 已创建了实现这些功能的方法,因此不需要编写脚本或使用复杂的图形用户界面。为此,提供了多个实用脚本,可用于批量将数据移入或移出数据库。这些实用脚本包括: - mongoimport
- mongoexport
- mongodump
- mongorestore
705. What are Transaction Storage Engines in MySQL?
MySQL 中的事务存储引擎是什么?
- 知识点: 数据库 (主题: mysql, sql, database;标签: interviewbit, mysql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37bd958d557c902bb502f | 官方: 否 | 付费: 否
答案:
To be able to use MySQL’s transaction facility, you have to be using MySQL’s InnoDB storage engine (which is the default from version 5.5 onward). If you are not sure which version of MySQL your code will be running on, rather than assuming InnoDB is the default engine you can force its use when creating a table, as follows.
要使用 MySQL 的事务功能,您必须使用 MySQL 的 InnoDB 存储引擎(从版本 5.5 起为默认引擎)。如果您不确定代码将运行的 MySQL 版本,与其假设 InnoDB 是默认引擎,不如在创建表时强制指定使用它,如下所示。
706. What is Sharding in SQL?
SQL 中的分片是什么?
- 知识点: 数据库 (主题: mysql, sql, database;标签: interviewbit, mysql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37bd958d557c902bb5032 | 官方: 否 | 付费: 否
答案:
The process of breaking up large tables into smaller chunks (called shards) that are spread across multiple servers is called Sharding. The advantage of Sharding is that since the sharded database is generally much smaller than the original; queries, maintenance, and all other tasks are much faster.
将大型表拆分成较小的块(称为分片)并分布到多个服务器上的过程称为分片。分片的优点是,由于分片后的数据库通常比原始数据库小得多,查询、维护以及所有其他任务都会快得多。
707. What is Scaling in MySQL?
MySQL 中的扩展是什么?
- 知识点: 数据库 (主题: mysql, sql, database;标签: interviewbit, mysql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37bda58d557c902bb5035 | 官方: 否 | 付费: 否
答案:
In MySQL, scaling capacity is actually the ability to handle the load, and it’s useful to think of load from several different angles such as: - Quantity of data
在 MySQL 中,扩展能力实际上是处理负载的能力,从多个不同角度考虑负载很有用,例如: - 数据量
- Number of users
- User activity
- Size of related datasets
708. Can you explain the logical architecture of MySQL?
你能解释 MySQL 的逻辑架构吗?
- 知识点: 数据库 (主题: mysql, sql, database;标签: interviewbit, mysql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: system-design
- 分类: fullstack
- id: 69b37bda58d557c902bb5038 | 官方: 否 | 付费: 否
答案:
The top layer contains the services most network-based client/server tools or servers need such as connection handling, authentication, security, and so forth. The second layer contains much of MySQL’s brains. This has the code for query parsing, analysis, optimization, caching, and all the built-in functions.
最上层包含大多数基于网络的客户端/服务器工具或服务器所需的服务,如连接处理、认证、安全性等。第二层包含 MySQL 的大部分核心逻辑,其中有查询解析、分析、优化、缓存以及所有内置函数的代码。
The third layer contains the storage engines that are responsible for storing and retrieving the data stored in MySQL.
第三层包含负责存储和检索 MySQL 中数据的存储引擎。
709. What Is The Distinction Between Raid 5 And Raid 10? Which Is the Better Option for Oracle?
RAID 5 和 RAID 10 之间的区别是什么?哪种更适用于 Oracle?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d16 | 官方: 否 | 付费: 否
答案:
- Striping with an additional drive for parity is what RAID 5 is all about. If we damage a disk, we may rebuild it from the parity disk.
- RAID 10 mirror pairs of drives before striping over those mirrors.
- RAID 5 was developed at a time when drives were costly. Its goal was to deliver RAID on a budget. If a disk stops working, the IO module will function VERY slowly while it is being rebuilt. Furthermore, with all of the increased weight of the rebuild, your likelihood of failure increases considerably during this period. RAID 5 is sluggish for everything except reading even when it is running properly. Given that, plus the fact that databases (particularly Oracle's redo logs) continue to suffer write activity at all times, we should avoid RAID5 in all but the odd database that has primarily read activity. Redo logs should not be placed on RAID5.
- RAID10 is just all-around awesome. If you lose a single disk in a set of ten, for example, you might lose any of the remaining eight disks and be OK. Furthermore, because you're only creating a mirror duplicate, rebuilding has no influence on productivity. Finally, RAID10 performs admirably in all sorts of databases.
710. Why does LGWR writes come before DBWR writes?
为什么LGWR的写入会发生在DBWR写入之前?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d19 | 官方: 否 | 付费: 否
答案:
Transaction recordkeeping is more significant than transaction processing in general. Assume we have repeated entries on disk and a power interruption occurs. The transactions can then be recovered by retrieving the redo logs on the disc. This method makes redo logs persistent first, and then temporary blocks are sent to storage.
事务记录通常比事务处理本身更重要。假设磁盘上有重复条目且发生电源中断,可以通过检索磁盘上的重做日志来恢复事务。这种方法使重做日志先持久化,然后将临时块发送到存储。
711. What are SNIPPED sessions in a database?
数据库中被“截断”的会话是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d1d | 官方: 否 | 付费: 否
答案:
Connections that surpass the given time are noted as clipped. When the client exceeds the normal time limit, the Oracle-level operations are removed, but the OS-level processes remain.
超过给定时间的连接会被标记为“截断”。当客户端超出正常时间限制时,Oracle层的操作会被移除,但操作系统层的进程仍然保留。
712. What is a scope parameter?
什么是作用域参数?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d20 | 官方: 否 | 付费: 否
答案:
There are various parameters that may be changed flexibly while using spfile. That is the most significant advantage of spfile over pfile. Every value that you change when the database is operating can have one of three scope values: spfile, memory, or sometimes both. S cope of the Spfile will alter after the next reboot, storage range will change instantly but rollback after the reboot, and both will alter quickly.
使用spfile时,有许多参数可以灵活更改。这是spfile相对于pfile最大的优势。当数据库运行时,你更改的每个值都可以具有三种作用域值之一:spfile、memory,或者有时两者兼有。Spfile的作用域会在下次重启后更改,内存范围会立即更改但重启后回滚,而两者都会快速更改。
713. Distinguish between the delete and truncate commands.
区分delete和truncate命令。
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d23 | 官方: 否 | 付费: 否
答案:
| Truncate command Truncate命令 | Delete command Delete命令 |
|---|---|
| Truncate is a DDL command Truncate是DDL命令 | Delete is a DML command Delete是DML命令 |
| The TRUNCATE command locks the whole table for the deletion of all specified entries TRUNCATE命令锁定整个表以删除所有指定条目 | the DELETE command is carried out with the assistance of a row lock. When the instruction is executed, every row in the tablespace is marked for elimination. DELETE命令借助行锁执行。当指令执行时,表空间中的每一行都被标记为待删除。 |
| The TRUNCATE command locks the whole table for the deletion of all specified entries whereas, By using the truncate command we can delete all of the rows in a table TRUNCATE命令锁定整个表以删除所有指定条目,而使用truncate命令可以删除表中的所有行 | the DELETE command is in charge of eliminating only a single row at a time, rather than removing all of the rows in the table at once. When a row is deleted, its record in the transaction log is logged. DELETE命令一次只负责删除单行,而不是同时删除表中的所有行。当一行被删除时,其事务日志中的记录会被记录。 |
| The TRUNCATE TABLE function aids in the removal of all information by making the memory pages free that are used to store the table data. Only the page unassigning is noted in the binary log after completion. Buttons are not triggered since no changes are going to place. TRUNCATE is a Definition Data Language command, therefore it does not affect data instead, it modifies the design and description of the table TRUNCATE TABLE函数通过释放存储表数据的内存页来帮助移除所有信息。完成后,二进制日志中只记录页面的取消分配。因为不会发生更改,所以不会触发按钮。TRUNCATE是数据定义语言命令,因此它不影响数据,而是修改表的设计和描述 | The DELETE is activated when both NSTEAD OF and AFTER are activated for the DELETE commands in the event of the DELETE command (if present). The DELETE command is a part of DML commands which helps to delete the data present in a row(row-wise). 当DELETE命令的INSTEAD OF和AFTER触发器被激活时(如果存在),DELETE会被触发。DELETE命令是DML命令的一部分,帮助删除行中存在的数据(按行方式)。 |
714. What exactly do you mean by "recovery catalog"?
你所说的“恢复目录”具体是什么意思?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d26 | 官方: 否 | 付费: 否
答案:
RMAN uses a database structure called a recovery catalog to hold information from Oracle databases. The catalog is usually kept in a separate database. A recovery catalog adds repetition to the RMAN library contained within every destination database's control file. It acts as a backup metadata store. Even if the destination control file and all duplicates are deleted, the RMAN information remains in the recovery catalog. A recovery catalog adds repetition to the RMAN library contained within every destination database's control file. It acts as a backup metadata store. Even if the destination control file and all duplicates are deleted, the RMAN information remains.
RMAN使用一种称为恢复目录的数据库结构来保存来自Oracle数据库的信息。该目录通常保存在单独的数据库中。恢复目录为每个目标数据库控制文件中的RMAN库增加了冗余。它充当备份元数据存储。即使目标控制文件及其所有副本都被删除,RMAN信息仍然保留在恢复目录中。恢复目录为每个目标数据库控制文件中的RMAN库增加了冗余。它充当备份元数据存储。即使目标控制文件及其所有副本都被删除,RMAN信息仍然保留。
715. Explain what exactly the deadlock is?
解释一下死锁到底是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d29 | 官方: 否 | 付费: 否
答案:
Deadlock occurs when two operations are trying to change rows of a table that are restricted by the other operation. This is frequently caused by failure to issue adequate row lock requests. This condition can be caused by a poorly designed UI application, and the server's productivity will suffer as a result. When a commit/rollback action is conducted, or either of these programs is stopped outside, these restrictions will be freed immediately.
当两个操作试图更改表中被另一个操作限制的行时,就会发生死锁。这通常是由于未能发出足够的行锁请求造成的。这种情况可能由设计不佳的UI应用程序引起,服务器生产力会因此受到影响。当执行提交/回滚操作,或者这些程序中的任何一个被外部终止时,这些限制将立即被释放。
716. What does the ANALYZE command do?
ANALYZE命令有什么作用?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d2c | 官方: 否 | 付费: 否
答案:
- It is used to get statistics on the optimizer's objects and record these in the database.
It is used to remove information from the database about the information used by the database.
- 它用于从数据库中移除有关数据库所使用信息的信息。
It is used to ensure that the object's structure is correct.
- 它用于确保对象的结构是正确的。
It is used to get the table or cluster's imported and linked rows.
- 它用于获取表或集群的导入和链接行。
717. What are the procedures to change the archiving mode of a database from NO ARCHIVELOG to ARCHIVELOG?
将数据库的归档模式从 NO ARCHIVELOG 更改为 ARCHIVELOG 的步骤是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d30 | 官方: 否 | 付费: 否
答案:
- The database instance should be shut down.
Make a backup of the database.
- 对数据库进行备份。
Perform any actions that are particular to your operating system.
- 执行针对操作系统的特定操作。
Start a new instance and load the database, but don't open it yet.
- 启动新实例并加载数据库,但暂时不要打开它。
Change the archiving mode of the database.
- 更改数据库的归档模式。
718. What does Oracle Home Inventory entail?
Oracle 主目录清单(Oracle Home Inventory)包含哪些内容?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d35 | 官方: 否 | 付费: 否
答案:
Any specified object in a database that would be used to keep or dataset is referred to as a database object. Views, clusters, tables, sequences, indexes, and synonyms have come under database objects.
数据库中用于保存或数据集的任何指定对象都称为数据库对象。视图、簇、表、序列、索引和同义词都属于数据库对象。
719. What exactly is a control file?
控制文件到底是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d39 | 官方: 否 | 付费: 否
答案:
- It's a two-part file that contains data in the database's physical form.
You can remove the probability of crashing with the assistance of the control file.
- 借助控制文件,你可以消除崩溃的可能性。
It contains information about the database name, checkpoint, duration, and the presence of multiple log files.
- 它包含有关数据库名称、检查点、持续时间和多个日志文件存在的信息。
The CONTROL FILE argument, which stores information about the control file, makes it simple to locate it.
- CONTROL FILE 参数存储了控制文件的相关信息,这使得定位它变得简单。
To avoid the problem related to a corrupted file, it is preferable to make numerous copies of the control file.
- 为了避免与损坏文件相关的问题,最好创建多个控制文件的副本。
720. What is the difference between a cluster and a grid?
集群和网格之间的区别是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d3c | 官方: 否 | 付费: 否
答案:
- Grid architecture can be built by using the famous technology known as clustering. The cluster provides static resources dedicated to certain applications and owners. Grids, which can be made up of numerous clusters, are resource provisioning pools that can be used by a wide range of applications and users. A grid does not presume that all of its servers are performing the same set of apps. Applications can be planned and transferred among grid servers.
Grid computing is, at its most basic level, processing as a service. If we talk in simple terms, it doesn't matter where your data is stored or your request is handled by which machine. You must be able to fetch data or computations and have them provided anytime and as much as you desire. This is similar to how power systems function in that you don't know where the generator is or how the grid is wired, all you have to do is ask for power and it will be provided. The objective is to turn computers into a utility, a commodity, and something that everyone has access to. As a result, the moniker 'The Grid' was coined. This is, of course, a "client-side" approach to utility computing.
- 网格计算最基本的形式是将处理作为服务提供。简单来说,数据存储在哪里或请求由哪台机器处理并不重要。你必须能够获取数据或计算,并随时按需获得它们。这与电力系统的运作方式类似:你不知道发电机在哪里或电网如何布线,你只需请求电力,然后它就会被提供。目标是使计算机变成一种公用事业、一种商品,以及人人可访问的东西。因此,得名“网格”。当然,这是公用事业计算的“客户端”方法。
The grid is all about the distribution of the resources, data exchange, and reliability from the "server-side" or the backend. Resource allocation guarantees that people who require or seek resources receive them and that assets are not unused while demands go unmet. Information sharing ensures that users and applications have access to the information they require, and when they require it. High availability characteristics ensure that all data and computations are always available, similar to how a utility provider ensures that electricity is always available.
- 网格涉及从“服务器端”或后端的资源分配、数据交换和可靠性。资源分配确保需要或寻求资源的人能获得资源,并且资产不会在需求未满足时闲置。信息共享确保用户和应用程序在需要时能访问所需的信息。高可用性特性确保所有数据和计算始终可用,类似于公用事业提供商确保电力始终可用。
721. What is the purpose of a password file, and why is it required?
密码文件的用途是什么,为什么需要它?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d3f | 官方: 否 | 付费: 否
答案:
The credentials of the database users are saved in the database's data dictionary. When the user tries to request access to the database, it compares the user's account and passcode to the data contained in the database. Once The user is only allowed database access if the account and passcode match. We can access the data dictionary as long as the database is open. This dictionary also contains the credentials for admins. You can't access the dictionary once the database is shut down. Because starting up a closed database is one of the executive's jobs, there has to be a means for admins to login into the database even when the server is down.
数据库用户的凭据保存在数据库的数据字典中。当用户尝试请求访问数据库时,它会将用户的账户和密码与数据库中所包含的数据进行比对。只有在账户和密码匹配时,用户才被允许访问数据库。只要数据库处于打开状态,我们就可以访问数据字典。该字典还包含管理员的凭据。一旦数据库关闭,你就无法访问该字典。因为启动一个已关闭的数据库是执行人员的工作之一,所以必须有一种方式让管理员即使服务器宕机时也能登录数据库。
A password file is a distinct OS file that is kept on a disc and is not connected to the server. It stores the login details for SYSDBA and SYSOPER clients. While the database is offline, the password file is used to verify admins with those rights.
密码文件是一个独立的操作系统文件,保存在磁盘上,与服务器无关。它存储了SYSDBA和SYSOPER客户的登录详细信息。当数据库离线时,密码文件用于验证具有这些权限的管理员。
722. How to become an oracle dba?
如何成为一名Oracle数据库管理员?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d42 | 官方: 否 | 付费: 否
答案:
People with straight software engineering experience are more likely to transition into this type of administrative function. Very strong knowledge is essential for this, as this type of position is not cracked by everyone.
具有直接软件工程经验的人更有可能转型到这种类型的管理职位。对此,非常扎实的知识至关重要,因为这种类型的职位并非人人都能胜任。
You must understand and have absolute trust in SQL and PL/SQL, which is standard program code accessible for Oracle databases. Moreover, the applicant must understand how the table was constructed within the system, the definition of tablespace, how to recreate and address certain extremely crucial query tuning issues, correct indexing, and how to preserve the required consistency for a whole database.
你必须理解并绝对信任SQL和PL/SQL,这是Oracle数据库可用的标准程序代码。此外,申请人必须了解表在系统内的构建方式、表空间的定义、如何重建和解决某些极其关键的查询调优问题、正确的索引,以及如何维护整个数据库所需的一致性。
As a database administrator license is generally granted depending on any edition, the applicant should always update himself with any latest iteration of the database released by Oracle.
作为数据库管理员,许可通常根据任何版本来授予,申请人应始终更新自己以适应Oracle发布的数据库任何最新版本。
Conclusion
结论
One of the most prominent database management systems is Oracle Database. Oracle is one of the top critical databases in the industry, used by the majority of organizations. As a result, being one of the administrators in that Oracle database is always a professional achievement for that individual.
最突出的数据库管理系统之一是Oracle数据库。Oracle是行业中的顶尖关键数据库之一,被大多数组织使用。因此,成为该Oracle数据库的管理员之一对个人来说总是一项专业成就。
There is nothing to question that a person with Oracle certification would never be unemployed in today's market.
毫无疑问,拥有Oracle认证的人在当今市场中永远不会失业。
Interview Resources
面试资源
- https://www.interviewbit.com/technical-interview-questions/
- https://www.interviewbit.com/coding-interview-questions/
- https://www.interviewbit.com/blog/
723. How much does a Database Administrator (DBA) Oracle in India make?
在印度,Oracle数据库管理员(DBA)的收入是多少?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d45 | 官方: 否 | 付费: 否
答案:
Without even a formal qualification, an Oracle database administrator can earn any income. A student with a valid Oracle credential is not guaranteed a high package compensation. There are different sorts of packages in the contemporary business, one is provided directly by Oracle, while the other is provided by IT organizations that require this type of administrative assistance for their own platform. Pay often ranges from $90000 to $180000, depending on the variety of certifications supplied by the oracle. Oracle qualifications for professionals, masters, and specialists will be developed for various types of pay in their future positions. However, a candidate should be more worried about the variety of updates and being recognized in advanced training. Based on that salary will be very attractive.
即使没有正式资格,Oracle数据库管理员也能获得收入。持有有效Oracle证书的学生并不保证获得高薪包。当代企业中有不同的薪酬类型,一种由Oracle直接提供,另一种由需要此类管理支持以维护其自身平台的IT组织提供。薪酬通常从90000美元到180000美元不等,具体取决于Oracle提供的认证种类。针对专业人士、硕士和专家的Oracle资格将根据其未来职位中的不同薪酬类型而制定。然而,候选人应更关注各种更新和在高级培训中获得认可。基于此,薪资将非常具有吸引力。
724. Is Oracle DBA a good career?
Oracle DBA是一个好的职业吗?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d48 | 官方: 否 | 付费: 否
答案:
Database administration, particularly in Oracle databases, is really a major and critical component of the work. According to today's market boom, the administrative position in the database, especially in Oracle, has already climbed 11%, which is much greater than that of other accessible occupations. The professional applicant is never able to consider their profession since they are so eager to state that they can simply claim their industry worth from IT Companies. Mostly all IT businesses place a high value on those individuals who can keep their own systems running well.
数据库管理,尤其在Oracle数据库中,确实是工作的重要组成部分和关键环节。根据当今市场繁荣情况,数据库中的管理职位,特别是Oracle中的,已增长11%,远高于其他可获得的职业。专业申请人从不需要考虑失业问题,因为他们急于表明可以轻易从IT公司获得行业价值。几乎所有IT企业都高度重视那些能保持自身系统良好运行的人员。
725. What is the role of DBA in Oracle?
在Oracle中,DBA的角色是什么?
- 知识点: 数据库 (主题: oracle, dba, database;标签: interviewbit, oracle-dba, topic-specific, oracle, dba, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c0b58d557c902bb6d4b | 官方: 否 | 付费: 否
答案:
- Oracle software installation
- Oracle database creation
- Upgrading the software and database to the current version levels
- Turn off and on the database
- Handling the storage architecture of the database
- User management and protection
- Taking care of schema objects like tables, indexes, and views
- It helps to backup data and, if necessary, execute database restoration
- Analyzing the database's quality on a regular basis and taking preventative or remedial action when needed
- Performance tracking and tweaking
- You could be the only individual doing these duties in a small to medium database environment. The position is frequently shared among numerous DBAs in big business systems, each with their particular area of expertise, such as database security analyst or database performance specialist.
726. What are COMMIT, ROLLBACK and SAVEPOINT statements in PL/SQL?
PL/SQL 中的 COMMIT、ROLLBACK 和 SAVEPOINT 语句是什么?
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb7568 | 官方: 否 | 付费: 否
答案:
- These are the three transaction specifications that are available in PL/SQL.
COMMIT: Whenever any DML operations are performed, the data gets manipulated only in the database buffer and not the actual database. In order to save these DML transactions to the database, there is a need to COMMIT these transactions.
COMMIT transaction action does saving of all the outstanding changes since the last commit and the below steps take place:COMMIT 事务操作会保存自上次提交以来所有未提交的更改,并执行以下步骤:
The release of affected rows.
释放受影响的行。
The transaction is marked as complete.
事务被标记为完成。
The details of the transaction would be stored in the data dictionary.
事务的详细信息将存储在数据字典中。
Syntax: COMMIT; - ROLLBACK: In order to undo or erase the changes that were done in the current transaction, the changes need to be rolled back. ROLLBACK statement erases all the changes since the last COMMIT.
语法:COMMIT; - ROLLBACK:为了撤销或擦除当前事务中所做的更改,需要回滚这些更改。ROLLBACK 语句会擦除自上次 COMMIT 以来的所有更改。
Syntax: ROLLBACK; - SAVEPOINT: This statement gives the name and defines a point in the current transaction process where any changes occurring before that SAVEPOINT would be preserved whereas all the changes after that point would be released.
语法:ROLLBACK; - SAVEPOINT:该语句为当前事务过程中的一个点提供名称并定义该点,在该 SAVEPOINT 之前发生的任何更改将被保留,而该点之后的所有更改将被释放。
Syntax: SAVEPOINT ;
语法:SAVEPOINT ;
727. How can you debug your PL/SQL code?
如何调试你的 PL/SQL 代码?
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb756b | 官方: 否 | 付费: 否
答案:
We can use DBMS_OUTPUT and DBMS_DEBUG statements for debugging our code:
DBMS_OUTPUT prints the output to the standard console.DBMS_OUTPUT 将输出打印到标准控制台。
DBMS_DEBUG prints the output to the log file.
DBMS_DEBUG 将输出打印到日志文件。
728. What is the difference between a mutating table and a constraining table?
变异表和约束表之间有什么区别?
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb756e | 官方: 否 | 付费: 否
答案:
- A table that is being modified by the usage of the DML statement currently is known as a mutating table. It can also be a table that has triggers defined on it.
- A table used for reading for the purpose of referential integrity constraint is called a constraining table.
729. In what cursor attributes the outcomes of DML statement execution are saved?
DML 语句执行的结果保存在哪些游标属性中?
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb7571 | 官方: 否 | 付费: 否
答案:
The outcomes of the execution of the DML statement is saved in the following 4 cursor attributes:
SQL%FOUND: This returns TRUE if at least one row has been processed.SQL%FOUND:如果至少处理了一行,则返回 TRUE。
SQL%NOTFOUND: This returns TRUE if no rows were processed.
SQL%NOTFOUND:如果未处理任何行,则返回 TRUE。
SQL%ISOPEN: This checks whether the cursor is open or not and returns TRUE if open.
SQL%ISOPEN:用于检查游标是否处于打开状态,若打开则返回 TRUE。
SQL%ROWCOUNT: This returns the number of rows processed by the DML statement.
SQL%ROWCOUNT:返回 DML 语句处理的行数。
730. Is it possible to declare column which has the number data type and its scale larger than the precision? For example defining columns like: column name NUMBER (10,100), column name NUMBER (10,-84)
是否可以声明一个数字数据类型且其精度小于标度的列?例如定义像这样的列:列名 NUMBER (10,100),列名 NUMBER (10,-84)?
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: system-design
- 分类: fullstack
- id: 69b37c1a58d557c902bb7574 | 官方: 否 | 付费: 否
答案:
- Yes, these type of declarations are possible.
- Number (9, 12) indicates that there are 12 digits after decimal point. But since the maximum precision is 9, the rest are 0 padded like 0.000999999999.
- Number (9, -12) indicates there are 21 digits before the decimal point and out of that there are 9 possible digits and the rest are 0 padded like 999999999000000000000.0
PL/SQL Programs
731. Write a PL/SQL program using WHILE loop for calculating the average of the numbers entered by user. Stop the entry of numbers whenever the user enters the number 0.
编写一个使用 WHILE 循环的 PL/SQL 程序,用于计算用户输入数字的平均值。当用户输入数字 0 时,停止输入数字。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb7577 | 官方: 否 | 付费: 否
答案:
DECLARE
声明
n NUMBER;
n 数字;
average NUMBER :=0 ;
平均值 数字 :=0;
sum NUMBER :=0 ;
总和 数字 :=0;
count NUMBER :=0 ;
计数 数字 :=0;
BEGIN
BEGIN
-- Take input from user
-- 从用户处获取输入
n := &input_number;
n := &input_number;
WHILE(n<>0)
当(n<>0)
LOOP
循环
-- Increment count to find total elements
-- 增加计数以找到总元素数
count := count+1;
计数 := 计数+1;
-- Sum of elements entered
-- 输入元素之和
sum := sum+n;
sum := sum+n;
-- Take input from user
-- 从用户处获取输入
n := &input_number;
n := &input_number;
END LOOP;
结束循环;
-- Average calculation
-- 平均值计算
average := sum/count;
average := sum/count;
DBMS_OUTPUT.PUT_LINE(‘Average of entered numbers is ’||average);
DBMS_OUTPUT.PUT_LINE(‘Average of entered numbers is ’||average);
END;
结束;
732. Write a PL/SQL procedure for selecting some records from the database using some parameters as filters.
编写一个PL/SQL过程,使用一些参数作为过滤器从数据库中选择一些记录。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb757a | 官方: 否 | 付费: 否
答案:
- Consider that we are fetching details of employees from ib_employee table where salary is a parameter for filter.
CREATE PROCEDURE get_employee_details @salary nvarchar(30)
CREATE PROCEDURE get_employee_details @salary nvarchar(30)
AS
AS
BEGIN
BEGIN
SELECT * FROM ib_employee WHERE salary = @salary;
SELECT * FROM ib_employee WHERE salary = @salary;
END;
结束;
733. Write a PL/SQL code to count the number of Sundays between the two inputted dates.
编写一段PL/SQL代码,计算两个输入日期之间的星期日数量。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb757d | 官方: 否 | 付费: 否
答案:
--declare 2 dates of type Date
--声明两个日期类型的变量
DECLARE
声明
start_date Date;
开始日期 日期类型;
end_date Date;
结束日期 日期类型;
sundays_count Number:=0;
星期天数 数字类型:=0;
BEGIN
BEGIN
-- input 2 dates
-- 输入2个日期
start_date:='&input_start_date';
开始日期:='&输入开始日期';
end_date:='&input_end_date';
结束日期:='&输入结束日期';
/*
Returns the date of the first day after the mentioned date
返回指定日期之后第一个与第二个参数中指定的星期匹配的日期
and matching the day specified in second parameter.
并匹配第二个参数中指定的星期几。
*/
start_date:=NEXT_DAY(start_date-1, 'SUNDAY');
开始日期:=NEXT_DAY(开始日期-1, 'SUNDAY');
--check the condition of dates by using while loop.
--使用while循环检查日期条件。
while(start_date<=end_date)
while(开始日期<=结束日期)
LOOP
循环
sundays_count:=sundays_count+1;
星期天数:=星期天数+1;
start_date:=start_date+7;
开始日期:=开始日期+7;
END LOOP;
结束循环;
-- print the count of sundays
-- 打印星期日的数量
dbms_output.put_line('Total number of Sundays between the two dates:'||sundays_count);
dbms_output.put_line('两个日期之间星期日总数:'||sundays_count);
END;
结束;
/
Input: start_date = ‘01-SEP-19’ end_date = ‘29-SEP-19’
输入:start_date = '01-SEP-19' end_date = '29-SEP-19'
Output: Total number of Sundays between the two dates: 5
输出:两个日期之间星期日总数:5
734. Write PL/SQL code block to increment the employee’s salary by 1000 whose employee_id is 102 from the given table below.
根据下表,编写PL/SQL代码块,将employee_id为102的员工工资增加1000。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb7580 | 官方: 否 | 付费: 否
答案:
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | EMAIL_ID | PHONE_NUMBER | JOIN_DATE | JOB_ID | SALARY |
|---|---|---|---|---|---|---|---|
| 100 | ABC | DEF | abef | 9876543210 | 2020-06-06 | AD_PRES | 24000.00 |
| 101 | GHI | JKL | ghkl | 9876543211 | 2021-02-08 | AD_VP | 17000.00 |
| 102 | MNO | PQR | mnqr | 9876543212 | 2016-05-14 | AD_VP | 17000.00 |
| 103 | STU | VWX | stwx | 9876543213 | 2019-06-24 | IT_PROG | 9000.00 |
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | EMAIL_ID | PHONE_NUMBER | JOIN_DATE | JOB_ID | SALARY |
|---|---|---|---|---|---|---|---|
| 100 | ABC | DEF | abef | 9876543210 | 2020-06-06 | AD_PRES | 24000.00 |
| 101 | GHI | JKL | ghkl | 9876543211 | 2021-02-08 | AD_VP | 17000.00 |
| 102 | MNO | PQR | mnqr | 9876543212 | 2016-05-14 | AD_VP | 17000.00 |
| 103 | STU | VWX | stwx | 9876543213 | 2019-06-24 | IT_PROG | 9000.00 |
DECLARE
声明
employee_salary NUMBER(8,2);
employee_salary 数字(8,2);
PROCEDURE update_salary (
过程 update_salary (
emp NUMBER,
emp 数字,
salary IN OUT NUMBER
salary 输入输出 数字
) IS
) 是
BEGIN
BEGIN
salary := salary + 1000;
salary := salary + 1000;
END;
结束;
BEGIN
BEGIN
SELECT salary INTO employee_salary
SELECT salary INTO employee_salary
FROM ib_employee
FROM ib_employee
WHERE employee_id = 102;
WHERE employee_id = 102;
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE
('Before update_salary procedure, salary is: ' || employee_salary);
('在调用update_salary过程之前,薪水为:' || employee_salary);
update_salary (100, employee_salary);
update_salary (100, employee_salary);
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE
('After update_salary procedure, salary is: ' || employee_salary);
('在调用update_salary过程之后,薪水为:' || employee_salary);
END;
结束;
/
Result:
结果:
Before update_salary procedure, salary is: 17000
在调用update_salary过程之前,薪水为:17000
After update_salary procedure, salary is: 18000
在调用update_salary过程之后,薪水为:18000
735. Write a PL/SQL code to find whether a given string is palindrome or not.
编写一段PL/SQL代码,判断给定的字符串是否为回文。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb7583 | 官方: 否 | 付费: 否
答案:
DECLARE
声明
-- Declared variables string, letter, reverse_string where string is the original string.
-- 声明变量string、letter、reverse_string,其中string是原始字符串。
string VARCHAR2(10) := 'abccba';
string VARCHAR2(10) := 'abccba';
letter VARCHAR2(20);
letter VARCHAR2(20);
reverse_string VARCHAR2(10);
reverse_string VARCHAR2(10);
BEGIN
BEGIN
FOR i IN REVERSE 1..LENGTH(string) LOOP
对于 i 在 1..长度(string) 的反向循环中
letter := SUBSTR(string, i, 1);
letter := SUBSTR(string, i, 1);
-- concatenate letter to reverse_string variable
-- 将字母连接到 reverse_string 变量
reverse_string := reverse_string ||''||letter;
reverse_string := reverse_string ||''||letter;
END LOOP;
结束循环;
IF reverse_string = string THEN
如果 reverse_string = string 那么
dbms_output.Put_line(reverse_string||''||' is palindrome');
dbms_output.Put_line(reverse_string||''||' 是回文');
ELSE
ELSE
dbms_output.Put_line(reverse_string ||'' ||' is not palindrome');
dbms_output.Put_line(reverse_string ||'' ||' 不是回文');
END IF;
结束如果;
END;
结束;
736. Write PL/SQL program to convert each digit of a given number into its corresponding word format.
编写 PL/SQL 程序,将给定数字的每一位转换为对应的单词格式。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb7586 | 官方: 否 | 付费: 否
答案:
DECLARE
声明
-- declare necessary variables
-- 声明必要的变量
-- num represents the given number
-- num 表示给定的数字
-- number_to_word represents the word format of the number
-- number_to_word 表示数字的单词格式
-- str, len and digit are the intermediate variables used for program execution
-- str、len 和 digit 是用于程序执行的中间变量
num INTEGER;
num INTEGER;
number_to_word VARCHAR2(100);
number_to_word VARCHAR2(100);
digit_str VARCHAR2(100);
digit_str VARCHAR2(100);
len INTEGER;
len INTEGER;
digit INTEGER;
digit INTEGER;
BEGIN
BEGIN
num := 123456;
num := 123456;
len := LENGTH(num);
len := LENGTH(num);
dbms_output.PUT_LINE('Input: ' ||num);
dbms_output.PUT_LINE('输入: ' ||num);
-- Iterate through the number one by one
-- 逐个循环遍历数字
FOR i IN 1..len LOOP
FOR i IN 1..len LOOP
digit := SUBSTR(num, i, 1);
digit := SUBSTR(num, i, 1);
-- Using DECODE, get the str representation of the digit
-- 使用 DECODE,获取数字的字符串表示
SELECT Decode(digit, 0, 'Zero ',
SELECT Decode(digit, 0, 'Zero ',
1, 'One ',
1, 'One ',
2, 'Two ',
2, 'Two ',
3, 'Three ',
3, 'Three ',
4, 'Four ',
4, 'Four ',
5, 'Five ',
5, 'Five ',
6, 'Six ',
6, 'Six ',
7, 'Seven ',
7, 'Seven ',
8, 'Eight ',
8, 'Eight ',
9, 'Nine ')
9, 'Nine ')
INTO digit_str
INTO digit_str
FROM dual;
FROM dual;
-- Append the str representation of digit to final result.
-- 将数字的字符串表示追加到最终结果。
number_to_word := number_to_word || digit_str;
number_to_word := number_to_word || digit_str;
END LOOP;
结束循环;
dbms_output.PUT_LINE('Output: ' ||number_to_word);
dbms_output.PUT_LINE('输出:' || number_to_word);
END;
结束;
Input: 12345 Output: One Two Three Four Five
输入:12345 输出:一 二 三 四 五
737. Write PL/SQL program to find the sum of digits of a number.
编写PL/SQL程序,求一个数字各位数字之和。
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c1a58d557c902bb7589 | 官方: 否 | 付费: 否
答案:
DECLARE
声明
--Declare variables num, sum_of_digits and remainder of datatype Integer
--声明变量num、sum_of_digits和remainder,数据类型为整数
num INTEGER;
num 整数;
sum_of_digits INTEGER;
sum_of_digits 整数;
remainder INTEGER;
remainder 整数;
BEGIN
BEGIN
num := 123456;
num := 123456;
sum_of_digits := 0;
sum_of_digits := 0;
-- Find the sum of digits until original number doesnt become null
--求各位数字之和,直到原始数字变为零
WHILE num <> 0 LOOP
当 num <> 0 循环
remainder := MOD(num, 10);
remainder := MOD(num, 10);
sum_of_digits := sum_of_digits + remainder;
sum_of_digits := sum_of_digits + remainder;
num := TRUNC(num / 10);
num := TRUNC(num / 10);
END LOOP;
结束循环;
dbms_output.PUT_LINE('Sum of digits is '|| sum_of_digits);
dbms_output.PUT_LINE('各位数字之和为 '|| sum_of_digits);
END;
结束;
Input: 9874 Output: 28
输入:9874 输出:28
PL/SQL Conclusion
738. PL SQL Interview
PL SQL 面试
- 知识点: 数据库 (主题: pl-sql, oracle, database;标签: interviewbit, pl-sql, topic-specific, oracle, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c1a58d557c902bb758c | 官方: 否 | 付费: 否
答案:
- PL/SQL is a programming extension of SQL developed by Oracle which combines the power of SQL in the field of data manipulation and the power of procedural language for faster and effective processing of data thereby resulting in the creation of powerful queries.
- PL/SQL enhances the security, increases the platform portability, and makes it more robust by means of instructing the compiler ‘what to do’ and ‘how to do’ using SQL and procedural form respectively.
- Finally, it gives more power over the database to the programmers due to the feature of decision making, filtering, and looping abilities thereby making it a more convenient and reliable means for the programmers to work on it.
References: https://oracle-base.com/articles/misc/introduction-to-plsql
参考:https://oracle-base.com/articles/misc/introduction-to-plsql
Recommended Tutorials:
推荐教程:
SQL Server Interview Questions MySQL Interview Questions MongoDB Interview Questions DBMS Interview Questions
SQL Server 面试题 MySQL 面试题 MongoDB 面试题 DBMS 面试题
739. Given a Supervision table with employee\_id and manager\_id, write a query to detect if there is a cycle in the reporting hierarchy.
给定一个包含 employee\_id 和 manager\_id 的 Supervision 表,编写一个查询来检测汇报层级中是否存在循环。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c89 | 官方: 否 | 付费: 否
答案:
WITH RECURSIVE Hierarchy AS (
使用递归层级 AS (
-- Base case SELECT employee_id, manager_id,
-- 基础情况 选择 employee_id、manager_id,
CAST(employee_id AS VARCHAR(200))
将 employee_id 转换为 VARCHAR(200)
AS path FROM Supervision UNION ALL
作为路径从 Supervision 表 UNION ALL
-- Recursive step
-- 递归步骤
SELECT s.employee_id, s.manager_id,
选择 s.employee_id、s.manager_id,
CONCAT(h.path, '->', s.employee_id)
连接 h.path、'->'、s.employee_id
AS path FROM Supervision s INNER JOIN Hierarchy h ON s.manager_id = h.employee_id
作为路径从 Supervision 表 s 内连接 Hierarchy 表 h 基于 s.manager_id = h.employee_id
-- Stop recursion if cycle detected
-- 若检测到循环则停止递归
WHERE h.path NOT LIKE CONCAT('%', s.employee_id, '%') )
WHERE h.path NOT LIKE CONCAT('%', s.employee_id, '%') )
-- Detect cycles where employee appears again in path
-- 检测路径中员工再次出现形成的循环
SELECT DISTINCT employee_id, path FROM Hierarchy
SELECT DISTINCT employee_id, path FROM Hierarchy
WHERE path LIKE CONCAT('%', employee_id, '%'); copy
WHERE path LIKE CONCAT('%', employee_id, '%'); copy
740. Write an UPDATE query to set the total\_sales to the sum of individual sales amounts for each employee in the employee table.
编写一个 UPDATE 查询,将 employee 表中每位员工的 total_sales 设置为该员工个人销售额的总和。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c8c | 官方: 否 | 付费: 否
答案:
-- Update total_sales column in the employee table
-- 更新 employee 表中的 total_sales 列
UPDATE Intellipaat_Emp e SET total_sales = (
UPDATE Intellipaat_Emp e SET total_sales = (
-- Calculate total sales per employee
-- 计算每位员工的销售总额
SELECT COALESCE(SUM(s.sale_amount), 0)
SELECT COALESCE(SUM(s.sale_amount), 0)
FROM sales s WHERE s.employee_id = e.employee_id )
FROM sales s WHERE s.employee_id = e.employee_id )
-- Update only employees who have sales records
-- 仅更新有销售记录的员工
WHERE EXISTS ( SELECT 1 FROM sales s
WHERE EXISTS ( SELECT 1 FROM sales s
WHERE s.employee_id = e.employee_id ); copy
WHERE s.employee_id = e.employee_id ); copy
741. Write an SQL syntax for joining 3 tables.
编写一个连接 3 张表的 SQL 语法。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c8f | 官方: 否 | 付费: 否
答案:
SELECT tab1.col1, tab2.col2, tab3.col3
SELECT tab1.col1, tab2.col2, tab3.col3
-- Columns to display FROM table1 tab1
-- 要从表table1 tab1显示的列
JOIN table2 tab2 ON tab1.col1 = tab2.col1
JOIN table2 tab2 ON tab1.col1 = tab2.col1
-- Matching condition
-- 匹配条件
JOIN table3 tab3 ON tab2.col1 = tab3.col1;
JOIN table3 tab3 ON tab2.col1 = tab3.col1;
-- Matching condition copy
-- 匹配条件副本
742. Write a query to select specific columns, say name and age, from a table called Employees.
编写一条查询语句,从名为Employees的表中选择特定列,比如name和age。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c92 | 官方: 否 | 付费: 否
答案:
SELECT name, age
SELECT name, age
-- Select specific columns FROM Employees;
-- 从Employees中选择特定列;
-- Table name copy
-- 表名副本
743. Write a query to get employees older than 35 and working in the operations department.
编写一条查询语句,获取年龄大于35且就职于运营部门的员工。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c95 | 官方: 否 | 付费: 否
答案:
SELECT * FROM Intellipaat_Emp
SELECT * FROM Intellipaat_Emp
-- Table name WHERE age > 35
-- 表名WHERE age > 35
-- Age greater than 35 AND department = 'operations';
-- 年龄大于35并且department = 'operations';
copy
copy
744. Write a query to find the average salary for each department.
编写一条查询语句,找出每个部门的平均工资。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c9a | 官方: 否 | 付费: 否
答案:
SELECT department, AVG(salary) AS avg_salary
SELECT department, AVG(salary) AS avg_salary
-- Calculate the average salary FROM Intellipaat_Emp GROUP BY department;
-- 计算 Intellipaat_Emp 按部门分组的平均工资
-- Group results by department
-- 按部门分组结果
copy
copy
745. Write a query to find employees whose names start with ‘Int’.
编写一个查询,找出姓名以“Int”开头的员工。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7c9d | 官方: 否 | 付费: 否
答案:
SELECT * FROM Intellipaat_Emp
SELECT * FROM Intellipaat_Emp
WHERE employee_name LIKE 'Int%';
WHERE employee_name LIKE 'Int%';
-- Names starting with 'Int' copy
-- 以“Int”开头的姓名 copy
746. Write a query to add a new employee record.
编写一个查询,添加一条新的员工记录。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ca0 | 官方: 否 | 付费: 否
答案:
INSERT INTO Intellipaat_Emp (
INSERT INTO Intellipaat_Emp (
Employee_name, Age, Department, Salary)
Employee_name, Age, Department, Salary)
VALUES ('John Doe', 28, 'Marketing', 50000); copy
VALUES ('John Doe', 28, 'Marketing', 50000); copy
747. Write a query to retrieve the last five records from the Employees table based on the ID column.
编写一个查询,从 Employees 表中根据 ID 列检索最后五条记录。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ca3 | 官方: 否 | 付费: 否
答案:
SELECT * FROM Intellipaat_Emp ORDER BY Employee_id DESC
SELECT * FROM Intellipaat_Emp ORDER BY Employee_id DESC
-- Sort by ID in descending order LIMIT 5;
-- 按 ID 降序排序 LIMIT 5;
-- Return last 5 records copy
-- 返回最后 5 条记录 copy
748. Write a query to label employees with salaries above 5000 as “High Salary.”
编写一个查询,将工资高于 5000 的员工标注为“高薪”。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ca6 | 官方: 否 | 付费: 否
答案:
SELECT Employee_name, Salary, CASE WHEN Salary > 5000
SELECT Employee_name, Salary, CASE WHEN Salary > 5000
THEN 'High Salary' ELSE 'Low Salary' END
THEN 'High Salary' ELSE 'Low Salary' END
AS salary_category FROM Intellipaat_Emp; copy
AS salary_category FROM Intellipaat_Emp; copy
749. Write a query to get all employees and their project names, showing NULL if an employee is not assigned a project.
编写查询,获取所有员工及其项目名称,如果员工未被分配项目则显示 NULL。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ca9 | 官方: 否 | 付费: 否
答案:
SELECT e.Employee_name, p.project_name FROM Intellipaat_Emp
SELECT e.Employee_name, p.project_name FROM Intellipaat_Emp
e LEFT JOIN Projects p ON e.project_id = p.id;
e LEFT JOIN Projects p ON e.project_id = p.id;
-- LEFT JOIN ensures NULL if no project copy
-- LEFT JOIN 确保无项目时显示 NULL copy
750. Write an SQL query to display each department along with the name of any employee who works in that department. If a department has no employees, show the department with NULL for the employee’s name.
编写 SQL 查询,显示每个部门以及在该部门工作的任何员工的姓名。如果某部门没有员工,则显示该部门并将员工姓名设为 NULL。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cac | 官方: 否 | 付费: 否
答案:
SELECT dept.DepartmentName, emp.Employee_name
SELECT dept.DepartmentName, emp.Employee_name
FROM Departments dept
FROM Departments dept
LEFT JOIN Intellipaat_Emp emp ON emp.DepartmentID
LEFT JOIN Intellipaat_Emp emp ON emp.DepartmentID
= dept.DepartmentID; copy
= dept.DepartmentID; copy
751. Write a query to increase the salary of all employees in the ‘HR’ department by 10%.
编写查询,将“HR”部门所有员工的工资提高10%。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7caf | 官方: 否 | 付费: 否
答案:
UPDATE Intellipaat_Emp SET Salary
UPDATE Intellipaat_Emp SET Salary
= Salary * 1.1 WHERE Department = 'HR'; copy
= Salary * 1.1 WHERE Department = 'HR'; copy
752. Write a query to fetch unique employee names where duplicate names exist in the Employees table.
编写查询,从 Employees 表中提取存在重复名称的唯一员工姓名。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cb2 | 官方: 否 | 付费: 否
答案:
SELECT Employee_name FROM Intellipaat_Emp
SELECT Employee_name FROM Intellipaat_Emp
GROUP BY Employee_name HAVING COUNT(*) > 1; copy
GROUP BY Employee_name HAVING COUNT(*) > 1; copy
753. Find all duplicate rows in the table Employees, considering all columns.
查找表 Employees 中所有重复行,考虑所有列。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cb5 | 官方: 否 | 付费: 否
答案:
SELECT FROM ( SELECT , ROW_NUMBER() OVER
SELECT FROM ( SELECT , ROW_NUMBER() OVER
( PARTITION BY Employee_name, Age, Department, Salary )
( PARTITION BY Employee_name, Age, Department, Salary )
AS rn FROM Intellipaat_Emp ) t WHERE rn > 1; copy
AS rn FROM Intellipaat_Emp ) t WHERE rn > 1; copy
754. How will you calculate the total sales in each category of a product sales table?
如何计算产品销售表中每个类别的总销售额?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cb8 | 官方: 否 | 付费: 否
答案:
To calculate the total sales in each category of a product sales table, we can use the aggregate function (SUM) with the sales amount column and group it by the category column.
要计算产品销售表中每个类别的总销售额,我们可以使用聚合函数(SUM)搭配销售额列,并按类别列进行分组。
SELECT category, SUM(sales_amt) AS Total_Sales
SELECT category, SUM(sales_amt) AS Total_Sales
-- Calculate total sales per category FROM sales
-- 计算每个类别的总销售额 FROM sales
GROUP BY category; -- Group totals by category copy
GROUP BY category; -- 按类别分组总计 copy
755. How can you copy data from one table to another table?
如何将数据从一个表复制到另一个表?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cbb | 官方: 否 | 付费: 否
答案:
--We can use the INSERT INTO SELECT operator.
--我们可以使用 INSERT INTO SELECT 运算符。
INSERT INTO employee_duplicate SELECT * FROM employees; copy
INSERT INTO employee_duplicate SELECT * FROM employees; copy
756. Write a query to fetch employees who earn more than the average salary.
编写一个查询来获取工资高于平均工资的员工。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cc0 | 官方: 否 | 付费: 否
答案:
SELECT * FROM Intellipaat_Emp
SELECT * FROM Intellipaat_Emp
-- Compare each employee's salary to the average salary
-- 将每位员工的薪资与平均薪资进行比较
WHERE salary > (SELECT AVG(salary) FROM Intellipaat_Emp); copy
WHERE salary > (SELECT AVG(salary) FROM Intellipaat_Emp); 复制
757. How would you find the 2nd-highest salary from a table called Employees?
你将如何从名为 Employees 的表中找出第二高的薪资?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: scenario
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cc3 | 官方: 否 | 付费: 否
答案:
SELECT MAX(salary)
SELECT MAX(salary)
-- Filter out the top salary FROM Intellipaat
-- 过滤掉最高薪资 FROM Intellipaat
_Emp WHERE salary < (SELECT MAX(salary)
_Emp WHERE salary < (SELECT MAX(salary)
-- Filter out the top salary FROM Intellipaat_Emp); copy
-- 过滤掉最高薪资 FROM Intellipaat_Emp); 复制
For the Nth highest salary, replace MAX with LIMIT:
对于第 N 高的薪资,用 LIMIT 替换 MAX:
SELECT DISTINCT salary FROM Intellipaat
SELECT DISTINCT salary FROM Intellipaat
_Emp ORDER BY salary DESC
_Emp ORDER BY salary DESC
-- Sort salaries from highest to lowest LIMIT N-1, 1;
-- 按薪资从高到低排序 LIMIT N-1, 1;
-- Skip the top (N-1) salaries and return the Nth highest one copy
-- 跳过前 (N-1) 个最高薪资并返回第 N 高的那个 复制
758. Write a query to select only even or odd rows from a table based on an ID field.
编写一个查询,根据 ID 字段从表中选择仅偶数或奇数行。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cc6 | 官方: 否 | 付费: 否
答案:
-- Select employees with EVEN Employee_id
-- 选择 Employee_id 为偶数的员工
SELECT * FROM Intellipaat_Emp WHERE Employee_id % 2 = 0;
SELECT * FROM Intellipaat_Emp WHERE Employee_id % 2 = 0;
-- IDs divisible by 2 are even
-- 能被 2 整除的 ID 是偶数
-- Select employees with ODD Employee_id SELECT * FROM
-- 选择具有奇数 Employee_id 的员工 SELECT * FROM
Intellipaat_Emp WHERE Employee_id % 2 = 1;
Intellipaat_Emp WHERE Employee_id % 2 = 1;
-- IDs not divisible by 2 are odd copy
-- 不能被2整除的ID是奇数 复制
759. Write a query to select the top 2 salaries from each department in the Employees table.
编写一个查询,从 Employees 表中选择每个部门薪资最高的前2名。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cc9 | 官方: 否 | 付费: 否
答案:
-- Select top 2 highest-paid employees per department
-- 选择每个部门薪资最高的前2名员工
SELECT Employee_name, Department, Salary FROM
SELECT Employee_name, Department, Salary FROM
( SELECT Employee_name, Department, Salary, ROW_NUMBER() OVER
( SELECT Employee_name, Department, Salary, ROW_NUMBER() OVER
( PARTITION BY Department ORDER BY Salary DESC )
( PARTITION BY Department ORDER BY Salary DESC )
AS salary_rank FROM Intellipaat_Emp ) ranked WHERE salary_rank <= 2; copy
AS salary_rank FROM Intellipaat_Emp ) ranked WHERE salary_rank <= 2; 复制
760. If you have an ID column with sequential numbers but some values are missing, write a query to find the missing numbers.
如果你有一个具有连续数字的 ID 列,但某些值缺失,编写一个查询来查找缺失的编号。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ccc | 官方: 否 | 付费: 否
答案:
-- Find missing Employee_id values in sequence
-- 查找序列中缺失的 Employee_id 值
SELECT (e.Employee_id + 1) AS missing_id FROM Intellipaat
SELECT (e.Employee_id + 1) AS missing_id FROM Intellipaat
_Emp e WHERE (e.Employee_id + 1) NOT IN
_Emp e WHERE (e.Employee_id + 1) NOT IN
( SELECT Employee_id FROM Intellipaat_Emp ); copy
( SELECT Employee_id FROM Intellipaat_Emp ); 复制
761. Write a query to swap the values in a column, for example, changing all ‘Male’ to ‘Female’ and vice versa in the column gender.
编写一个查询来交换列中的值,例如,将 gender 列中的所有‘Male’改为‘Female’,反之亦然。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ccf | 官方: 否 | 付费: 否
答案:
-- Swap Male to Female and Female to Male
-- 交换 Male 和 Female
UPDATE Intellipaat_Emp SET Gender = CASE
UPDATE Intellipaat_Emp SET Gender = CASE
WHEN Gender = 'Male' THEN 'Female' WHEN Gender = 'Female'
当 Gender = 'Male' 时 THEN 'Female' 当 Gender = 'Female'
THEN 'Male' ELSE Gender -- Keep other values unchanged END; copy
则 THEN 'Male' ELSE Gender -- 保持其他值不变 END; 复制
762. Write a query to find pairs of employees who have the same salary.
编写一个查询来查找薪水相同的员工对。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cd2 | 官方: 否 | 付费: 否
答案:
-- Find employee pairs who earn the same salary
-- 查找薪水相同的员工对
SELECT A.Employee_name AS employee1,
SELECT A.Employee_name AS employee1,
B.Employee_name AS employee2, A.Salary FROM Intellipaat
B.Employee_name AS employee2, A.Salary FROM Intellipaat
_Emp A JOIN Intellipaat_Emp B ON A.Salary = B.Salary
_Emp A JOIN Intellipaat_Emp B ON A.Salary = B.Salary
AND A.Employee_name < B.Employee_name;
AND A.Employee_name < B.Employee_name;
-- Avoid self-match & duplicate pairs copy
-- 避免自我匹配和重复对 复制
763. Write a query to find the number of days an employee has been with the company.
编写一个查询来查找员工在公司工作的天数。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cd5 | 官方: 否 | 付费: 否
答案:
-- Calculate number of days since employee joined SELECT Employee_name, DATEDIFF(CURDATE(), Joining_date) AS days_with_company FROM Intellipaat_Emp; copy
-- 计算员工加入以来的天数 SELECT Employee_name, DATEDIFF(CURDATE(), Joining_date) AS days_with_company FROM Intellipaat_Emp; 复制
764. Find pairs of employees who were hired on the same day.
查找同一天入职的员工对。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cd8 | 官方: 否 | 付费: 否
答案:
-- Find employee pairs hired on the same date
-- 查找同一天入职的员工对
SELECT A.Employee_name AS employee1, B.
SELECT A.Employee_name AS employee1, B.
Employee_name AS employee2, A.Joining_date
Employee_name AS employee2, A.Joining_date
FROM Intellipaat_Emp A JOIN Intellipaat_Emp B
从 Intellipaat_Emp A 连接 Intellipaat_Emp B
ON A.Joining_date = B.Joining_date AND A.
基于 A.Joining_date = B.Joining_date 且 A.
Employee_name < B.Employee_name; -- Avoid duplicate pairs copy
Employee_name < B.Employee_name; -- 避免重复对复制
765. Write a query to find the median salary in each department from the Employee table.
编写一个查询,从 Employee 表中查找每个部门的中位数薪资。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cdb | 官方: 否 | 付费: 否
答案:
Hint: You may use ROW\_NUMBER() or PERCENT\_RANK() to determine median values.
提示:您可以使用 ROW_NUMBER() 或 PERCENT_RANK() 来确定中位数。
-- Calculate median salary per department WITH RankedSalaries AS ( SELECT Department, Salary, -- Rank salaries in ascending order ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary) AS rn_asc, -- Rank salaries in descending order ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS rn_desc FROM Intellipaat_Emp ) -- Select middle salary (median) SELECT Department, AVG(Salary) AS median_salary FROM RankedSalaries WHERE rn_asc = rn_desc OR rn_asc + 1 = rn_desc GROUP BY Department; copy
-- 计算每个部门的薪资中位数 使用 RankedSalaries 作为 ( 选择 Department, Salary, -- 按升序排列薪资排名 ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary) AS rn_asc, -- 按降序排列薪资排名 ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS rn_desc 从 Intellipaat_Emp ) -- 选择中间薪资(中位数) 选择 Department, AVG(Salary) AS median_salary 从 RankedSalaries 其中 rn_asc = rn_desc 或 rn_asc + 1 = rn_desc 按 Department 分组;复制
766. Write a query to get the top 10% of employees by salary.
编写一个查询,获取薪资排名前 10% 的员工。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cde | 官方: 否 | 付费: 否
答案:
Hint: Use PERCENT\_RANK() to filter out top percentages.
提示:使用 PERCENT_RANK() 来筛选出排名靠前的百分比。
-- Select top 10% highest-paid employees SELECT * FROM ( SELECT Employee_name, Salary, -- Rank employees by descending salary percentage PERCENT_RANK() OVER (ORDER BY Salary DESC) AS pct_rank FROM Intellipaat_Emp ) Ranked WHERE pct_rank <= 0.1; -- Top 10% earners copy
-- 选择薪资最高的前 10% 员工 选择 * 从 ( 选择 Employee_name, Salary, -- 按薪资降序百分比排列员工排名 PERCENT_RANK() OVER (ORDER BY Salary DESC) AS pct_rank 从 Intellipaat_Emp ) Ranked 其中 pct_rank <= 0.1; -- 收入最高的前 10% 复制
767. Write a query to calculate the cumulative salary (running total) within each department.
编写一个查询,计算每个部门内的累计薪资(运行总计)。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ce1 | 官方: 否 | 付费: 否
答案:
-- Calculate running total salary within each department SELECT Department, Employee_name, Salary, -- Running total ordered by salary SUM(Salary) OVER ( PARTITION BY Department ORDER BY Salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_salary FROM Intellipaat_Emp; copy
-- 计算每个部门内的运行总计薪资 选择 Department, Employee_name, Salary, -- 按薪资排序的运行总计 SUM(Salary) OVER ( PARTITION BY Department ORDER BY Salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_salary 从 Intellipaat_Emp;复制
768. Write a query to calculate the time gap (in hours) between consecutive logins for each user.
编写一个查询,计算每个用户连续登录之间的时间间隔(以小时为单位)。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ce4 | 官方: 否 | 付费: 否
答案:
-- Calculate time difference in hours between consecutive logins per user
-- 计算每个用户连续登录之间的小时时间差
SELECT user_id, login_time, TIMESTAMPDIFF( HOUR, LAG(login_time)
选择 user_id, login_time, TIMESTAMPDIFF( HOUR, LAG(login_time)
OVER ( PARTITION BY user_id -- Restart for each user
OVER ( PARTITION BY user_id -- 为每个用户重新开始
ORDER BY login_time -- Compare chronologically ),
ORDER BY login_time -- 按时间顺序比较 ),
login_time -- Current login time )
login_time -- 当前登录时间)
AS hours_since_last_login FROM Logins; copy
AS hours_since_last_login FROM Logins; 复制
769. Write a query to get a full list of products, including products that have no sales, by performing a full outer join between product\_dim and sales\_fact.
编写一个查询,通过 product\_dim 和 sales\_fact 之间执行全外连接,获取完整的产品列表,包括没有销售记录的产品。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ce7 | 官方: 否 | 付费: 否
答案:
-- Return all products, including those with no sales SELECT p.product_id, p.product_name, COALESCE(SUM(s.sale_amount), 0) AS total_sales FROM product_dim p LEFT JOIN sales_fact s ON p.product_id = s.product_id GROUP BY p.product_id, p.product_name; copy
-- 返回所有产品,包括没有销售记录的产品 SELECT p.product_id, p.product_name, COALESCE(SUM(s.sale_amount), 0) AS total_sales FROM product_dim p LEFT JOIN sales_fact s ON p.product_id = s.product_id GROUP BY p.product_id, p.product_name; 复制
770. Write a query to calculate the year-to-date (YTD) sales for each product up to the current date in the sales\_fact table.
编写一个查询,计算 sales\_fact 表中每个产品截至当前日期的年初至今(YTD)销售额。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cea | 官方: 否 | 付费: 否
答案:
-- Calculate Year-To-Date sales per product
-- 计算每个产品的年初至今销售额
SELECT product_id, SUM(sale_amount) AS ytd_sales
SELECT product_id, SUM(sale_amount) AS ytd_sales
FROM sales_fact WHERE sale_date >=
FROM sales_fact WHERE sale_date >=
DATE_FORMAT(CURRENT_DATE, '%Y-01-01')
DATE_FORMAT(CURRENT_DATE, '%Y-01-01')
AND sale_date <= CURRENT_DATE
AND sale_date <= CURRENT_DATE
GROUP BY product_id; copy
GROUP BY product_id; 复制
771. How would you find the second-highest salary from a table?
你如何从表中找出第二高的薪水?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: scenario
- 分类: fullstack
- id: 69b37c5c58d557c902bc7ced | 官方: 否 | 付费: 否
答案:
-- Second-highest salary using ranking
-- 使用排名找出第二高的薪水
SELECT e_salary FROM ( SELECT e_salary, DENSE_RANK() OVER (
SELECT e_salary FROM ( SELECT e_salary, DENSE_RANK() OVER (
ORDER BY e_salary DESC) AS rnk FROM employee ) ranked
ORDER BY e_salary DESC) AS rnk FROM employee ) ranked
WHERE rnk = 2; copy
WHERE rnk = 2; 复制
772. How will you fetch the most recent entries in a database?
你将如何获取数据库中最新的条目?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cf0 | 官方: 否 | 付费: 否
答案:
We can fetch the most recent entries in a database by using the ORDER BY clause along with the timestamp column in descending order.
我们可以通过使用 ORDER BY 子句以及时间戳列按降序排列来获取数据库中最新的条目。
SELECT * FROM table_name
SELECT * FROM table_name
ORDER BY timestamp_column DESC;
ORDER BY timestamp_column DESC;
-- Sort by timestamp in descending order copy
-- 按时间戳降序排序 复制
773. How will you find the IDs or details where there have been no entries in terms of sales?
你将如何找出在销售方面没有条目的 ID 或详细信息?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cf3 | 官方: 否 | 付费: 否
答案:
To find the IDs or details where there have been no entries in terms of sales, we can use the LEFT JOIN or NOT EXISTS clause.
要找出在销售方面没有条目的 ID 或详细信息,我们可以使用 LEFT JOIN 或 NOT EXISTS 子句。
Assume we have two tables: product with product details and sales with sales data.
假设我们有两个表:包含产品详细信息的 product 表和包含销售数据的 sales 表。
Left Joins:
左连接:
SELECT p.product_id, p.product_name FROM product p LEFT JOIN sales s ON p.product_id = s.product_id WHERE s.product_id IS NULL; copy
SELECT p.product_id, p.product_name FROM product p LEFT JOIN sales s ON p.product_id = s.product_id WHERE s.product_id IS NULL; 复制
Here, the WHERE s.product\_id is NULL condition helps us filter out the rows where a match in the sales table is not found.
这里,WHERE s.product\_id is NULL 条件帮助我们过滤掉在 sales 表中未找到匹配项的行。
Not Exists:
不存在:
SELECT p.product_id, p.product_name
SELECT p.product_id, p.product_name
FROM products p WHERE NOT EXISTS (
FROM products p WHERE NOT EXISTS (
SELECT 1 FROM sales s
SELECT 1 FROM sales s
WHERE s.product_id = p.product_id ); copy
WHERE s.product_id = p.product_id ); 复制
774. Suppose there is a database where information about the employees in various verticals is stored. Your task is to find the average salary of each vertical and the highest salary among the lot.
假设有一个数据库,其中存储了各个垂直领域员工的信息。你的任务是找出每个垂直领域的平均工资以及其中的最高工资。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cf6 | 官方: 否 | 付费: 否
答案:
To find the average salary of each vertical and the highest salary among the employees, we can use the group by clause along with the aggregate functions (AVG and MAX).
要找出每个垂直领域的平均工资以及员工中的最高工资,我们可以使用 GROUP BY 子句以及聚合函数(AVG 和 MAX)。
SELECT vertical, -- Grouping by vertical AVG(salary) AS average_salary, -- Calculate average salary for each vertical MAX(salary) AS highest_salary -- Find the highest salary in each vertical FROM employees GROUP BY vertical; -- Group the results by vertical copy
SELECT vertical, -- 按垂直领域分组 AVG(salary) AS average_salary, -- 计算每个垂直领域的平均工资 MAX(salary) AS highest_salary -- 找出每个垂直领域的最高工资 FROM employees GROUP BY vertical; -- 按垂直领域分组结果 复制
Where, - vertical: column that you want to group
其中,- vertical:你要分组的列
- salary: column in the table
- employees: table name
775. Given data on where the store inventory is stored, your task is to find the top 3 products in each category in terms of price.
给定商店库存的存储位置数据,你的任务是按价格找出每个类别中排名前 3 的产品。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cf9 | 官方: 否 | 付费: 否
答案:
To find the top 3 products in each category in terms of price, we can group by clause along with the aggregate function (MAX) with the price column, and set the limit as 3 in descending order.
要按价格找出每个类别中排名前 3 的产品,我们可以使用 GROUP BY 子句以及聚合函数(MAX)与价格列,并按降序将限制设置为 3。
-- Get top 3 highest-priced products in each category SELECT category, product_name, price FROM ( SELECT category, product_name, price, ROW_NUMBER() OVER ( PARTITION BY category ORDER BY price DESC ) AS price_rank FROM inventory ) ranked WHERE price_rank <= 3; copy
-- 获取每个类别中价格最高的前 3 个产品 SELECT category, product_name, price FROM ( SELECT category, product_name, price, ROW_NUMBER() OVER ( PARTITION BY category ORDER BY price DESC ) AS price_rank FROM inventory ) ranked WHERE price_rank <= 3; 复制
776. Write an SQL query to find the month-on-month sales of a specific product in a store.
编写一个 SQL 查询,查找商店中特定产品的月度环比销售额。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cfc | 官方: 否 | 付费: 否
答案:
To calculate the month-on-month sales of a specific product in a store, we can use a combination of date functions and aggregate functions.
要计算商店中特定产品的月度环比销售额,我们可以使用日期函数和聚合函数的组合。
— Extract year and month from the sale date
— 从销售日期中提取年份和月份
-- Calculate month-on-month sales for a specific product SELECT DATE_FORMAT(sale_date, '%Y-%m') AS year_month, SUM(quantity_sold) AS total_sales FROM sales WHERE product_id = 'your_product_id' GROUP BY year_month ORDER BY year_month; copy
-- 计算特定产品的月度环比销售额 SELECT DATE_FORMAT(sale_date, '%Y-%m') AS year_month, SUM(quantity_sold) AS total_sales FROM sales WHERE product_id = 'your_product_id' GROUP BY year_month ORDER BY year_month; 复制
777. Suppose in an organisation, employees are mapped under managers. Write an SQL query that will fetch you the managers and employees working under them.
假设在一个组织中,员工被映射到经理之下。编写一个 SQL 查询,用于获取经理及其下属员工。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5c58d557c902bc7cff | 官方: 否 | 付费: 否
答案:
To fetch the managers and employees working under them, we can use a self-join to fetch the managers and the employees working under them.
要获取经理及其下属员工,我们可以使用自连接来获取经理以及在他们手下工作的员工。
-- Fetch managers and their reporting employees SELECT M.employee_id AS manager_id, M.employee_name AS manager_name, E.employee_id AS employee_id, E.employee_name AS employee_name FROM employees E JOIN employees M ON E.manager_id = M.employee_id ORDER BY M.employee_id, E.employee_id; copy
-- 获取经理及其汇报员工 SELECT M.employee_id AS manager_id, M.employee_name AS manager_name, E.employee_id AS employee_id, E.employee_name AS employee_name FROM employees E JOIN employees M ON E.manager_id = M.employee_id ORDER BY M.employee_id, E.employee_id; 复制
778. In a store inventory, your task is to fetch the total quantity of the top product purchased by the customers.
在商店库存中,你的任务是获取客户购买的最热门产品的总数量。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d02 | 官方: 否 | 付费: 否
答案:
To fetch the total quantity of the top product purchased by the customers, we can use a group by clause along with the limit in descending order.
要获取客户购买的最热门产品的总数量,我们可以使用 GROUP BY 子句以及降序排列的 LIMIT 子句。
-- Find the product with the highest total quantity purchased
-- 查找购买总量最高的产品
SELECT product_id, SUM(quantity_purchased)
SELECT product_id, SUM(quantity_purchased)
AS total_quantity_purchased FROM purchases
AS total_quantity_purchased FROM purchases
GROUP BY product_id
GROUP BY product_id
ORDER BY total_quantity_purchased
ORDER BY total_quantity_purchased
DESC LIMIT 1; copy
DESC LIMIT 1; copy
779. You need to create a materialised view to store the monthly total sales by product for faster reporting. Write the SQL to create this view.
您需要创建一个物化视图,按产品存储每月的总销售额,以便加快报表生成。编写SQL来创建此视图。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d05 | 官方: 否 | 付费: 否
答案:
CREATE MATERIALIZED VIEW mv_monthly_sales AS
CREATE MATERIALIZED VIEW mv_monthly_sales AS
SELECT product_id, YEAR(sale_date) AS year,
SELECT product_id, YEAR(sale_date) AS year,
MONTH(sale_date) AS month, SUM(sale_amount)
MONTH(sale_date) AS month, SUM(sale_amount)
AS total_sales FROM sales_fact
AS total_sales FROM sales_fact
GROUP BY product_id, YEAR(sale_date),
GROUP BY product_id, YEAR(sale_date),
MONTH(sale_date); copy
MONTH(sale_date); copy
780. Write a query that detects missing dates in a sequence from a sales table. The sales table contains sale\_date and sale\_amount, and you need to find any missing dates between the earliest and latest sales dates.
编写一个查询,检测销售表中日期序列的缺失日期。销售表包含sale\_date和sale\_amount,您需要找出最早和最晚销售日期之间的所有缺失日期。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d08 | 官方: 否 | 付费: 否
答案:
-- Generate all dates between min and max sale_date
-- 生成最小和最大sale_date之间的所有日期
WITH RECURSIVE DateSeries AS ( SELECT MIN(sale_date)
WITH RECURSIVE DateSeries AS ( SELECT MIN(sale_date)
AS date_value, MAX(sale_date) AS max_date
AS date_value, MAX(sale_date) AS max_date
FROM sales UNION ALL SELECT date_value + INTERVAL 1
FROM sales UNION ALL SELECT date_value + INTERVAL 1
DAY, max_date FROM DateSeries
DAY, max_date FROM DateSeries
WHERE date_value < max_date ) -- Find missing dates
WHERE date_value < max_date ) -- 查找缺失日期
SELECT date_value AS missing_date FROM DateSeries
SELECT date_value AS missing_date FROM DateSeries
WHERE date_value NOT IN ( SELECT sale_date FROM sales )
WHERE date_value NOT IN ( SELECT sale_date FROM sales )
ORDER BY missing_date; copy
ORDER BY missing_date; 复制
781. Write a query using a Common Table Expression (CTE) to rank customers by total purchase amount and return the top 10 customers.
编写一个查询,使用公用表表达式(CTE)按总购买金额对客户进行排名,并返回前10名客户。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d0b | 官方: 否 | 付费: 否
答案:
-- Rank customers by total purchase amount and return
-- 按总购买金额对客户进行排名并返回
top 10 WITH RankedCustomers AS (
前10名 WITH RankedCustomers AS (
SELECT customer_id, SUM(purchase_amount) AS total_spent,
SELECT customer_id, SUM(purchase_amount) AS total_spent,
-- Rank customers by spending (highest first) DENSE_RANK() OVER (
-- 按消费金额对客户排名(最高优先) DENSE_RANK() OVER (
ORDER BY SUM(purchase_amount) DESC ) AS rank FROM orders
ORDER BY SUM(purchase_amount) DESC ) AS rank FROM orders
GROUP BY customer_id ) SELECT customer_id, total_spent
GROUP BY customer_id ) SELECT customer_id, total_spent
FROM RankedCustomers WHERE rank <= 10; copy
FROM RankedCustomers WHERE rank <= 10; 复制
782. Can you identify the employee who has the third-highest salary from the given employee table (with salary-related data)?
你能从给定的员工表(包含薪资相关数据)中找出薪资第三高的员工吗?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d0e | 官方: 否 | 付费: 否
答案:
Consider the following employee table. In the table, Sabid has the third-highest salary (60,000).
考虑以下员工表。在表中,Sabid 拥有第三高的薪资(60,000)。
NameSalaryTarun70,000Sabid60,000Adarsh30,000Vaibhav80,000
姓名薪资Tarun70,000Sabid60,000Adarsh30,000Vaibhav80,000
Below is a simple query to find out which employee has the third-highest salary. The functions RANK, DENSE RANK, and ROW NUMBER are used to obtain the increasing integer value by imposing the ORDER BY clause in the SELECT statement, based on the ordering of the rows. The ORDER BY clause is necessary when the RANK, DENSE RANK, or ROW NUMBER functions are used. On the other hand, the PARTITION BY clause is optional.
下面是一个简单的查询,用于找出薪资第三高的员工。函数 RANK、DENSE RANK 和 ROW NUMBER 通过在 SELECT 语句中施加 ORDER BY 子句,基于行的排序来获取递增的整数值。使用 RANK、DENSE RANK 或 ROW NUMBER 函数时,ORDER BY 子句是必需的。另一方面,PARTITION BY 子句是可选的。
WITH CTE AS ( SELECT Name, Salary, ROW_NUMBER()
WITH CTE AS ( SELECT Name, Salary, ROW_NUMBER()
OVER (ORDER BY Salary DESC) AS RN
OVER (ORDER BY Salary DESC) AS RN
FROM EMPLOYEE ) SELECT Name,
FROM EMPLOYEE ) SELECT Name,
Salary FROM CTE WHERE RN = 3; copy
Salary FROM CTE WHERE RN = 3; 复制
783. Get the customer name and product name ordered by first name from the customer
获取客户名称和产品名称,按客户的名字排序
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d11 | 官方: 否 | 付费: 否
答案:
SELECT first_name, b.Product_name
SELECT first_name, b.Product_name
FROM [customer] A LEFT OUTER JOIN [Product] B
FROM [customer] A LEFT OUTER JOIN [Product] B
-- Left join to include customers without orders ON A.
-- 左连接以包含没有订单的客户 ON A.
customer_id = B.customer_id
customer_id = B.customer_id
-- Join condition on customer_id
-- 连接条件基于 customer_id
ORDER BY a.first_name
ORDER BY a.first_name
-- Order the result by customer's first name copy
-- 按客户的名字排序结果 复制
784. Get the customer’s name and the product name ordered by first name
获取客户的姓名和产品名称,按名字排序
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d14 | 官方: 否 | 付费: 否
答案:
SELECT a.First_Name, ISNULL(b.
SELECT a.First_Name, ISNULL(b.
Product_name,'-No Project Assigned')
Product_name,'-No Project Assigned')
AS Product_Name
AS Product_Name
FROM customer A LEFT OUTER JOIN product
FROM customer A LEFT OUTER JOIN product
B ON A.customer_id = B.customer_id
B ON A.customer_id = B.customer_id
ORDER BY a.first_name copy
ORDER BY a.first_name copy
785. Get all product names, even if they have not matched any customer ID, in the left table, order by first name
获取左表中所有产品名称,即使它们未匹配任何客户ID,按名字排序
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d17 | 官方: 否 | 付费: 否
答案:
SELECT a.first_name,b.
SELECT a.first_name,b.
Product_name FROM [customer]
Product_name FROM [customer]
A RIGHT OUTER JOIN [product] B ON a.
A RIGHT OUTER JOIN [product] B ON a.
customer_id = b.customer_id
customer_id = b.customer_id
ORDER BY a.first_name copy
ORDER BY a.first_name copy
786. Get the complete record (customer name, product name) from both tables ([CustomerDetail], [ProductDetail]); if no match is found in any table, then show NULL.
从两个表([CustomerDetail]、[ProductDetail])获取完整记录(客户名称、产品名称);如果任一表中未找到匹配项,则显示 NULL。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d1a | 官方: 否 | 付费: 否
答案:
SELECT a.first_name,b.Product_name
SELECT a.first_name,b.Product_name
FROM [customer] A FULL OUTER JOIN [product]
FROM [customer] A FULL OUTER JOIN [product]
B ON a.customer_id = b.customer_id
B ON a.customer_id = b.customer_id
ORDER BY a.first_name copy
ORDER BY a.first_name copy
787. Write a query to find out the product name that is not assigned to any employee( tables: [CustomerDetail],[ProductDetail]).
编写一个查询来找出未分配给任何员工的产品名称(表:[CustomerDetail] 和 [ProductDetail])。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d1d | 官方: 否 | 付费: 否
答案:
SELECT b.Product_name FROM [customer]
SELECT b.Product_name FROM [customer]
A RIGHT OUTER JOIN [product] B ON a.
A RIGHT OUTER JOIN [product] B ON a.
customer_id = b.customer_id
customer_id = b.customer_id
WHERE a.first_name IS NULL copy
WHERE a.first_name IS NULL copy
788. Write down the query to fetch the ProductName on which more than one customer is working, along with the CustomerName.
编写查询来获取有多个客户在工作的产品名称(ProductName),以及相应的客户名称(CustomerName)。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d20 | 官方: 否 | 付费: 否
答案:
Select P.Product_name, c.first_name from product P
Select P.Product_name, c.first_name from product P
INNER JOIN customer c on p.customer_id = c.
INNER JOIN customer c on p.customer_id = c.
customer_id where P.Product_name in
customer_id where P.Product_name in
(select Product_name from product
(select Product_name from product
group by Product_name having COUNT(1)>1) copy
group by Product_name having COUNT(1)>1) copy
*The output will not come as there is no duplicate record in the product table.
*由于产品表中没有重复记录,输出将不会出现。
789. Write a query to find the Nth highest salary from a table
编写一个查询来从表中找出第N高的薪水。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d23 | 官方: 否 | 付费: 否
答案:
To find the Nth highest salary, the DENSE\_RANK() window function is commonly used because it handles duplicate salaries correctly.
要找到第N高的薪水,通常使用DENSE\_RANK()窗口函数,因为它能正确处理重复的薪水值。
SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (
SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (
ORDER BY salary DESC) AS rank_num FROM employees )
ORDER BY salary DESC) AS rank_num FROM employees )
ranked_salaries WHERE rank_num = N; copy
ranked_salaries WHERE rank_num = N; copy
Replace N with the required position (for example, 2 for second highest salary).
将 N 替换为所需的位置(例如,2 表示第二高的薪水)。
790. Write a query to find and remove duplicate rows from a table
编写一个查询,用于查找并删除表中的重复行
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d26 | 官方: 否 | 付费: 否
答案:
Duplicate rows can be identified using ROW\_NUMBER() and removed by keeping only the first occurrence.
可以使用 ROW\_NUMBER() 来识别重复行,并通过仅保留第一次出现的记录来删除它们。
DELETE FROM employees WHERE id NOT IN
DELETE FROM employees WHERE id NOT IN
( SELECT MIN(id) FROM employees
( SELECT MIN(id) FROM employees
GROUP BY name, salary ); copy
GROUP BY name, salary ); copy
This query keeps one unique record and removes all duplicates based on the selected columns.
此查询保留一条唯一记录,并根据所选列删除所有重复项。
791. How do you pattern match for names starting with “A” and ending with “n”?
如何模式匹配以“A”开头并以“n”结尾的名称?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d29 | 官方: 否 | 付费: 否
答案:
The LIKE operator is used for pattern matching. The pattern 'A%n' matches names that start with A and end with n.
LIKE 运算符用于模式匹配。模式 'A%n' 匹配以 A 开头并以 n 结尾的名称。
SELECT * FROM employees
SELECT * FROM employees
WHERE name LIKE 'A%n'; copy
WHERE name LIKE 'A%n'; copy
Here, % represents zero or more characters between A and n.
这里,% 表示 A 和 n 之间的零个或多个字符。
792. Write a query to show the current date and time
编写一个查询以显示当前日期和时间
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d2c | 官方: 否 | 付费: 否
答案:
Different databases use different functions to return the current date and time.
不同的数据库使用不同的函数来返回当前日期和时间。
SQL Server:
SQL Server:
SELECT GETDATE(); copy
SELECT GETDATE(); 复制
MySQL:
MySQL:
SELECT NOW(); copy
SELECT NOW(); 复制
Both queries return the current system date and time of the database server.
两个查询都返回数据库服务器的当前系统日期和时间。
793. How do you create an empty table with the same structure as another table?
如何创建一个与另一个表结构相同的空表?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d2f | 官方: 否 | 付费: 否
答案:
An empty table with the same structure can be created using SELECT INTO with a condition that always evaluates to false.
可以使用始终为假条件的 SELECT INTO 来创建一个结构相同的空表。
SELECT * INTO new_table
SELECT * INTO new_table
FROM existing_table WHERE 1 = 0; copy
FROM existing_table WHERE 1 = 0; 复制
This copies only the table structure, not the data.
这仅复制表结构,而不复制数据。
794. How do you check if a table exists before creating it?
在创建表之前,如何检查表是否已存在?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d32 | 官方: 否 | 付费: 否
答案:
Checking for table existence helps prevent errors when creating tables.
检查表是否存在有助于防止创建表时出错。
SQL Server:
SQL Server:
IF NOT EXISTS ( SELECT * FROM sys.tables
IF NOT EXISTS ( SELECT * FROM sys.tables
WHERE name = 'employees' ) BEGIN
WHERE name = 'employees' ) BEGIN
CREATE TABLE employees ( id INT, name VARCHAR(50) ); END copy
CREATE TABLE employees ( id INT, name VARCHAR(50) ); END 复制
MySQL:
MySQL:
CREATE TABLE IF NOT EXISTS
如果不存在则创建表
employees ( id INT, name VARCHAR(50) ); copy
employees ( id INT, name VARCHAR(50) ); 复制
These approaches ensure the table is created only if it does not already exist.
这些方法确保仅在表不存在时才创建该表。
795. How would you optimize a slow-moving SQL query? List the SQL optimization techniques.
如何优化一个执行缓慢的 SQL 查询?列出 SQL 优化技术。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d35 | 官方: 否 | 付费: 否
答案:
You can optimize a slow-moving SQL query by using specific performance tuning techniques.
您可以通过使用特定的性能调优技术来优化执行缓慢的 SQL 查询。
There are several SQL query optimization techniques listed below:
以下列出了几种 SQL 查询优化技术:
- Use indexes on frequently filtered or joined columns.
- Avoid SELECT *; select only the required columns.
- Filter early with proper WHERE clauses.
- Analyse the query with EXPLAIN to find bottlenecks.
- Replace correlated subqueries with joins or CTEs.
- Limit results using LIMIT or pagination.
- Ensure efficient joins and avoid unnecessary sorting.
These steps help improve performance by reducing data scanned and optimising execution.
这些步骤通过减少扫描的数据量和优化执行来提高性能。
796. Explain the concept of database partitioning and its benefits.
解释数据库分区(partitioning)的概念及其优势。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d38 | 官方: 否 | 付费: 否
答案:
Database partitioning divides a large table into smaller segments based on a chosen key. This improves the performance of the SQL queries by allowing queries to run on the specific partitions and reducing I/O operations.
数据库分区根据选定的键将大表划分为更小的片段。这通过允许查询在特定分区上运行并减少 I/O 操作来提高 SQL 查询的性能。
797. Explain the difference between horizontal and vertical partitioning.
解释水平分区和垂直分区之间的区别。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d3b | 官方: 否 | 付费: 否
答案:
Horizontal: Splits a table by rows (e.g., by date ranges)
水平分区:按行分割表(例如,按日期范围)
Vertical: Splits a table by columns (e.g., separating frequently vs rarely accessed fields)
垂直分区:按列分割表(例如,分离频繁访问和很少访问的字段)
Use horizontal for distributed querying, vertical for security/performance optimization.
对于分布式查询使用水平分区,对于安全/性能优化使用垂直分区。
798. What third-party tools are used in SQL Server?
SQL Server 中使用了哪些第三方工具?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d3e | 官方: 否 | 付费: 否
答案:
The following is the list of third-party tools that are used in SQL Server: - SQL CHECK
以下是 SQL Server 中使用的第三方工具列表: - SQL CHECK
- SQL DOC 2
- SQL Backup 5
- SQL Prompt
- Litespeed 5.0
799. How would you track changes to sensitive data for auditing?
你会如何跟踪敏感数据的变化以进行审计?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: scenario
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d41 | 官方: 否 | 付费: 否
答案:
-- Create a table named 'audit_log' to track changes in data
-- 创建一个名为 'audit_log' 的表来跟踪数据变化
CREATE TABLE audit_log ( change_time TIMESTAMP,
CREATE TABLE audit_log ( change_time TIMESTAMP,
-- Timestamp of when the change occurred
-- 变化发生的时间戳
user_id INT,
user_id INT,
-- Id of the user who made the change
-- 进行更改的用户ID
old_value JSONB,
old_value JSONB,
-- Previous state of the data stored as JSONB
-- 以JSONB格式存储的数据先前状态
new_value JSONB
new_value JSONB
-- Updated state of the data stored as JSONB );
-- 以JSONB格式存储的数据更新后状态 );
Use triggers or CDC (Change Data Capture) to populate this table. copy
使用触发器或CDC(变更数据捕获)来填充此表。复制
800. You have an order table with millions of rows, and you frequently run a query that filters it by customer\_id, order\_date, and status. What indexes would you create to optimize this query, and why?
你有一个包含数百万行的订单表,并且经常运行一个按customer\_id、order\_date和status过滤的查询。你会创建哪些索引来优化此查询,为什么?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d44 | 官方: 否 | 付费: 否
答案:
We need to create a composite index on columns that are frequently used for filtering.
我们需要在常用于过滤的列上创建复合索引。
CREATE INDEX idx_orders_customer_date_status
CREATE INDEX idx_orders_customer_date_status
ON orders (customer_id, order_date, status); copy
ON orders (customer_id, order_date, status); 复制
801. What is Denormalization, and when is it used?
什么是反规范化,以及何时使用它?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d47 | 官方: 否 | 付费: 否
答案:
Denormalization is the process of intentionally introducing redundancy into a database by combining tables to improve query performance.
反规范化是通过合并表来有意引入数据库冗余以提升查询性能的过程。
While normalization focuses on reducing data duplication, denormalization is used when read performance is more important than storage efficiency. - Reduces the need for complex joins
规范化侧重于减少数据重复,而当读性能比存储效率更重要时,会使用反规范化。- 减少了复杂连接的需求。
- Improves read and reporting performance
- Commonly used in data warehouses and OLAP systems
- May increase data redundancy and update complexity
802. What is a View? How is it different from a Materialized View?
什么是视图?它与物化视图有何不同?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d4a | 官方: 否 | 付费: 否
答案:
A View is a virtual table created from a SQL query, whereas a Materialized View stores the query result physically on disk.
视图是由SQL查询创建的虚拟表,而物化视图则物理存储查询结果于磁盘上。
| Feature 功能 | View 视图 | Materialized View 物化视图 |
|---|---|---|
| Storage 存储 | Virtual (no data stored) 虚拟(不存储数据) | Physical data stored 物理存储数据 |
| Performance 性能 | Slower for complex queries 复杂查询较慢 | Faster query performance 查询性能更快 |
| Refresh Required 需要刷新 | No 否 | Yes 是 |
| Use Case 使用场景 | Security and abstraction 安全性和抽象 | Reporting and analytics 报告和分析 |
803. What is a Cursor? Why should you avoid using them?
什么是游标?为什么应避免使用它们?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d4d | 官方: 否 | 付费: 否
答案:
A Cursor is a database object used to retrieve and process rows one at a time instead of processing them as a set.
游标是一种数据库对象,用于逐行检索和处理数据,而非作为集合一次性处理。
Cursors should generally be avoided because they significantly impact performance compared to set-based operations. - Processes rows sequentially (row-by-row)
一般应避免使用游标,因为与基于集合的操作相比,它们会显著影响性能。- 逐行顺序处理行数据
- Consumes more memory and CPU
- Slower than set-based SQL operations
- Used only when row-level processing is unavoidable
804. Explain Window Functions (RANK vs DENSE\_RANK vs ROW\_NUMBER)
解释窗口函数(RANK 对比 DENSE_RANK 对比 ROW_NUMBER)
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d50 | 官方: 否 | 付费: 否
答案:
Window functions perform calculations across a set of rows related to the current row without collapsing the result set.
窗口函数对与当前行相关的一组行执行计算,而不折叠结果集。
| Feature
功能 | RANK | DENSE\_RANK
DENSE_RANK | ROW\_NUMBER
ROW_NUMBER |
| Handles Duplicates 处理重复值 | Yes 是 | Yes 是 | No 否 |
| Gap in Ranking 排名间隙 | Yes 是 | No 否 | No 否 |
| Unique Row Number 唯一行号 | No 否 | No 否 | Yes 是 |
| Common Use 常见用途 | Leaderboard ranking 排行榜排名 | Nth highest value 第N高值 | Remove duplicates 移除重复项 |
805. How does an Index work internally?
索引内部是如何工作的?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d53 | 官方: 否 | 付费: 否
答案:
An Index improves query performance by allowing the database to locate rows quickly without scanning the entire table.
索引通过允许数据库快速定位行而无需扫描整个表,从而提高查询性能。
Most relational databases implement indexes using B-Tree data structures. - B-Trees keep data sorted and balanced
大多数关系数据库使用B-Tree数据结构实现索引。- B-Tree保持数据有序且平衡
- Search, insert, and delete operations run in logarithmic time
- Indexes store key values and pointers to actual rows
Excessive indexing can slow down write operations
Indexes significantly speed up SELECT queries but should be used carefully to balance performance.索引显著加速SELECT查询,但应谨慎使用以平衡性能。
806. Explain the CAP Theorem.
解释CAP定理。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d56 | 官方: 否 | 付费: 否
答案:
CAP Theorem, also known as Brewer’s Theorem, which is a key concept in distributed systems that states all three properties cannot be guaranteed at the same time: - Consistency
CAP 定理,又称布鲁尔定理,是分布式系统中的关键概念,指出三个属性无法同时保证:- 一致性
- Availability
- Partition Tolerance
807. Explain the GROUP BY and HAVING clauses
解释 GROUP BY 和 HAVING 子句
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d5c | 官方: 否 | 付费: 否
答案:
GROUP BY: GROUP BY aggregates data into groups based on specified columns (like department or date).
GROUP BY:GROUP BY 根据指定列(如部门或日期)将数据聚合为组。
HAVING: HAVING filters these groups after aggregation, similar to WHERE for individual rows.
HAVING:HAVING 在聚合后过滤这些组,类似于 WHERE 对单独行的过滤。
Example: SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 80000 shows only departments with an average salary above 60k.
示例:SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 80000 仅显示平均工资高于 60k 的部门。
808. What are the different types of SQL commands?
SQL 命令有哪些不同类型?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d60 | 官方: 否 | 付费: 否
答案:
SQL commands are broadly classified into five categories: DDL (Data Definition Language), DML (Data Manipulation Language), DCL (Data Control Language), TCL (Transaction Control Language), and DQL (Data Query Language). - DDL consists of commands such as CREATE, ALTER, and DROP.
SQL 命令大致分为五类:DDL(数据定义语言)、DML(数据操作语言)、DCL(数据控制语言)、TCL(事务控制语言)和 DQL(数据查询语言)。- DDL 包含 CREATE、ALTER 和 DROP 等命令。
- DML consists of INSERT, UPDATE, and DELETE.
- DCL consists of GRANT and REVOKE.
- TCL consists of COMMIT, ROLLBACK, and SAVEPOINT.
DQL is mainly the SELECT command.
The SQL command types are various ways to handle the database structure, perform data operations, and regulate access.SQL 命令类型有多种方式来处理数据库结构、执行数据操作和规范访问权限。
809. Explain the difference between a correlated subquery and a nested subquery.
解释相关子查询和嵌套子查询之间的区别。
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d66 | 官方: 否 | 付费: 否
答案:
- Correlated Subquery: References data from the outer query in its WHERE clause.
- Nested Subquery: This can be placed anywhere in the outer query and does not directly reference the outer table.
810. How do window functions work?
窗口函数如何工作?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d69 | 官方: 否 | 付费: 否
答案:
Window functions perform calculations across related rows without collapsing them like GROUP BY.
窗口函数在相关行之间执行计算,而不会像 GROUP BY 那样合并它们。
Example: RANK() OVER (PARTITION BY department ORDER BY salary DESC) ranks salaries within each department. They’re powerful for running totals, rankings, and moving averages while preserving original rows.
示例:RANK() OVER (PARTITION BY department ORDER BY salary DESC) 对每个部门内的工资进行排名。它们对于运行总计、排名和移动平均值非常强大,同时保留原始行。
811. What is a trigger?
什么是触发器?
- 知识点: 数据库 (主题: sql, database;标签: intellipaat, sql, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5d58d557c902bc7d6c | 官方: 否 | 付费: 否
答案:
The trigger is used to do an automatic process when a particular event happens in the database or table. It helps in maintaining the integrity of the table and associated tables. The trigger can be activated when SQL commands like insert, update, and delete are fired. The syntax used to generate the trigger function is as follows:
触发器用于在数据库或表中发生特定事件时自动执行过程。它有助于维护表及相关表的完整性。当执行如 insert、update 和 delete 等 SQL 命令时,触发器可以被激活。用于生成触发器函数的语法如下:
CREATE TRIGGER trigger_name copy
CREATE TRIGGER trigger_name copy
812. How do you find the Top N rows per group?
如何查找每个组中的前 N 行?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5e58d557c902bc7e5f | 官方: 否 | 付费: 否
答案:
To find the Top N rows per group, a window function is used to rank rows within each group, followed by filtering based on that rank. This approach avoids grouping the data and allows row-level details to be retained.
要查找每个组的前 N 行,使用窗口函数对每个组内的行进行排名,然后基于该排名进行过滤。此方法避免了对数据进行分组,并允许保留行级细节。
The common method is to use ROW_NUMBER , RANK , or DENSE_RANK with PARTITION BY , and then filter the ranked results in an outer query.
常见方法是使用带有 PARTITION BY 的 ROW_NUMBER 、 RANK 或 DENSE_RANK ,然后在外部查询中过滤排名后的结果。
Example: Finding the top 3 highest-paid employees in each department.
示例:找出每个部门薪资最高的前3名员工。
SELECT *
SELECT *
FROM (
FROM (
SELECT
选择
department_id,
department_id,
employee_name,
employee_name,
salary,
salary,
ROW_NUMBER() OVER (
ROW_NUMBER() OVER (
PARTITION BY department_id
PARTITION BY department_id
ORDER BY salary DESC
ORDER BY salary DESC
) AS rn
) AS rn
FROM employees
FROM employees
) ranked
) ranked
WHERE rn <= 3;
WHERE rn <= 3;
In this example: - Rows are partitioned by department_id
在此示例中:- 行按 department_id 进行分区
- Employees are ranked by salary within each department
Only the top 3 rows per department are selected
If ties need to be handled differently, RANK or DENSE_RANK can be used instead of ROW_NUMBER . The choice depends on whether duplicate ranks should be included or limited.如果需要以不同方式处理平局,可以使用 RANK 或 DENSE_RANK 代替 ROW_NUMBER 。选择取决于重复排名是应包含还是应限制。
813. What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?
ROW_NUMBER、RANK 和 DENSE_RANK 之间有什么区别?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5e58d557c902bc7e62 | 官方: 否 | 付费: 否
答案:
ROW_NUMBER , RANK , and DENSE_RANK are window functions used to assign ranking values to rows within a partition, based on a specified ordering. The key difference between them lies in how they handle ties. - ROW_NUMBER assigns a unique sequential number to each row, even if two rows have the same values. Tied rows are given different numbers based on their order.
ROW_NUMBER、RANK 和 DENSE_RANK 是窗口函数,用于根据指定排序在分区内为行分配排名值。它们之间的关键区别在于如何处理并列情况。- ROW_NUMBER 为每行分配一个唯一的连续编号,即使两行具有相同的值。并列的行会根据其顺序获得不同的编号。
- RANK assigns the same rank to tied rows, but skips the next rank values. This results in gaps in the ranking sequence.
DENSE_RANK also assigns the same rank to tied rows, but does not skip any ranks. The ranking remains continuous.
Example: Ranking employees by salary within a department.示例:按部门内员工的薪资进行排名。
SELECT
选择
department_id,
department_id,
employee_name,
employee_name,
salary,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS row_num,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS row_num,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank_val,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank_val,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dense_rank_val
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dense_rank_val
FROM employees;
FROM employees;
If two employees have the same salary: - ROW_NUMBER will assign different numbers
如果两名员工具有相同的薪资:- ROW_NUMBER 将分配不同的编号
- RANK will assign the same rank and skip the next rank
DENSE_RANK will assign the same rank without skipping
Choosing the right function depends on whether gaps in ranking are acceptable and whether unique row ordering is required.选择正确的函数取决于排名中是否允许存在间隔,以及是否需要唯一的行排序。
814. What is a window function?
什么是窗口函数?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: coding
- 分类: fullstack
- id: 69b37c5e58d557c902bc7e65 | 官方: 否 | 付费: 否
答案:
A window function performs a calculation across a set of rows that are related to the current row, without collapsing the result into a single output row. Also, window functions do not reduce the number of rows returned like how it happens with aggregate functions.
窗口函数对与当前行相关的一组行执行计算,而不会将结果折叠为单个输出行。此外,窗口函数不会像聚合函数那样减少返回的行数。
Window functions are defined using the OVER clause, which specifies how rows are grouped and ordered for the calculation.
窗口函数使用 OVER 子句定义,该子句指定了计算中行的分组和排序方式。
Window functions form an important category of SQL window functions interview questions, especially for analytics and data-focused roles.
窗口函数构成了 SQL 窗口函数面试问题中的一个重要类别,尤其是在分析和数据导向的职位中。
The OVER clause commonly includes: - PARTITION BY - divides the result set into partitions (similar to GROUP BY)
OVER 子句通常包含:- PARTITION BY - 将结果集分区(类似于 GROUP BY)
ORDER BY - defines the order of rows within each partition
Example: Calculating a running total of sales per department.示例:计算每个部门的销售累计总额。
SELECT
选择
department_id,
department_id,
order_date,
order_date,
amount,
amount,
SUM(amount) OVER (
SUM(amount) OVER (
PARTITION BY department_id
PARTITION BY department_id
ORDER BY order_date
ORDER BY order_date
) AS running_total
) AS running_total
FROM orders;
FROM orders;
In this example: - Rows are grouped by department_id
在此示例中:- 行按 department_id 分组
- Within each department, rows are ordered by order_date
The running total is calculated for each row without grouping the results
Window functions are commonly used for ranking, running totals, moving averages, and comparisons across rows. They are especially useful in analytical queries where row-level detail must be preserved.窗口函数通常用于排名、累计总额、移动平均值以及跨行比较。它们在必须保留行级细节的分析查询中尤其有用。
815. What is the difference between a CTE and a subquery?
CTE 和子查询之间有什么区别?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e6c | 官方: 否 | 付费: 否
答案:
A subquery is a query nested inside another SQL query, whereas a CTE (Common Table Expression) is a named temporary result set defined using the WITH clause and referenced later in the main query.
子查询是嵌套在另一个 SQL 查询中的查询,而 CTE(公用表表达式)是使用 WITH 子句定义的命名临时结果集,可在主查询中稍后引用。
The main difference between the two is in their readability, reusability, and scope.
两者之间的主要区别在于可读性、可重用性和作用域。
Subqueries are useful for simple, one-time operations, but they can become difficult to read and maintain when deeply nested. Each subquery exists only at the point where it is written and cannot be reused elsewhere in the same query.
子查询适用于简单的单次操作,但在深度嵌套时可能难以阅读和维护。每个子查询仅存在于其编写的位置,不能在同一查询中的其他地方重用。
CTEs , on the other hand, allow complex logic to be written once and referenced multiple times within the same query. By giving intermediate results a name, CTEs make queries easier to read, debug, and modify. This is especially helpful in queries involving multiple joins, aggregations, or step-by-step transformations.
另一方面,CTE允许将复杂逻辑编写一次并在同一查询中多次引用。通过为中间结果命名,CTE使查询更易于阅读、调试和修改。这在涉及多个连接、聚合或逐步转换的查询中尤其有用。
Scope-wise, both CTEs and subqueries exist only for the duration of the query in which they are defined. However, a CTE’s scope is clearer and more flexible within that query, as it can be referenced multiple times, while a subquery is limited to its immediate context.
在作用范围方面,CTE和子查询都仅存在于其定义所在查询的持续期间内。然而,在该查询中,CTE的作用范围更清晰且更灵活,因为它可以被多次引用,而子查询则仅限于其直接上下文。
In usage, subqueries are preferred for small, straightforward conditions, while CTEs are better suited for complex queries where readability and logical separation are important.
在使用上,子查询适用于小型、直接的条件,而CTE更适合复杂查询,其中可读性和逻辑分离至关重要。
Many of these topics are also asked as SQL queries interview questions, where candidates are expected to write or reason through queries instead of explaining concepts verbally.
其中许多主题也常被作为SQL查询面试题提出,候选人需要编写或推理查询,而不是口头解释概念。
816. What is a CTE, and when should you use it?
什么是CTE,何时应该使用它?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e6f | 官方: 否 | 付费: 否
答案:
A CTE (Common Table Expression) is a temporary result set that can be referenced within a SELECT , INSERT , UPDATE , or DELETE statement. It is defined using the WITH keyword and exists only for the duration of the query in which it is used.
CTE(通用表表达式)是一个临时结果集,可在SELECT、INSERT、UPDATE或DELETE语句中引用。它使用WITH关键字定义,并且仅在其使用的查询持续期间内存在。
CTEs are mainly used to improve the structure and readability of the query, especially when dealing with complex queries that involve multiple steps, aggregations, or intermediate results. Instead of nesting subqueries, a CTE allows breaking the logic into smaller, more understandable parts.
CTE主要用于改善查询的结构和可读性,特别是在处理涉及多个步骤、聚合或中间结果的复杂查询时。与其嵌套子查询,CTE允许将逻辑分解为更小、更容易理解的部分。
CTEs are commonly used when: - A query requires the same subquery logic multiple times
CTE通常在以下情况下使用:- 一个查询需要多次使用相同的子查询逻辑
- Complex joins, or aggregations, need to be organized clearly
Recursive queries are required (for hierarchical data)
Example: Using a CTE to find employees with salaries above the department average.示例:使用CTE查找薪水高于部门平均水平的员工。
WITH dept_avg AS (
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
FROM employees
GROUP BY department_id
GROUP BY department_id
)
SELECT e.employee_id, e.salary
SELECT e.employee_id, e.salary
FROM employees e
FROM employees e
JOIN dept_avg d
JOIN dept_avg d
ON e.department_id = d.department_id
ON e.department_id = d.department_id
WHERE e.salary >
WHERE e.salary >
In this example, the CTE dept_avg computes the average salary per department, which is then reused in the main query to filter employees. This approach is clearer and easier to maintain than writing the same logic as a nested subquery.
在此示例中,CTE dept_avg 计算每个部门的平均工资,然后在主查询中复用该结果来过滤员工。这种方法比将相同逻辑写成嵌套子查询更清晰,也更易于维护。
817. How do you find the latest record per user?
如何查找每个用户的最新记录?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e72 | 官方: 否 | 付费: 否
答案:
To find the latest record per user, a window function is used to rank records for each user based on a timestamp or date column. The most common approach is to apply ROW_NUMBER with descending order and then filter for the first row.
要查找每个用户的最新记录,可以使用窗口函数根据时间戳或日期列对每个用户的记录进行排名。最常用的方法是应用 ROW_NUMBER 并降序排列,然后筛选第一行。
This method ensures that exactly one latest record is selected per user, even when multiple records exist.
这种方法确保为每个用户恰好选择一条最新记录,即使存在多条记录也是如此。
Example: Fetching the most recent order for each user.
示例:获取每个用户最近一次的订单。
SELECT *
SELECT *
FROM (
FROM (
SELECT
选择
user_id,
user_id,
order_id,
order_id,
order_date,
order_date,
ROW_NUMBER() OVER (
ROW_NUMBER() OVER (
PARTITION BY user_id
PARTITION BY user_id
ORDER BY order_date DESC
ORDER BY order_date DESC
) AS rn
) AS rn
FROM orders
FROM orders
) latest_orders
) latest_orders
WHERE rn = 1;
WHERE rn = 1;
In this query: - Records are grouped by user_id
在此查询中:- 记录按 user_id 分组
- Orders are ordered by order_date in descending order
The most recent record per user is selected by filtering rn = 1
This approach is preferred over aggregate-based methods because it preserves complete row details and handles ties in a controlled manner.这种方法优于基于聚合的方法,因为它保留了完整的行详细信息,并以可控的方式处理并列情况。
818. What are transaction isolation levels?
什么是事务隔离级别?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e75 | 官方: 否 | 付费: 否
答案:
Transaction isolation levels define how and when the changes made by one transaction become visible to other concurrent transactions. They control the balance between data consistency and performance in a database system.
事务隔离级别定义了由一个事务所做的更改何时以及如何对其他并发事务可见。它们控制着数据库系统中数据一致性与性能之间的平衡。
SQL defines four standard isolation levels, each preventing certain types of anomalies.
SQL 定义了四种标准隔离级别,每种级别都防止特定类型的异常。
Common anomalies: - Dirty read: Reading data that has been modified but not yet committed
常见的异常:- 脏读:读取已修改但尚未提交的数据
- Non-repeatable read: Reading the same row twice and getting different values
Phantom read: Re-running a query and seeing new rows that were not visible earlier
Isolation levels and what they prevent: - READ UNCOMMITTED Allows dirty reads, non-repeatable reads, and phantom reads. It offers the highest concurrency but the lowest data consistency.隔离级别及其所防止的异常:- 读未提交 允许脏读、不可重复读和幻读。它提供最高的并发性,但数据一致性最低。
- READ COMMITTED Prevents dirty reads but allows non-repeatable reads and phantom reads. This is the default level in many databases.
- REPEATABLE READ Prevents dirty reads and non-repeatable reads, but phantom reads may still occur depending on the database implementation.
SERIALIZABLE Prevents all anomalies by making transactions behave as if they are executed one after another. This provides the strongest consistency but can reduce concurrency.
Choosing the right isolation level depends on the use case. Systems that prioritize accuracy use higher isolation, while high-throughput systems may accept some anomalies for better performance.选择正确的隔离级别取决于使用场景。注重准确性的系统使用较高的隔离级别,而高吞吐量的系统为了获得更好的性能可能会接受一些异常。
819. What is a deadlock and how do you avoid it?
什么是死锁,如何避免它?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e78 | 官方: 否 | 付费: 否
答案:
A deadlock occurs when two or more transactions block each other indefinitely because each transaction is holding a lock that the other needs. As a result, none of the transactions can proceed, and the database must intervene to resolve the situation.
当两个或多个事务无限期地相互阻塞时,就会发生死锁,因为每个事务都持有着另一个事务所需的锁。结果是,没有任何事务能够继续执行,数据库必须介入以解决这种情况。
Deadlocks commonly happen when: - Transactions acquire locks on the same resources in different orders
死锁通常发生在以下情况:- 事务以不同的顺序获取相同资源上的锁
- Long-running transactions hold locks for extended periods
Multiple rows or tables are locked within a single transaction
Example scenario: Transaction A locks Table X and waits for Table Y, while Transaction B locks Table Y and waits for Table X. Neither transaction can continue, resulting in a deadlock.示例场景:事务 A 锁定表 X 并等待表 Y,而事务 B 锁定表 Y 并等待表 X。这两个事务都无法继续,导致死锁。
Ways to avoid deadlocks: - Use consistent lock ordering: Ensure all transactions acquire locks in the same order
避免死锁的方法:- 使用一致的锁顺序:确保所有事务以相同的顺序获取锁
- Keep transactions short: Commit or roll back as early as possible
- Avoid unnecessary locks by accessing only required rows
- Use appropriate isolation levels to reduce lock contention
Handle deadlock retries gracefully, as most databases automatically roll back one transaction
Databases detect deadlocks automatically and resolve them by terminating one of the transactions. Writing queries with predictable lock behavior and consistent ordering significantly reduces the likelihood of deadlocks.数据库会自动检测死锁,并通过终止其中一个事务来解决它们。编写具有可预测锁行为和一致顺序的查询,能显著降低死锁发生的可能性。
While syntax may vary slightly, most of these concepts apply equally to SQL Server interview questions and Oracle SQL interview questions, making them useful across database platforms.
虽然语法可能略有差异,但这些概念大多同样适用于 SQL Server 面试题和 Oracle SQL 面试题,使其在各种数据库平台上都具有实用性。
820. What causes double counting in joins and how can it be prevented?
连接中导致重复计数(双计数)的原因是什么,如何防止?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e7b | 官方: 否 | 付费: 否
答案:
Double counting in joins usually occurs when tables are joined in a many-to-many relationship without proper aggregation or filtering. In such cases, rows from one table match multiple rows in another, causing values to be repeated and summed more than once.
连接中的重复计数通常发生在表以多对多关系连接且未进行适当聚合或过滤时。在这种情况下,一个表中的行会匹配另一个表中的多行,导致值被重复并多次求和。
Concepts like joins, anti-joins, and many-to-many relationships are asked through SQL joins interview questions.
连接、反连接和多对多关系等概念,常通过 SQL 连接面试题来考察。
This is commonly seen when: - Fact tables are joined directly without aggregation
这常见于:- 事实表未经聚合直接连接
- Dimension tables contain multiple matching rows
Join conditions are incomplete or incorrect
Example: If an orders table is joined with an order_items table, each order appears once for every item it contains. Summing order-level values after this join can lead to inflated results.示例:如果订单表与订单项表连接,每个订单会为其包含的每个项目出现一次。连接后对订单级别值求和可能导致结果虚增。
SELECT
选择
SUM(o.total_amount)
SUM(o.total_amount)
FROM orders o
FROM orders o
JOIN order_items i
JOIN order_items i
ON o.order_id = i.order_id;
ON o.order_id = i.order_id;
Here, total_amount is repeated for each item, causing double counting.
这里,total_amount 为每个项目重复出现,导致重复计数。
Ways to prevent double counting: - Aggregate before joining, especially in many-to-many relationships
防止重复计数的方法:- 在连接前进行聚合,尤其是在多对多关系中
- Use DISTINCT carefully when appropriate
- Join at the correct grain, ensuring both tables represent data at compatible levels
Use subqueries or CTEs to reduce data before the join
Corrected approach (aggregate first):修正方法(先聚合):
SELECT
选择
SUM(order_total)
SUM(order_total)
FROM (
FROM (
SELECT
选择
order_id,
order_id,
MAX(total_amount) AS order_total
MAX(total_amount) AS order_total
FROM orders
FROM orders
GROUP BY order_id
GROUP BY order_id
) o;
) o;
Preventing double counting requires understanding the data grain of each table and ensuring joins are designed to preserve it. This is especially important in reporting
防止重复计算需要理解每个表的数据粒度,并确保连接设计能够保持该粒度。这在报表中尤为重要
821. How do you handle slowly changing dimensions (SCD Type 2)?
您如何处理缓慢变化维度(SCD 类型 2)?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e80 | 官方: 否 | 付费: 否
答案:
lowly Changing Dimension (SCD) Type 2 is a technique used to preserve the full history of changes in dimension tables. Instead of updating existing records, a new row is inserted whenever a tracked attribute changes, while the old record is marked as inactive.
缓慢变化维度(SCD)类型 2 是一种用于保留维度表中完整变更历史的技术。当跟踪的属性发生变化时,不会更新现有记录,而是插入新行,同时将旧记录标记为无效。
This approach is commonly used in data warehouses to track historical changes in attributes such as customer address, job title, or product category.
这种方法常用于数据仓库中,以跟踪客户地址、职位或产品类别等属性的历史变化。
An SCD Type 2 table typically includes: - A surrogate key (unique row identifier)
SCD 类型 2 表通常包括:- 代理键(唯一行标识符)
- Effective start and end dates
A flag to indicate the current active record
Example: Dimension table structure for tracking customer history.示例:用于跟踪客户历史的维度表结构。
customer_dim
customer_dim
customer_sk
customer_sk
customer_id
customer_id
address
address
start_date
start_date
end_date
结束日期
is_current
是否当前
When a customer’s address changes:
当客户地址变更时:
The existing active record is updated to set end_date and mark it as inactive 2. A new record is inserted with the updated address and marked as current
- 现有有效记录被更新,设置结束日期并标记为无效 2. 插入一条新记录,包含更新后的地址并标记为当前
-- Expire existing record
-- 使现有记录失效
UPDATE customer_dim
更新客户维度表
SET end_date = CURRENT_DATE,
设置结束日期 = 当前日期,
is_current = 'N'
是否当前 = 'N'
WHERE customer_id = 101
其中客户ID = 101
AND is_current = 'Y';
且是否当前 = 'Y';
-- Insert new record
-- 插入新记录
INSERT INTO customer_dim (
插入到客户维度表(
customer_id, address, start_date, end_date, is_current
客户ID, 地址, 开始日期, 结束日期, 是否当前
)
VALUES (
值(
101, 'New Address', CURRENT_DATE, NULL, 'Y'
101, '新地址', 当前日期, NULL, 'Y'
);
This method ensures that historical data is preserved and reports can accurately reflect changes over time. SCD Type 2 is widely used when auditability and time-based analysis are required.
此方法确保历史数据得到保留,报告能准确反映随时间的变化。当需要可审计性和基于时间的分析时,SCD类型2被广泛使用。
822. What is MERGE/UPSERT and when should it be used?
什么是 MERGE/UPSERT,何时应该使用它?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e85 | 官方: 否 | 付费: 否
答案:
MERGE (also known as UPSERT) is an operation that allows inserting new rows and updating existing rows in a single statement. It compares records from a source dataset with a target table and decides whether to insert or update based on a matching condition.
MERGE(也称为 UPSERT)是一种操作,允许在单个语句中插入新行并更新现有行。它将源数据集中的记录与目标表进行比较,并根据匹配条件决定是插入还是更新。
MERGE/UPSERT is especially useful in incremental data loads, where only new or changed records need to be applied instead of reloading the entire table.
MERGE/UPSERT 在增量数据加载中特别有用,此时只需应用新增或变更的记录,而不是重新加载整个表。
This approach helps: - Avoid duplicate records
这种方法有助于:- 避免重复记录
- Reduce data processing time
Keep target tables in sync with source data
Example: Updating existing customer records and inserting new ones.示例:更新现有客户记录并插入新记录。
MERGE INTO customers t
MERGE INTO customers t
USING staging_customers s
USING staging_customers s
ON t.customer_id = s.customer_id
ON t.customer_id = s.customer_id
WHEN MATCHED THEN
WHEN MATCHED THEN
UPDATE SET
UPDATE SET
t.name = s.name,
t.name = s.name,
t.email = s.email
t.email = s.email
WHEN NOT MATCHED THEN
WHEN NOT MATCHED THEN
INSERT (customer_id, name, email)
INSERT (customer_id, name, email)
VALUES (s.customer_id, s.name, s.email);
VALUES (s.customer_id, s.name, s.email);
In this example: - Existing customers are updated
在此示例中:- 现有客户被更新
- New customers are inserted
Both actions happen in a single statement
MERGE/UPSERT is commonly used in ETL pipelines, data warehouses, and sync jobs where data arrives incrementally and needs to be applied efficiently.MERGE/UPSERT 常用于ETL管道、数据仓库和同步作业中,这些场景下数据会增量到达且需要高效应用。
823. What is partitioning and why does it help?
什么是分区,为什么它有帮助?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e88 | 官方: 否 | 付费: 否
答案:
Partitioning is a database technique where a large table is divided into smaller, more manageable pieces called partitions, based on the values of one or more columns. Each partition holds a subset of the data, but together they represent the full table.
分区是一种数据库技术,它将一个大表根据一个或多个列的值划分为更小、更易管理的部分,称为分区。每个分区包含数据的一个子集,但共同代表完整的表。
Partitioning helps improve performance through a mechanism called partition pruning. When a query includes a filter on the partition key, the database can skip irrelevant partitions and scan only the required ones. This reduces the amount of data read and speeds up query execution.
分区通过一种称为分区裁剪的机制来提高性能。当查询包含对分区键的过滤条件时,数据库可以跳过不相关的分区,只扫描所需的那些分区。这减少了读取的数据量,加快了查询执行速度。
Partitioning is commonly done using: - Range partitioning (e.g., by date)
分区通常通过以下方式进行: - 范围分区(例如,按日期)
- List partitioning (e.g., by region or category)
Hash partitioning (for even data distribution)
Example: Partitioning an orders table by order date.示例:按订单日期对orders表进行分区。
CREATE TABLE orders (
CREATE TABLE orders (
order_id INT,
order_id INT,
order_date DATE,
order_date DATE,
amount DECIMAL
amount DECIMAL
)
PARTITION BY RANGE (order_date);
PARTITION BY RANGE (order_date);
When a query filters by a specific date range:
当查询按特定日期范围过滤时:
SELECT *
SELECT *
FROM orders
FROM orders
WHERE order_date >= '2024-01-01'
WHERE order_date >= '2024-01-01'
AND order_date < '2024-02-01';
AND order_date < '2024-02-01';
Only the partitions covering January 2024 are scanned, while others are ignored.
仅扫描覆盖2024年1月的分区,其他分区将被忽略。
Partitioning is especially useful for large tables, time-based data, and analytical queries where filtering on the partition key is common.
分区对于大型表、基于时间的数据和按分区键进行过滤的常见分析查询尤其有用。
824. What is a materialized view and when should it be used?
什么是物化视图,何时应该使用它?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e8b | 官方: 否 | 付费: 否
答案:
A materialized view is a database object that stores the precomputed result of a query physically on disk. Unlike a regular view, which runs the underlying query every time it is accessed, a materialized view returns stored results, making read operations much faster.
物化视图是一种数据库对象,将查询的预计算结果物理存储在磁盘上。与每次访问时都运行底层查询的普通视图不同,物化视图返回存储的结果,使读操作速度更快。
Materialized views are useful when queries involve heavy aggregations, joins, or transformations and are executed frequently on relatively static data.
当查询涉及大量聚合、连接或转换,并且对相对静态的数据频繁执行时,物化视图非常有用。
The main trade-off when using materialized views is data freshness versus performance. Since the data is stored, it must be refreshed to reflect changes in the underlying tables.
使用物化视图的主要权衡是数据新鲜度与性能。由于数据被存储,必须刷新以反映底层表的变化。
Materialized views are typically used when: - Query performance is critical
物化视图通常在以下情况下使用:- 查询性能至关重要
- The underlying data changes less frequently
Slightly stale data is acceptable
Example: Creating a materialized view for daily sales totals.示例:为每日销售总额创建物化视图。
CREATE MATERIALIZED VIEW daily_sales AS
CREATE MATERIALIZED VIEW daily_sales AS
SELECT
选择
order_date,
order_date,
SUM(amount) AS total_sales
SUM(amount) AS total_sales
FROM orders
FROM orders
GROUP BY order_date;
GROUP BY order_date;
The materialized view can be refreshed based on requirements:
物化视图可以根据需求进行刷新:
REFRESH MATERIALIZED VIEW daily_sales;
REFRESH MATERIALIZED VIEW daily_sales;
Choosing between on-demand or scheduled refresh depends on how up-to-date the data needs to be. Materialized views are commonly used in reporting and analytics systems to reduce query load and improve performance.
选择按需刷新或计划刷新取决于数据需要多新。物化视图通常用于报表和分析系统中,以减少查询负载并提高性能。
825. What is a covering index?
什么是覆盖索引?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e8e | 官方: 否 | 付费: 否
答案:
A covering index is an index that contains all the columns required by a query, so the database engine can retrieve the result directly from the index without accessing the underlying table.
覆盖索引是包含查询所需所有列的索引,因此数据库引擎可以直接从索引中检索结果,而无需访问底层表。
When a covering index is used, the database avoids additional table (or heap) lookups, which significantly improves query performance, especially for read-heavy workloads.
使用覆盖索引时,数据库可避免额外的表(或堆)查找,这显著提升了查询性能,尤其是在读密集型工作负载中。
This works because indexes store not only the indexed columns but also pointers to the data. If every column referenced in the SELECT , WHERE , and JOIN clauses is already present in the index, the table itself does not need to be read.
这之所以有效,是因为索引不仅存储了被索引的列,还存储了指向数据的指针。如果SELECT、WHERE和JOIN子句中引用的每一列都已存在于索引中,则无需读取表本身。
Example: Query fetching order details filtered by status and date.
示例:按状态和日期筛选获取订单详情的查询。
SELECT order_id, order_date
SELECT order_id, order_date
FROM orders
FROM orders
WHERE status = 'completed'
WHERE status = 'completed'
AND order_date >= '2024-01-01';
AND order_date >= '2024-01-01';
A covering index for this query would be:
此查询的覆盖索引将是:
CREATE INDEX idx_orders_covering
CREATE INDEX idx_orders_covering
ON orders (status, order_date, order_id);
ON orders (status, order_date, order_id);
In this case: - status and order_date support filtering
在这种情况下:- status和order_date支持筛选
order_id is included to satisfy the SELECT clause
Because all required columns are present in the index, the query can be answered entirely using the index, avoiding table access. Covering indexes are especially useful for frequently executed queries that return a limited set of columns.因为所有必需的列都存在于索引中,查询可以完全使用索引来回答,从而避免表访问。覆盖索引对于频繁执行且返回有限列集的查询尤其有用。
826. What are composite indexes and how do you choose column order?
什么是复合索引,如何选择列顺序?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e91 | 官方: 否 | 付费: 否
答案:
A composite index is an index created on multiple columns of a table. It is used to speed up queries that filter or sort data based on more than one column.
复合索引是在表的多个列上创建的索引。它用于加速基于多个列筛选或排序数据的查询。
The order of columns in a composite index matters because the database can efficiently use the index only from the leftmost prefix of the index definition.
复合索引中列的顺序很重要,因为数据库只能从索引定义的最左前缀有效地使用索引。
A common rule for choosing column order is: - Place equality conditions first
选择列顺序的一个常见规则是:- 将等值条件放在前面
Place range conditions (such as , BETWEEN) after them
This allows the index to narrow down rows as much as possible before applying range filtering.这允许索引在应用范围过滤之前尽可能多地缩小行范围。
Example: Query filtering by status (equality) and date (range).
示例:按 status(等值)和 date(范围)过滤的查询。
SELECT *
SELECT *
FROM orders
FROM orders
WHERE status = 'completed'
WHERE status = 'completed'
AND order_date >= '2024-01-01';
AND order_date >= '2024-01-01';
An effective composite index for this query would be:
对此查询有效的复合索引为:
CREATE INDEX idx_orders_status_date
CREATE INDEX idx_orders_status_date
ON orders (status, order_date);
ON orders (status, order_date);
Here: - status uses an equality condition and is placed first
这里:- status 使用等值条件并放在首位
order_date uses a range condition and is placed second
If the column order were reversed, the index would be less effective for this query. Choosing the correct column order in composite indexes is essential for optimal query performance.如果列顺序颠倒,该索引对此查询的效果会较差。在复合索引中选择正确的列顺序对于最佳查询性能至关重要。
827. How do you optimize a slow query?
如何优化慢查询?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e94 | 官方: 否 | 付费: 否
答案:
Optimizing a slow query starts with understanding where time and resources are being spent. The most effective optimizations usually focus on reducing the number of rows processed early and ensuring that indexes are used correctly.
优化慢查询首先要了解时间和资源花费在哪里。最有效的优化通常集中在早期减少处理的行数,并确保正确使用索引。
A common first step is to analyze the query using an execution plan ( EXPLAIN ) to identify full table scans, inefficient joins, or missing indexes.
常见的第一步是使用执行计划(EXPLAIN)分析查询,以识别全表扫描、低效的连接或缺失索引。
Key optimization techniques include: - Filtering rows as early as possible using selective WHERE conditions
关键的优化技术包括:- 使用有选择性的 WHERE 条件尽早筛选行
- Creating appropriate indexes on columns used in filters, joins, and sorting
- Avoiding non-sargable conditions, such as functions on indexed columns
- Selecting only required columns instead of using SELECT *
Reordering joins so that smaller or filtered datasets are processed first
Example: Filtering rows early to reduce data scanned.示例:尽早筛选行以减少扫描的数据量。
SELECT order_id, order_date, amount
SELECT order_id, order_date, amount
FROM orders
FROM orders
WHERE order_date >= '2024-01-01'
WHERE order_date >= '2024-01-01'
AND status = 'completed';
AND status = 'completed';
If order_date and status are indexed appropriately, this query limits the number of rows before further processing, improving performance.
如果 order_date 和 status 被适当地索引,此查询会在进一步处理前限制行数,从而提高性能。
In practice, query optimization is an iterative process that combines execution plan analysis, proper indexing, and query rewriting to minimize unnecessary data access.
在实践中,查询优化是一个迭代过程,它结合了执行计划分析、恰当的索引和查询重写,以最小化不必要的数据访问。
828. What is an execution plan (EXPLAIN)?
什么是执行计划(EXPLAIN)?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e97 | 官方: 否 | 付费: 否
答案:
An execution plan describes how a database engine executes a SQL query. It shows the sequence of operations the optimizer chooses to retrieve data, such as table scans, index lookups, joins, and filtering steps. The EXPLAIN command is used to view this plan before or during query execution.
执行计划描述了数据库引擎如何执行 SQL 查询。它展示了优化器选择用于检索数据的操作序列,例如表扫描、索引查找、连接和过滤步骤。EXPLAIN 命令用于在查询执行前或执行期间查看此计划。
Execution plans help identify whether a query is using an index scan or a full table scan , which has a direct impact on performance. - Index scan: The database uses an index to quickly locate matching rows. This is generally faster and preferred for selective queries.
执行计划有助于识别查询是使用索引扫描还是全表扫描,这对性能有直接影响。- 索引扫描:数据库使用索引快速定位匹配的行。这通常更快,并且更适合选择性查询。
Table scan (or sequential scan): The database scans every row in the table. This can be expensive for large tables and usually indicates missing or unused indexes.
Example: Viewing the execution plan for a query.示例:查看查询的执行计划。
EXPLAIN
EXPLAIN
SELECT *
SELECT *
FROM orders
FROM orders
WHERE order_date >= '2024-01-01';
WHERE order_date >= '2024-01-01';
The output of EXPLAIN shows details such as: - Which indexes are used (if any)
EXPLAIN的输出显示了详细信息,例如:使用了哪些索引(如果有的话)
- The estimated number of rows processed
The cost of each operation
By analyzing an execution plan, inefficient scans can be detected early, allowing queries to be optimized through better indexing or query rewriting.通过分析执行计划,可以及早发现低效的扫描,从而通过更好的索引或查询重写来优化查询。
Questions related to indexing, execution plans, and query optimization often appear as SQL performance tuning interview questions, testing how efficiently a candidate can work with large datasets.
与索引、执行计划和查询优化相关的问题经常作为SQL性能调优面试问题出现,测试候选人处理大型数据集的效率。
829. What is sargability in SQL?
SQL中的sargability是什么?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e9a | 官方: 否 | 付费: 否
答案:
Sargability refers to whether a SQL query can efficiently use an index to filter rows. A query is considered sargable if the database engine can apply the search condition directly to an indexed column, rather than evaluating the condition row by row.
Sargability指的是SQL查询能否高效地使用索引来筛选行。如果数据库引擎可以直接将搜索条件应用于索引列,而不是逐行评估条件,则该查询被认为是sargable的。
Non-sargable conditions usually occur when functions, calculations, or transformations are applied to indexed columns in the WHERE clause. This prevents the query optimizer from using the index effectively, leading to full table scans.
非sargable条件通常发生在WHERE子句中对索引列应用函数、计算或转换时。这会阻止查询优化器有效使用索引,导致全表扫描。
Example: A non-sargable condition that prevents index usage.
示例:一个阻止索引使用的非sargable条件。
SELECT *
SELECT *
FROM orders
FROM orders
WHERE YEAR(order_date) = 2024;
WHERE YEAR(order_date) = 2024;
In this case, the function YEAR() is applied to the indexed column order_date , making the condition non-sargable.
在这种情况下,函数YEAR()被应用于索引列order_date,使得该条件成为非sargable的。
A sargable alternative rewrites the condition to avoid applying functions on the column:
一个sargable的替代方案通过重写条件以避免在列上应用函数:
SELECT *
SELECT *
FROM orders
FROM orders
WHERE order_date >= '2024-01-01'
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01';
AND order_date < '2025-01-01';
This version allows the database to use the index on order_date efficiently.
此版本允许数据库高效利用 order_date 上的索引。
Writing sargable queries is important for performance, especially when working with large tables and indexed columns.
编写可搜索(SARGable)查询对于性能至关重要,尤其是在处理大型表和索引列时。
830. What is the difference between NOT IN and NOT EXISTS?
NOT IN 和 NOT EXISTS 有什么区别?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql, topic-specific, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7e9d | 官方: 否 | 付费: 否
答案:
Both NOT IN and NOT EXISTS are used to filter rows that do not have matching values in a subquery. However, they behave differently when NULL values are involved, which is a common source of errors.
NOT IN 和 NOT EXISTS 都用于过滤子查询中没有匹配值的行。然而,当涉及 NULL 值时,它们的行为有所不同,而这正是常见的错误来源。
The key difference lies in how each handles NULLs. - NOT IN returns no rows if the subquery contains even a single NULL value. This happens because comparisons with NULL result in an unknown condition, causing the entire filter to fail.
关键区别在于各自如何处理 NULL。- 如果子查询中哪怕包含一个 NULL 值,NOT IN 就不会返回任何行。这是因为与 NULL 的比较会产生未知条件,导致整个过滤失败。
NOT EXISTS does not have this issue. It checks for the existence of matching rows and safely handles NULLs, making it more reliable in most cases.
Example: Finding users who have not placed any orders.示例:查找未下过任何订单的用户。
-- Using NOT IN (can fail if subquery returns NULL)
-- 使用 NOT IN(如果子查询返回 NULL,则可能失败)
SELECT user_id
SELECT user_id
FROM users
FROM users
WHERE user_id NOT IN (
WHERE user_id NOT IN (
SELECT user_id
SELECT user_id
FROM orders
FROM orders
);
If orders.user_id contains a NULL, this query may return no results.
如果 orders.user_id 包含 NULL,则此查询可能不返回任何结果。
-- Using NOT EXISTS (NULL-safe)
-- 使用 NOT EXISTS(NULL 安全)
SELECT u.user_id
SELECT u.user_id
FROM users u
FROM users u
WHERE NOT EXISTS (
WHERE NOT EXISTS (
SELECT 1
SELECT 1
FROM orders o
FROM orders o
WHERE o.user_id = u.user_id
WHERE o.user_id = u.user_id
);
While using, NOT EXISTS is generally preferred for anti-join conditions because it is NULL-safe and more predictable, especially when working with real-world data.
在使用时,NOT EXISTS 通常更受青睐,用于反连接条件,因为它对 NULL 安全且更具可预测性,尤其是在处理真实世界的数据时。
831. How should data be structured to support Join Operations in a one-to-many relationship?
在一对多关系中,应如何构建数据以支持连接操作?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7ee3 | 官方: 否 | 付费: 否
答案:
Among the most common types of database relationships are the ones involving one-to-many relationships. Consider the example of the Customer and Mobile table.
在最常见的数据库关系类型中,涉及一对多关系的那些属于其中之一。考虑 Customer 和 Mobile 表的示例。
Customer Table:
Customer 表:
| Customer_ID | First_Name | Last_Name | |
|---|---|---|---|
| 1 | Sasha | Frank | sashafrank@gmail.com |
| 2 | Isha | Joshi | ishajoshi@gmail.com |
| 3 | Danish | Khan | danishkhan@gmail.com |
| Customer_ID | First_Name | Last_Name | |
|---|---|---|---|
| 1 | Sasha | Frank | sashafrank@gmail.com |
| 2 | Isha | Joshi | ishajoshi@gmail.com |
| 3 | Danish | Khan | danishkhan@gmail.com |
Mobile Table:
Mobile 表:
| Mobile_ID | Customer_ID | OrderPlaced_Date |
|---|---|---|
| 1 | 1 | 2022-03-24 |
| 2 | 3 | 2021-05-22 |
| 3 | 2 | 2022-01-05 |
| 4 | 1 | 2020-10-14 |
| 5 | 2 | 2021-08-29 |
| Mobile_ID | Customer_ID | OrderPlaced_Date |
|---|---|---|
| 1 | 1 | 2022-03-24 |
| 2 | 3 | 2021-05-22 |
| 3 | 2 | 2022-01-05 |
| 4 | 1 | 2020-10-14 |
| 5 | 2 | 2021-08-29 |
A customer can own many mobile phones, but a mobile belongs to one customer only. Therefore, we've defined the Foreign Key column (Customer_ID) in the Mobile table allowing us to perform SELECT queries with JOIN clauses fairly easily.
一个客户可以拥有多部手机,但一部手机只属于一个客户。因此,我们在 Mobile 表中定义了外键列(Customer_ID),这使得我们能够相对容易地使用 JOIN 子句执行 SELECT 查询。
832. How should data be structured to support Join Operations in a many-to-many relationship?
在多对多关系中,应如何构建数据以支持连接操作?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7ee7 | 官方: 否 | 付费: 否
答案:
The many-to-many relationship is a bit more complex than the one-to-many relationship.
多对多关系比一对多关系稍微复杂一些。
Example: Consider a Student table and a Class table, both of which have many-to-many relationships: any student can be enrolled in many classes, and any class can have many students. It means an individual student may have many classes, and there may be many students in each class.
示例:考虑一个 Student 表和一个 Class 表,两者之间存在多对多关系:任何学生可以注册多门课程,任何课程可以有多名学生。这意味着一个学生可能有多门课程,而每门课程中可能有多个学生。
Student Table
Student 表
| Student_ID | Student_Name |
|---|---|
| 1 | Asha Bisht |
| 2 | Rohit Sharma |
| 3 | Karan Tacker |
| Student_ID | Student_Name |
|---|---|
| 1 | Asha Bisht |
| 2 | Rohit Sharma |
| 3 | Karan Tacker |
Class Table
班级表
| Class_ID | Class_Name |
|---|---|
| 1 | Maths 数学 |
| 2 | Science 科学 |
| 3 | English 英语 |
| 4 | Physical Education 体育 |
| 5 | Computer Science 计算机科学 |
In this case, we cannot add the primary key of one table to that of another, or to both of them, as this only stores a single relationship, while what we really need is multiple relationships. Thus, we use a concept called a bridging table or joining table. The joining tables are those that are placed between two other tables in a many-to-many relationship and are intended to hold a record for each combination of the two other tables. It may seem like quite a chunk of work, but the process is simple and provides a much better data structure. In this case, we will create a new table called ClassEnroll maintaining two columns, one for each of the primary keys of the other table. Those columns store separate records for every class and student combination.
在这种情况下,我们不能将一个表的主键添加到另一个表或同时添加到两个表中,因为这只能存储单一关系,而我们需要的是多重关系。因此,我们使用一个称为桥接表或连接表的概念。连接表是位于多对多关系中两个其他表之间的表,旨在为两个其他表的每种组合存储一条记录。这看起来可能工作量不小,但过程简单且能提供更好的数据结构。在这种情况下,我们将创建一个名为ClassEnroll的新表,包含两列,每列对应其他表的主键。这些列为每个班级和学生组合存储单独的记录。
ClassEnroll Table
ClassEnroll表
| Student_ID | Class_ID |
|---|---|
| 1 | 1 |
| 1 | 3 |
| 2 | 4 |
| 2 | 2 |
| 3 | 4 |
| 3 | 1 |
| Student_ID | Class_ID |
|---|---|
| 1 | 1 |
| 1 | 3 |
| 2 | 4 |
| 2 | 2 |
| 3 | 4 |
| 3 | 1 |
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
833. Explain natural join.
解释自然连接。
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7eea | 官方: 否 | 付费: 否
答案:
Natural Joins are a type of join that combines tables based on columns that share the same name and have the same datatype. Ideally, there should be a common attribute (column) among two tables in order to perform a natural join.
自然连接是一种基于具有相同名称和数据类型的列来合并表的连接类型。理想情况下,两个表之间应存在一个公共属性(列)才能执行自然连接。
Syntax:
语法:
SELECT * FROM TableName1 NATURAL JOIN TableName2;
SELECT * FROM TableName1 NATURAL JOIN TableName2;
Example: Consider two tables Employee and Employment.
示例:考虑两个表Employee和Employment。
Employee
Employee
| Emp_ID | Emp_Name |
|---|---|
| 1 | Khushboo Ahuja |
| 2 | Kartik Sharma |
| 3 | Milli Desai |
| Emp_ID | Emp_Name |
|---|---|
| 1 | Khushboo Ahuja |
| 2 | Kartik Sharma |
| 3 | Milli Desai |
Employment
Employment
| Emp_ID | Emp_Profile |
|---|---|
| 1 | Content Writer 内容编辑 |
| 2 | Business Development Executive 业务发展主管 |
| 3 | Marketing Manager 市场经理 |
Now, consider the following query.
现在,考虑以下查询。
SELECT * FROM Employee NATURAL JOIN Employment;
SELECT * FROM Employee NATURAL JOIN Employment;
Output:
输出:
| Emp_ID | Emp_Name | Emp_Profile |
|---|---|---|
| 1 | Khushboo Ahuja | Content Writer |
| 2 | Kartik Sharma | Business Development Executive |
| 3 | Milli Desai | Marketing Manager |
| Emp_ID | Emp_Name | Emp_Profile |
|---|---|---|
| 1 | Khushboo Ahuja | Content Writer |
| 2 | Kartik Sharma | Business Development Executive |
| 3 | Milli Desai | Marketing Manager |
834. What is a Non-Equi Join?
什么是非等值连接?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7ef1 | 官方: 否 | 付费: 否
答案:
A Non-Equi join entails pulling data from multiple tables by using an INNER join. This type of join matches the columns of two tables based on an inequality using operators such as , >=, !=, BETWEEN, etc.
非等值连接是通过使用内连接从多个表中提取数据。这种连接基于不等式,使用运算符(如 >、>=、!=、BETWEEN 等)匹配两个表的列。
Syntax:
语法:
SELECT * FROM TableName1, TableName2
SELECT * FROM TableName1, TableName2
WHERE TableName1.columnName [> | < | >= | <= | != | BETWEEN ] TableName2.columnName;
WHERE TableName1.columnName [> | < | >= | <= | != | BETWEEN ] TableName2.columnName;
835. What makes a Union clause different from a Join clause?
UNION 子句与 JOIN 子句有何不同?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7ef4 | 官方: 否 | 付费: 否
答案:
To combine data from two or more tables, you may use joins and UNIONS in your queries. - Join: Essentially, joins allow you to combine data into new columns horizontally. A join clause is an SQL command used in order to combine records from multiple tables or retrieve data from these tables based on the existence of a common field (column) between them. In JOIN, the columns of the joining tables may differ. Here is a visual representation of how a join looks. See how the columns from Tables A and B have been combined to generate the result.
要组合两个或多个表的数据,可以在查询中使用连接和 UNION。 - 连接:本质上,连接允许你将数据水平组合成新列。连接子句是一条 SQL 命令,用于根据多个表之间共同字段(列)的存在来组合记录或从这些表中检索数据。在 JOIN 中,连接表的列可能不同。以下是连接的可视化表示。请注意表 A 和表 B 的列是如何组合以生成结果的。
- Union: In SQL, the term UNION is used to combine the results of more than one SELECT statement. Union allows you to combine data into new rows vertically. UNION requires that all queries have the same number of columns and order of columns. Here is a visual representation of how a union looks. See how the columns from Tables A and B have been combined to generate the result.
836. Is it required that the Join condition be based on equality?
连接条件是否必须基于相等性?
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7ef7 | 官方: 否 | 付费: 否
答案:
No, joins can have non-equi conditions as well. Join clauses can be used with common comparison operators, such as , >=, !=, BETWEEN. For example, listing records, listing unique pairs, and identifying duplicate records are just a few situations where non-equi joins can prove to be useful.
不,连接也可以有非等值条件。连接子句可以与常见比较运算符一起使用,如 >、>=、!=、BETWEEN。例如,列出记录、列出唯一对以及识别重复记录只是非等值连接可以证明有用的一些情况。
837. State difference between Full Join and Cross Join.
说明全连接和交叉连接之间的区别。
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7efa | 官方: 否 | 付费: 否
答案:
- Cross Join: A Cross Join is also referred to as a Cartesian join or Cartesian product. The result set of a cross join is equal to all of the rows from the first table multiplied by all of the rows from the second table. It applies to all columns.
Syntax:
语法:
SELECT * FROM Table_1 CROSS JOIN Table_2;
SELECT * FROM Table_1 CROSS JOIN Table_2;
In the case of two lists, one consisting of 4, 5, 6, and the other consisting of a, b, and c, the Cartesian product between the two lists would be as follows:
对于两个列表,一个包含 4、5、6,另一个包含 a、b 和 c,这两个列表之间的笛卡尔积如下所示:
4a, 4b, 4c 5a, 5b, 5c 6a, 6b, 6c - Full Join: This is also referred to as a full outer join. In a full outer join, all rows of tables are combined to form a result set. It basically means that a query would return a result set from both tables, even if they had NULL values. A result set (joined table) will display NULL values if both tables do not contain any matching rows.
4a, 4b, 4c 5a, 5b, 5c 6a, 6b, 6c - 全连接:这也被称为全外连接。在全外连接中,所有表的行都被组合以形成结果集。这基本上意味着查询会从两个表返回结果集,即使它们有 NULL 值。如果两个表都没有匹配的行,结果集(连接后的表)将显示 NULL 值。
Syntax:
语法:
SELECT * FROM Table1 FULL OUTER JOIN Table2 ON Table1.column_name = Table2.column_name;
SELECT * FROM Table1 FULL OUTER JOIN Table2 ON Table1.column_name = Table2.column_name;
838. Explain CTE (Common Table Expression) SQL.
解释 SQL 中的 CTE(公用表表达式)。
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7efd | 官方: 否 | 付费: 否
答案:
Generally, Common Table Expressions (CTEs) are temporary named result sets that you can use to refer to within an UPDATE, INSERT, SELECT, or DELETE statement. The CTEs can be defined by adding a WITH before an UPDATE, INSERT, DELETE, SELECT, OR MERGE statement. Several CTEs may be used within the WITH clause, separated by commas.
通常,公用表表达式(CTE)是临时命名的结果集,你可以在 UPDATE、INSERT、SELECT 或 DELETE 语句中引用它们。可以通过在 UPDATE、INSERT、DELETE、SELECT 或 MERGE 语句之前添加 WITH 来定义 CTE。WITH 子句中可以包含多个 CTE,用逗号分隔。
839. Distinguish between nested subquery, correlated subquery, and join operation.
区分嵌套子查询、相关子查询和连接操作。
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7f00 | 官方: 否 | 付费: 否
答案:
- Join Operation: A join operation is a binary operation that combines the data or rows from two or more tables based on a field they have in common. There are different types of joins, such as INNER JOIN, FULL JOIN, LEFT JOIN, RIGHT JOIN, etc.
- Subquery: A query can be enclosed within another query, so the outer query is called the main query, and the inner query is called a subquery.
Nested Query: Nested queries execute the inner query first, and only once. An outer query is then executed based on the results of the inner query. The inner query is therefore used to execute the outer query.
嵌套查询:嵌套查询首先执行内层查询,且只执行一次。然后基于内层查询的结果执行外层查询。因此,内层查询用于执行外层查询。
Correlated Query: The outer query is executed first, and for every row of the outer query, the inner query is executed. Thus, values from the outer query are used in the inner query.
相关查询:外层查询首先执行,对于外层查询的每一行,内层查询都会被执行。因此,外层查询中的值会被用于内层查询。
840. State difference between Cross join and Natural Join.
说明交叉连接和自然连接之间的区别。
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-joins, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c5f58d557c902bc7f03 | 官方: 否 | 付费: 否
答案:
- Natural Join: Natural Joins are a type of join that combines tables based on columns that share the same name and have the same datatype. Ideally, there should be a common attribute (column) among two tables in order to perform a natural join.
- Cross Join: A Cross Join is also referred to as a Cartesian join or Cartesian product. The result set of a cross join is equal to all of the rows from the first table multiplied by all of the rows from the second table. It applies to all columns.
Conclusion
结论
SQL joins are a simple concept that everyone should be able to grasp, even if writing codes and handling them isn't hard. There is only one decision to make: which join to use. What you need to know is what join you should use, which is what makes joining so challenging at times. If you wish to become better at making such decisions, you should gain as much experience as possible, following which you will be more prepared to read and comprehend SQL Joins, understand data, and decide which join type to use. In this article, you will find a number of frequently asked SQL Joins interview questions and answers that will help you prepare convincing answers.
SQL连接是一个简单的概念,每个人都应该能够掌握,即使编写代码和处理它们并不困难。只需要做一个决定:使用哪种连接。你需要知道的是应该使用哪种连接,这正是连接有时具有挑战性的原因。如果你想在这方面做出更好的决定,你应该尽可能多地积累经验,这样你将更有能力阅读和理解SQL连接,理解数据,并决定使用哪种连接类型。在本文中,你将找到许多常见的SQL连接面试问题和答案,这将帮助你准备令人信服的回答。
At the end of the day, you should know that the goal is to provide a concise, yet well-illustrated answer that demonstrates your knowledge of the subject matter without going on and on. The best approach would be for you to give an example of a use case you have encountered while using this feature. Practice mock interviews and solve SQL interview questions before your actual interview, as this will boost your confidence and help you prepare for the different scenarios you may face. As previously noted, they are not attempting to certify you, but rather gauge your level of proficiency within your field. In that regard, bear in mind that you should act confidently, professionally, and courteously during the interview. Remember, interviews can be long and tiresome, so do not forget to smile!
归根结底,你应该知道目标是要提供一个简洁但说明充分的答案,以展示你对主题的理解,而不应冗长啰嗦。最好的方法是举一个你在使用此功能时遇到的用例示例。在实际面试前练习模拟面试并解决SQL面试问题,这将增强你的信心,并帮助你为可能面临的不同场景做好准备。如前所述,他们并非试图认证你,而是评估你在领域内的熟练程度。在这方面,请记住,在面试过程中你应该表现得自信、专业且礼貌。记住,面试可能漫长而令人疲惫,所以别忘了微笑!
Recommended Resources
推荐资源
- https://www.interviewbit.com/sql-interview-questions/
- https://www.interviewbit.com/sql-query-interview-questions/
- https://www.interviewbit.com/blog/characteristics-of-sql/
- https://www.interviewbit.com/blog/sql-projects/
- https://www.interviewbit.com/sql-mcq/
- https://www.interviewbit.com/blog/sql-books/
841. "Inner": When the tree node is an inner node, we label it as “Inner”
“内部”:当树节点是内部节点时,我们将其标记为“内部”
- 知识点: 数据库 (主题: sql, database;标签: interviewbit, sql-query, topic-specific, sql, database)
- 类型: technical | 难度: hard | 子类型: concept
- 分类: fullstack
- id: 69b37c6058d557c902bc7f2f | 官方: 否 | 付费: 否
答案:
Write a SQL query to find and return the type of each of the nodes in the given tree. You can return the result in any order.
编写一个 SQL 查询,查找并返回给定树中每个节点的类型。可以按任意顺序返回结果。
Example:
示例:
Input: Tree Table
输入:树表
| id | parent_id |
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 3 |
| 5 | 2 |
| id | parent_id |
|---|---|
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 3 |
| 5 | 2 |
Output:
输出:
| id | type |
| 1 | Root |
| 2 | Inner |
| 3 | Inner |
| 4 | Leaf |
| 5 | Leaf |
| id | type |
|---|---|
| 1 | Root |
| 2 | Inner |
| 3 | Inner |
| 4 | Leaf |
| 5 | Leaf |
Explanation:
说明:
Because node 1’s parent node is null, and it has child nodes 2 and 3, Node 1 is the root node. 2. Because node 2 and node 3 have parent node 1 and child nodes 5 and 4 respectively, Node 2 and node 3 are inner nodes. 3. Because nodes 4 and 5 have parent nodes but no child nodes, nodes 4, and 5 are leaf nodes.
- 因为节点 1 的父节点为 null,且有子节点 2 和 3,所以节点 1 是根节点。 2. 因为节点 2 和节点 3 有父节点 1 且分别有子节点 5 和 4,所以节点 2 和节点 3 是内部节点。 3. 因为节点 4 和 5 有父节点但没有子节点,所以节点 4 和 5 是叶节点。
Approach 1:
方法一:
In this approach, we subdivide our problem of categorizing the type of each of the nodes in the tree. We first find all the root nodes and add them to our resultant set with the type “root”. Then, we find all the leaf nodes and add them to our resultant set with the type “leaf”. Similarly, we find all the inner nodes and add them to our resultant set with the type “inner”. Now let us look at the query for finding each of the node types. - For root nodes:
在这种方法中,我们细分了分类树中每个节点类型的问题。首先,我们找到所有根节点,并将它们以“根”类型添加到结果集中。然后,我们找到所有叶节点,并将它们以“叶”类型添加到结果集中。类似地,我们找到所有内部节点,并将它们以“内部”类型添加到结果集中。现在,让我们查看查找每种节点类型的查询。- 对于根节点:
SELECT
选择
id, 'Root' AS Type
id, 'Root' AS Type
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NULL
parent_id IS NULL
Here, we check if the parent_id of the node is null, then we assign the type of node as ‘Root’ and include it in our result set. - For leaf nodes:
在这里,我们检查节点的 parent_id 是否为空,如果为空,则将节点类型赋值为 ‘Root’,并将其包含在结果集中。 - 对于叶节点:
SELECT
选择
id, 'Leaf' AS Type
id, 'Leaf' AS Type
FROM
从
tree
tree(树)
WHERE
其中
id NOT IN (SELECT DISTINCT
id NOT IN (SELECT DISTINCT
parent_id
parent_id(父节点ID)
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NOT NULL)
parent_id 不为空)
AND parent_id IS NOT NULL
且 parent_id 不为空
Here, we first find all the nodes that have a child node. Next, we check if the current node is present in the set of root nodes. If present, it cannot be a leaf node and we eliminate it from our answer set. We also check that the parent_id of the current node is not null. If both the conditions satisfy then we include it in our answer set. - For inner nodes:
在这里,我们首先找到所有拥有子节点的节点。接下来,我们检查当前节点是否存在于根节点集合中。如果存在,则它不能是叶节点,我们将其从答案集中排除。我们还检查当前节点的 parent_id 是否不为空。如果两个条件都满足,则将其包含在答案集中。 - 对于内部节点:
SELECT
选择
id, 'Inner' AS Type
id, 'Inner' AS Type
FROM
从
tree
tree(树)
WHERE
其中
id IN (SELECT DISTINCT
id IN (SELECT DISTINCT
parent_id
parent_id(父节点ID)
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NOT NULL)
parent_id 不为空)
AND parent_id IS NOT NULL
且 parent_id 不为空
Here, we first find all the nodes that have a child node. Next, we check if the current node is present in the set of root nodes. If not present, it cannot be an inner node and we eliminate it from our answer set. We also check that the parent_id of the current node is not null. If both the conditions satisfy then we include it in our answer set.
在这里,我们首先找到所有有子节点的节点。接下来,我们检查当前节点是否在根节点集合中。如果不在,则它不是内部节点,我们将其从答案集中排除。我们还检查当前节点的parent_id是否不为空。如果两个条件都满足,则将其包含在答案集中。
At last, we combine all three resultant sets using the UNION operator. So, the final SQL query is as follows:
最后,我们使用UNION运算符将三个结果集合并。因此,最终的SQL查询如下:
SELECT
选择
id, 'Root' AS Type
id, 'Root' AS Type
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NULL
parent_id IS NULL
UNION
UNION
SELECT
选择
id, 'Leaf' AS Type
id, 'Leaf' AS Type
FROM
从
tree
tree(树)
WHERE
其中
id NOT IN (SELECT DISTINCT
id NOT IN (SELECT DISTINCT
parent_id
parent_id(父节点ID)
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NOT NULL)
parent_id 不为空)
AND parent_id IS NOT NULL
且 parent_id 不为空
UNION
UNION
SELECT
选择
id, 'Inner' AS Type
id, 'Inner' AS Type
FROM
从
tree
tree(树)
WHERE
其中
id IN (SELECT DISTINCT
id IN (SELECT DISTINCT
parent_id
parent_id(父节点ID)
FROM
从
tree
tree(树)
WHERE
其中
parent_id IS NOT NULL)
parent_id 不为空)
AND parent_id IS NOT NULL
且 parent_id 不为空
ORDER BY id;
按 id 排序;
Approach 2:
方法 2:
In this approach, we use the control statement CASE. This simplifies our query a lot from the previous approach. We first check if a node falls into the category of “Root”. If the node does not satisfy the conditions of a root node, it implies that the node will either be a “Leaf” node or an “Inner” node. Next, we check if the node falls into the category of “Inner” node. If it is not an “Inner” node, there is only one option left, which is the “Leaf” node.
在这种方法中,我们使用控制语句 CASE。与之前的方法相比,这大大简化了我们的查询。我们首先检查节点是否属于“Root”(根节点)类别。如果节点不满足根节点的条件,则意味着该节点将是“Leaf”(叶子节点)或“Inner”(内部节点)。接下来,我们检查节点是否属于“Inner”(内部节点)类别。如果它不是“Inner”(内部节点),则只剩下一个选项,即“Leaf”(叶子节点)。
The SQL query for this approach can be written as follows:
这种方法的SQL查询可以编写如下:
SELECT
选择
id ASId,
选择 id 作为Id,
CASE
CASE
WHEN tree.id = (SELECT aliastree.id FROM tree aliastree WHERE aliastree.parent_id IS NULL)
当 tree.id = (从 tree aliastree 中选择 aliastree.id 其中 aliastree.parent_id 为空)
THEN 'Root'
则返回 'Root'
WHEN tree.id IN (SELECT aliastree.parent_id FROM tree aliastree)
当 tree.id 在 (从 tree aliastree 中选择 aliastree.parent_id)
THEN 'Inner'
则返回 'Inner'
ELSE 'Leaf'
否则返回 'Leaf'
END AS Type
END AS 类型
FROM
从
tree
tree(树)
ORDER BYId;
按Id排序;
Approach 3:
方法 3:
In this approach, we follow a similar logic as discussed in the previous approach. However, we will use the IF operator instead of the CASE operator. The SQL query for this approach can be written as follows:
在这种方法中,我们遵循与前一种方法讨论的类似逻辑。然而,我们将使用 IF 运算符而不是 CASE 运算符。此方法的 SQL 查询可以编写如下:
SELECT
选择
aliastree.id,
别名的id,
IF(ISNULL(aliastree.parent_id),
IF(ISNULL(别名.parent_id),
'Root',
'根',
IF(aliastree.id IN (SELECT parent_id FROM tree), 'Inner','Leaf')) Type
IF(别名.id IN (SELECT parent_id FROM tree), '内部','叶子')) 类型
FROM
从
tree aliastree
树 别名
ORDER BY aliastree.id
按别名.id 排序
评论