Questions tagged [sql]

Structured Query Language (SQL) is a language for querying databases. Questions should include code examples, table structure, sample data, and a tag for the DBMS implementation (e.g. MySQL, PostgreSQL, Oracle, MS SQL Server, IBM DB2, etc.) being used. If your question relates solely to a specific DBMS (uses specific extensions/features), use that DBMS's tag instead. Answers to questions tagged with SQL should use ISO/IEC standard SQL.

How to write a good SQL question?

There are five ingredients to this recipe:

  1. Provide a clear textual explanation of the problem at hand.
  2. Provide proper sample data, as DDL (create table statement(s)) and DML (insert statement(s)). The sample data should be enough to demonstrate the problem, including edge cases. Usually, a few relevant rows are enough.
  3. Provide the expected output for the sample data you've posted.
  4. Show your attempts to solve the problem.
  5. Tag properly. In addition to , also provide the relevant rdbms tag (i.e. , , ), and the lowest version you need the solution for (i.e , ).
    Remember - different products use different dialects of SQL, and this can have a drastic effect on the answers you might get.
    Different versions of the same product have different built-in functions and capabilities that might also have a drastic effect on the answers.

Do not include images of data or code!

A link to an online SQL test environment such as SQL Fiddle, Rextester, or db<>fiddle might help, but it is not a replacement for having all the data inside the question.
For more information, Read Why should I provide an MCVE for what seems to me to be a very simple SQL query? and Help me write this query in SQL.

General Information

From Wikipedia:

SQL stands for Structured Query Language (informally) and is usually pronounced as Sequel.

SQL is based on relational algebra. In relational algebra, the word relation is synonymous with the word table. SQL is a standard to use relational algebra in a technical environment.

One subset of the SQL standard is DDL (Data Definition Language), used to create tables and constraints. These include:

  • CREATE
  • DROP
  • ALTER

Another subset is DML (Data Manipulation Language), which is used to modify and view data within the database:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE

The final "standard" subset of commands is DCL (Data Control Language):

  • GRANT
  • REVOKE

Many database implementations require the use of SQL, and over the years, vendors have implemented dialects of SQL to provide more functionality and simplify it. Because of these deviations from the standard, SQL is fractured – syntax that works on one implementation does not necessarily work on another.

ISO/IEC (formerly ANSI) standards have been beneficial in resolving such situations, but adoption is selective. Queries conforming to these standards should be portable to other databases, though performance may vary.

Most DBMSs have additional languages for writing stored procedures. In Oracle, it is PL/SQL (Procedural Language/Structured Query Language). In PostgreSQL, it's PL/pgSQL (Procedural Language/PostgreSQL). Outside of stored procedures or functions, Oracle and PostgreSQL use SQL. Thus the tags and should only be used for problems directly related to writing stored procedures. Microsoft SQL Server uses the term T-SQL (Transact-SQL)() for both "plain" SQL (queries, DML, ..) and the language used for stored procedures.

List of Procedural Extensions

  • ANSI/ISO Standard: SQL/PSM (SQL / Persistent Stored Modules)
  • Interbase/Firebird: PSQL (Procedural SQL)
  • IBM DB2 SQL: PL/SQL (Procedural Language, implements SQL/PSM)
  • IBM Informix: SPL (Stored Procedural Language)
  • IBM Netezza: NZPLSQL (based on Postgres PL/pgSQL)
  • Microsoft/Sybase: T-SQL (Transact-SQL)
  • Mimer SQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MySQL: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • MonetDB: SQL/PSM (SQL / Persistent Stored Module, implements SQL/PSM)
  • NuoDB: SSP (Starkey Stored Procedures)
  • Oracle: PL/SQL (Procedural Language / SQL, based on Ada)
  • PostgreSQL: PL/pgSQL (Procedural Language / PostgreSQL Structured Query Language, implements SQL/PSM)
  • Sybase: Watcom-SQL (SQL Anywhere Watcom-SQL Dialect)
  • Teradata: SPL (Stored Procedural Language)
  • SAP: SAP HANA (SQL Script)

Tagging Recommendation

This tag should be used for general SQL programming language questions, in addition to tags for specific products. For example, questions about Microsoft SQL Server should use the tag, while questions regarding MySQL should use the tag. SQL is the umbrella under which these products exist; tagging them by product (including version, e.g , , ) is the easiest way to know what functionality is available for the task at hand. It is very common for questions to omit this tag because query discussions on MySQL are more often stated as MySQL rather than SQL in general.

Please read this summary about the SQL standard (The 1992 one in this case, broadly implemented) and if you can, refer to the book itself.

More specific tags

When you are asking a question about SQL you can also add more specific tags. Here is the list of available tags:

Implementation specific tags

You can specify your question by adding the implementation you used as a tag.

Other Resources

Free SQL Programming Books

Free SQL/Database Online Courses

SQL/Database Online Tutorial

SQL reserved words overview

Online Testing

While you should always provide complete code examples (e.g., schema, data sample and expected result) in your question or answer, you can also isolate problematic code and reproduce it in an online environment:

  • SQL Fiddle MySQL 5.6, Oracle 11g R2, PostgreSQL 9.6, PostgreSQL 9.3, SQLite (WebSQL), SQLite (SQL.js), SQL Server 2017
  • Rextester: SQL Server, PostgreSQL, MySql, Oracle
  • Stack Exchange Data Explorer Microsoft SQL Server 2016
  • db-fiddle MySQL 5.5, 5.6, 5.7, 8.0 PostgreSQL 9.4, 9.5, 9.6, 10, 11, 12, 13 SQLite 3.26, 3.30
  • db <> fiddle Db2 Developer-C 11.1, Firebird 3.0, MariaDB 10.3, 10.4, 10.5, 10.6, MySQL 5.5, 5.6, 5.7, 8.0, Oracle 11g Release 2, Postgres 9.5, 9.6, 10, 11, 12,13, SQLite 3.27, SQL Server 2014, 2016 and 2017, 2017 (Linux), 2019, 2019 (Linux)
  • Hue demo Hive, Trino, MySQL, Flink SQL, Phoenix SQL, ksqlDB, Dask SQL, SparkSQL
665031 questions
98
votes
12 answers

Can I do a max(count(*)) in SQL?

Here's my code: select yr,count(*) from movie join casting on casting.movieid=movie.id join actor on casting.actorid = actor.id where actor.name = 'John Travolta' group by yr; Here's the question: Which were the busiest years for 'John Travolta'.…
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
98
votes
10 answers

Group by minimum value in one field while selecting distinct rows

Here's what I'm trying to do. Let's say I have this table t: key_id | id | record_date | other_cols 1 | 18 | 2011-04-03 | x 2 | 18 | 2012-05-19 | y 3 | 18 | 2012-08-09 | z 4 | 19 | 2009-06-01 | a 5 | 19 | 2011-04-03 |…
user2765924
  • 983
  • 1
  • 6
  • 4
98
votes
11 answers

Disable all table constraints in Oracle

How can I disable all table constrains in Oracle with a single command? This can be either for a single table, a list of tables, or for all tables.
oneself
  • 38,641
  • 34
  • 96
  • 120
97
votes
5 answers

Rails: How to find_by a field containing a certain string

I have a model named Topic, that has a name as a field. So say I have a term I'm searching for, apple. If I do a Topic.find_by_name("apple") I get a record back with the name apple. That's good -- but how do I change find_by_name so that it can…
varatis
  • 14,494
  • 23
  • 71
  • 114
97
votes
3 answers

How to update selected rows with values from a CSV file in Postgres?

I'm using Postgres and would like to make a big update query that would pick up from a CSV file, lets say I got a table that's got (id, banana, apple). I'd like to run an update that changes the Bananas and not the Apples, each new Banana and their…
user519753
  • 1,527
  • 6
  • 18
  • 22
97
votes
5 answers

Why does Sql Server keep executing after raiserror when xact_abort is on?

I just got surprised by something in TSQL. I thought that if xact_abort was on, calling something like raiserror('Something bad happened', 16, 1); would stop execution of the stored procedure (or any batch). But my ADO.NET error message just…
Eric Z Beard
  • 37,669
  • 27
  • 100
  • 145
97
votes
4 answers

Strip last two characters of a column in MySQL

I have an SQL column where the entries are strings. I need to display those entries after trimming the last two characters, e.g. if the entry is 199902345 it should output 1999023. I tried looking into TRIM but looks like it offers to trim only if…
Lucky Murari
  • 12,672
  • 5
  • 22
  • 43
97
votes
9 answers

use current date as default value for a column

Is there a way to set the default value of a column to DateTime.Now in Sql Server? Example: table Event Id int (auto-increment) not null Description nvarchar(50) not null Date datetime not null The line: Insert into Event(Description)…
dcarneiro
  • 7,060
  • 11
  • 51
  • 74
97
votes
6 answers

How to Select Top 100 rows in Oracle?

My requirement is to get each client's latest order, and then get top 100 records. I wrote one query as below to get latest orders for each client. Internal query works fine. But I don't know how to get first 100 based on the results. SELECT *…
user2321728
  • 1,293
  • 1
  • 12
  • 17
97
votes
1 answer

dbms_lob.getlength() vs. length() to find blob size in oracle

I'm getting the same results from select length(column_name) from table as from select dbms_lob.getlength(column_name) from table However, the answers to this question seem to favor using dbms_lob.getlength(). Is there any benefit to using…
user285498
97
votes
14 answers

What are views good for?

I'm just trying to get a general idea of what views are used for in RDBMSes. That is to say, I know what a view is and how to make one. I also know what I've used them for in the past. But I want to make sure I have a thorough understanding of…
Jason Baker
  • 192,085
  • 135
  • 376
  • 510
97
votes
3 answers

How do I rename an Index in MySQL

I would like to rename an index. I've looked at the alter table documentation, but I can't figure out the syntax to simply rename an index. When doing it through the MySQL GUI, it drops the index, and creates a new one. While this works, I would…
Kibbee
  • 65,369
  • 27
  • 142
  • 182
97
votes
2 answers

exec failed because the name not a valid identifier?

I have a query I need run it as a dynamic query to output a meaningful column name. As an example, if I run the query directly, it returns data correctly. However, if I use below code, it shows: The name ' SELECT (CASE WHEN A.Domain IS…
urlreader
  • 6,319
  • 7
  • 57
  • 91
97
votes
12 answers

Export table data from one SQL Server to another

I have two SQL Servers (both 2005 version). I want to migrate several tables from one to another. I have tried: On source server I have right clicked on the database, selected Tasks/Generate scripts. The problem is that under Table/View options…
no9
  • 6,424
  • 25
  • 76
  • 115
97
votes
11 answers

SQL Server - copy stored procedures from one db to another

I am new to SQL, and what I needed to do was to combine 2 .mdf databases into one. I did that using SQL Server 2008 Manager - Tasks > Import/Export tables.The tables and views were copied successfully, but there are no Stored procedures in the new…
Oak
  • 1,159
  • 3
  • 13
  • 21