Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a user defined function and I want to do a select and choose a column based on whether or not it is bigger or small than another.
For example:
```
Select
t.A, t.B
From
Table t
Where
if(t.A <= t.B) then
use t.A
else
use t.B
```
Is this possible? Thanks in advance! | It seems like you want
```
SELECT
CASE
WHEN t.A <= t.B
THEN t.A
ELSE t.B
END AS Smaller
FROM Table t
``` | No! But you can use a `case` statement
```
Select
t.A, t.B
From
Table t
Where
(case when t.A <= t.B then t.A ELSE t.B END) = SomeValue
```
or if the smaller column is required in the select statement only then
```
Select
(case when t.A <= t.B then t.A ELSE t.B END) as column
From
Table t
```
**NOTE**... | Using an IF statement in a WHERE clause | [
"",
"sql",
"pervasive-sql",
""
] |
I need to create a column in SQL Server database. Entries for that column will contain messages from chat. Previously such messages has been stored as comments.
My main quetion is:
What is typical text length for **chat message** and **comment**?
By the way:
What would happen if I used *varchar(max)*? How would it im... | Using VARCHAR(MAX) has a disadvantage: you can not define an index over this column.
Generally, your application should impose a maximum length for a chat message. How big that limit is depends very much on what the application is used for. But anything more than 1000 byte is probably less a legitimate message but an ... | Short answer - it doesn't matter.
From [MSDN](http://technet.microsoft.com/en-us/library/ms176089.aspx):
> The storage size is the actual length of the data entered + 2 bytes.
So VARCHAR(10) and VARCHAR(10000) will consume the same amount of data if the values don't exceed 10 characters. | What are typical lengths of chat message and comment in database? | [
"",
"sql",
"sql-server",
"database",
""
] |
I cant realize whats wrong with my query (Firebird SQL):
```
select max(column1) from (select first 100 column1 from table1 where column1 > 0) p
```
Error message:
```
SQL Message : -104
Invalid token
Message: isc_dsql_prepare failed
SQL Message : -104
Invalid token
Engine Code : 335544569
Engine Message :
Dynami... | SQL does not have `FIRST` keyword it uses `TOP` keyword. Full explanation here
<http://technet.microsoft.com/en-us/library/ms189463.aspx>
Firebird:
"In MS SQL 7 and above, the SELECT clause can take a TOP specifier to limit the number of rows returned. This feature is currently under development for the Firebird eng... | Nested SELECT queries ("SELECT from SELECT") use derived tables, which are only supported in [Firebird 2.0 and above](http://www.firebirdsql.org/refdocs/langrefupd20-select.html#langrefupd20-derived-tables).
However, since Firebird 1.5 allows SELECT statements to appear in the WHERE clause, your query can be rewritten... | Firebird SQL Nested Select | [
"",
"sql",
"select",
"nested",
"firebird",
""
] |
I have a table that records shifts worked by employees. It's pretty simple, consisting of (reduced for simplicity): an auto-increment `primary key`, `employee_id`, `job_id`, `date`
A row is created for each shift worked, so if a particular employee doesn't work on a particular day, there will be no row for that employ... | If you had a sequence of numbers, then the difference between those numbers and a sequence of dates will be constant. We can use this fact to group the working days into groups with a minimum and maximum date:
```
select employee_id, min(date) as mindate, max(date) as maxdate
from (select s.*, date_sub(date, interval ... | Suppose your table name is `shift`, then the following query would provide you with the number of rows between the provided date and current date.
```
SELECT COUNT(`date`) AS working_days
FROM `shift`
WHERE `date` BETWEEN '2014-01-02' AND CURDATE()
``` | MySQL: Count rows with consecutive dates leading up to given date | [
"",
"mysql",
"sql",
""
] |
i'm trying to create a table with columns that reference toward other tables.
How do i make the foreign keys?
Scheme:

Query: (not working):
```
CREATE TABLE gebruikers_trainingen (
gebruiker_id INT UNSIGNED NOT NULL,
training_id INT UNSIGNE... | You should add indexes on your foreign keys:
```
CREATE TABLE gebruikers_trainingen (
gebruiker_id INT UNSIGNED NOT NULL,
training_id INT UNSIGNED NOT NULL,
gebruiker_naam VARCHAR(255) NOT NULL,
training_naam VARCHAR(255) NOT NULL,
INDEX (gebruiker_id, gebruiker_naam),
INDEX (training_id, trai... | Has this table existed before in a different guise?
[Mysql 1005 error when creating table using InnoDB engine](https://stackoverflow.com/questions/4213013/mysql-1005-error-when-creating-table-using-innodb-engine)
Hth Oli | Cannot create interconnecting table | [
"",
"mysql",
"sql",
"foreign-keys",
""
] |
I am trying to execute a large sql script which contains about 1000000 simple `UPDATE`queries.
The total size of this script file is about 100 MB.
When I run this script I'm getting an Out Of Memory exception.
When I split the file into chunks of 10 MB I can run each of them.
However, I for convenience I would like... | If you have not done so already, insert a `GO` every thousand statements or so. Otherwise the whole file will be one large batch. SQL Server calculates a single execution plan for a batch which may be pushing you to resource limits.
You might run into another type of resource problem if you run the whole file in the s... | **UPDATED:**
Open the window command prompt (run+cmd) and run the following:
```
sqlcmd -S YOURSQLSERVER\INSTANCENAME -i c:\your_script_file.sql -o c:\your_log_file.log
``` | Out of memory exception in SQL Server 2012 | [
"",
"sql",
"sql-server",
"sql-update",
"bulk",
""
] |
how to get today date in YYYYMMDD in firebird, I had a look on [following](http://www.firebirdsql.org/en/firebird-date-literals/) but could not figured how to write this. | I think you can do:
```
select replace(cast(cast('Now' as date) as varchar(10)), '-', '')
from rdb$database
``` | **IN FIREBIRD v2.5.5:**
```
SELECT LPAD( EXTRACT( YEAR FROM CURRENT_TIMESTAMP ), 4, '0' ) ||
LPAD( EXTRACT( MONTH FROM CURRENT_TIMESTAMP ), 2, '0' ) ||
LPAD( EXTRACT( DAY FROM CURRENT_TIMESTAMP ), 2, '0' ) || ' ' ||
LPAD( EXTRACT( HOUR FROM CURRENT_TIMESTAMP ), 2, '0' ) ||
LP... | how to get today date in YYYYMMDD in firebird | [
"",
"sql",
"firebird",
"firebird2.5",
""
] |
I am using SQL server management studio, i am trying to update something in my database the return type of that column is bit so its either 0 or 1: this is my sql statment:
```
public void Update(int ID)
{
SqlConnection myConnection = new sqlConnection etc....;
string query = "UPDATE Table SET ColumnName= Col... | Change the line
```
myComm.CommandType = CommandType.StoredProcedure;
```
to
```
myComm.CommandType = CommandType.Text;
```
(or just remove it since `CommandType.Text` is the default)
You are not executing a stored procedure - you are executing direct SQL. | I think you should to remove this line
`myComm.CommandType = CommandType.StoredProcedure;`
You are not calling a procedure.. Hence, you don't need it. | sql Could not find stored procedure ''. with bit as a return type | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I want to left join this query but it does not seem to work
```
select *,(SELECT datediff(t1.expirydate,CURDATE())as daysleft
from tbl1 t1,
left join tbl2 t2 on (t1.mid=t2.mid and t1.pid=t2.pid and t1.uid=3)
```
you have an error in your SQL syntax;
```
right syntax to use near 'left join tbl2 t2 on (t1.mid=t2.... | You don't put a comma between joins.
```
SELECT t1.*, t2.*, datediff(fsp.expirydate, CURDATE()) AS daysleft
FROM tbl1 t1
left join tbl2 t2 on t1.mid = t2.mid and t1.pid = t2.pid
cross join fsp
where t1.uid = 3
```
You also shouldn't put the `t1.uid = 3` condition in the `ON` clause. `ON` should only contain condition... | No comma after "t1" on line 2.
Also I don't think you can do "\*," on line 1, you need to either do "SELECT \*" or "SELECT column, column2" | select query using leftjoin doesnt work | [
"",
"mysql",
"sql",
"left-join",
""
] |
Im creating a database design in MySQL Workbench. I want to have a enumarated table which holds some standard values. The values of the enumaration table needs to be linked to a row in my other table. So i have a table called 'club' which holds a row 'club\_soort'. The row 'club\_soort' needs to relate to the enumarati... | Rather than using enumerations, you should use what's known as a lookup or reference table. This table would contain your enumerations and be referenced as a foreign key by the parent table.
As an example, this would look like:
```
parent_table
------------ club
id ----
club_so... | ENUM values cannot be linked to any MySQL structures. It can contain only static data. | Using enumerations in mySQL Workbench | [
"",
"mysql",
"sql",
"workbench",
""
] |
I need to generate a report every day for exception which have occurred today.
I have a column "Exception Details" where I store the details of the exception along with the date on which it occurred.
I have another table where i store my current date which changes everyday.
I need to compare these two dates and if t... | I have found the solution to it using ReGEX:
SELECT \* FROM EXCEPTION WHERE EXP\_STAT = 'OPEN' AND REGEXP\_SUBSTR(EXCEPTION\_DETAILS,
'(19|20)\d\d- -.- -.') = (select to\_char(date, 'YYYY-MM-DD') from calendar\_table where date\_type='CURRENT') | ```
SELECT tableA.* FROM tableA, tableB
WHERE tableA.EXP_STAT = 'OPEN'
AND SUBSTR(EXCEPTION_DETAILS ,INSTR(EXCEPTION_DETAILS,to_char(tableB.current_date,'YYYY-MM-DD')),12) = to_char(tableB.current_date,'YYYY-MM-DD');
```
Assuming your date table , don't have repetitive dates. | How do I compare a date from one table with the date present in another table? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I was trying to create a function which returns to an integer. However, I got the warning as
```
"Msg 2715, Level 16, State 3, Procedure median, Line 1
Column, parameter, or variable #0: Cannot find data type Median."
```
Here is the query. Thanks in advance.
```
CREATE FUNCTION dbo.median (@score int)
RETURNS Medi... | Just change the return type to integer:
```
CREATE FUNCTION dbo.median (@score int)
RETURNS integer
AS
BEGIN
DECLARE @MedianScore as integer;
```
Unless you're intentionally using the `Median` type for something that you haven't stated. | Since you are calculating Median of some values I would suggest you return a Numeric value instead of Integer as MAX(@score) + MIN(@score)/ 2 can return a decimal number value. so trying to save that value in an INT variable will truncate the Decimal part. which can lead to wrong results.
In the following example I ha... | Create function return integer SQL Server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"function",
""
] |
I am creating a application which is mainly used inside a office for data maintenance. It will be used to store data like work list, future works, reminders etc .All data will be presented to user in the form of grids. So it's all about data stored in SQL server database. There will be number of users accessing it and ... | Some pointers:
**WinForms**
Good
* No webserver to install, setup and secure
Bad
* Installation of some kind required on each machine e.g .NET framwork, exe, assemblies, etc.
* More difficult to rollout updates to the application
**ASP.NET**
Good
* No installation on clients required
* Can run on machines other... | Unless you want to use jQuery and Javascript to add additional functionality to the Standard ASP.NET GridView I would say a Windows Form would be more suited, depending on the size of the data it will most likely offer better performance and you have much more control over the actual functionality of the program, rathe... | Windows Forms vs ASP.NET to create a Data Maintenance program | [
"",
"asp.net",
"sql",
"vb.net",
"winforms",
"datagridview",
""
] |
I'm working with PostgreSQL.
I have table with some elements. In last column there is 'Y' or 'N' letter. I need command which Select only first that match (I mean where last column is 'N') and change it on 'Y'.
My idea:
```
UPDATE Table SET Checked='Y'
WHERE (SELECT Checked FROM Table WHERE Checked='N' ORDER BY ID L... | Here is query
```
UPDATE Table SET Checked='Y'
WHERE ID =(SELECT ID FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1)
``` | ## Why it didn't work
Others have answered the *how*, but you really need to understand *why* this was wrong:
```
UPDATE Table SET Checked='Y' WHERE (
SELECT Checked FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1
) = 'N'
```
SQL evaluates step by step in a well-defined order. In this case, the subquery evaluates... | SQL How to Update only first Row | [
"",
"sql",
"postgresql",
""
] |
I have data that has come over from a hierarchical database, and it often has columns that contain data that SHOULD be in another table, if the original database had been relational.
The column's data is formatted in pairs, with `LABEL\VALUE` with a space as the delimiter, like this:
> LABEL1\VALUE LABEL2\VALUE LABEL... | Assuming that the data label contains no `.` characters, you can use a simple function for this:
```
CREATE FUNCTION [dbo].[SplitGriswold]
(
@List NVARCHAR(MAX),
@Delim1 NCHAR(1),
@Delim2 NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
SELECT
Val1 = PARSENAME(Value,2),
Val2 = PARSENAME(Value,1)
... | Using the [SQL split string function](http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx) given at referenced SQL tutorial, you can split the label-value pairs as following
```
SELECT
id, max(label) as label, max(value) as value
FROM (
SELECT
s.id,
label = case when t.... | split string in column | [
"",
"sql",
"sql-server",
"t-sql",
"parsing",
"split",
""
] |
How can i restrict field in a table to 15 or 16 digits. I have this table:
```
create table Person(
,UserID varchar(30)
,Password varchar(30) not null
,CCtype varchar(8)
,CCNumber numeric
,primary key(UserID)
,constraint CK_CCvalidity check
(
(CCType is null or CCNumber... | `CCNumber` should never be numeric. That will lead to a world of pain.
It should be `varchar(X)` where X is 13 - 24 digits.
Credit card numbers are usually represented by groups of 4 or 5
digits separated by spaces or dashes or simply all together with no separators.
[note: American Express: 15 digits; Visa: 13 or 1... | You can create a function to remove the Non-Numeric characters from a varchar, like [this one](https://stackoverflow.com/a/6529463/122195):
```
CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
SET @strTe... | Digit restriction on SQL server numeric field | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am using `MySQL 5.2.42 CE`.
I have a table which has a column named `"organization_id"`. It contains some repeated values for different rows, means more than one row can have `"org1"` value in that field.
Now I have to loop through the distinct values of that column, means different organizations.
But I don't know ... | You have to use [`CURSORS`](http://dev.mysql.com/doc/refman/5.6/en/cursors.html).
Using a cursor, read the fetched ids into local variable and perform other conditional operations based on that organisation id.
```
...
DECLARE cur_orgs CURSOR FOR
SELECT DISTINCT organization_id FROM tbl_organization;
...
... | If I am understanding right then
you can use **CURSOR** in your trigger.
ursor is used to iterate through a set of rows, which returned by a query, and process individual row. Currently with all versions greater 5.x, MySQL cursor has following properties:
* Read only: it means you cannot update the cursor.
* Non-scr... | Looping on a Select query result set element and get the elements in MySQL | [
"",
"mysql",
"sql",
""
] |
I have a table like this:
```
Table company
companyid | companyname | owner |
5 |coffecompany |Mike |
6 |juicecompany |Mike |
```
For some reason, I need to use this:
```
DELETE FROM company WHERE companyid='5';
DELETE FROM company WHERE companyid='6';
```
instead of
```
DELETE FROM company WHE... | `delete from company where companyId in (5, 6);` should always be faster, even though the difference might be negligible if eg. you've got proper indexes, no concurrent queries, no issues with locking etc.
Note that my query is for MS SQL, if your database server allows using the same construct (ie. specifying all the... | Generally, SQL is language operating on sets of data so second query will be much faster for huge amount of rows.
First choice might be slower as you'll have to send query text as many times as you have rows to delete. Imagine network traffic if you want to delete 1 000 000 rows.
On small amounts of rows probably you... | Will one query run faster than multiple queries, if they are deleting the same amount of records | [
"",
"sql",
""
] |
Lets say today's date is Jan 22, 2014
and i run a report having this table below (Table) but input range of SIdate
from Jan 01, 2014 to Jan 18, 2014 only.
I want to display all rows based on the SIdate i entered which is jan 01,2014 to Jan 18, 2014 but CMdate should be considered also and should pass the date paramete... | You'll need to repeat the filter on both columns, optionally allowing for a NULL `CMDate`
```
SELECT
Emp, SIDate, item, TotQty, TotAmt, CMDate, CMAmt
FROM
Table1
WHERE
SIDate BETWEEN '2014-01-01' AND '2014-01-18'
AND (CMDate IS NULL OR CMDate BETWEEN '2014-01-01' AND '2014-01-18');
```
[Fiddle here]... | ```
select * from table where (cmdate between '01-01-2014' and '18-01-2014' or cmdate is null) and sidate between '01-01-2014' and '18-01-2014'
``` | How to create a sql script to consider two columns? | [
"",
"mysql",
"sql",
"date",
"select",
"where-clause",
""
] |
Two Windows 7 computers connected through network (workgroup) and can ping each other. I have my database on one of them and need the other computer to connect to this database through my window application.
Here's what I have :
* both pcs are Windows 7 (ultimate & professional).
* I enabled TCP/IP under SQL Configur... | It turned out to be a Firewall problem. I disabled Firewall and it worked. Even though I have the port opened as a rule, but there is something else in my Firewall which seem to be blocking the connection.
I ended up disabling Windows Firewall and installing another one. | If you are on a work group with a PC named SERVER and another PC named CLIENT, you have to choose what security you are going to use. STANDARD vs NT AUTHENTICATION.
First, did you check to see if the server is active on the default port?
Did you try the following commands on the server from a command shell.
```
cd c... | Cannot connect to SQL Server 2008 on workgroup network | [
"",
"sql",
"sql-server",
"sql-server-2008",
"networking",
"windows-7",
""
] |
I have a problem to getting the last month in a query :
This is my query:
```
SELECT
i_chelt_pub_val.`agent_id`,
i_chelt_pub_val.`date`,
i_chelt_pub_val.`form_val`
FROM
i_chelt_pub_val
WHERE (
MONTH(i_chelt_pub_val.`date`) = (MONTH(CURRENT_TIMESTAMP) - 1)
)
AND i_chelt_pub_val.`agent_id` = '253'
``... | try DATE\_SUB():
```
... = MONTH(DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH));
``` | Assuming, that you want all data from the beginning of the last month to the end of the last month, your query has three issues:
* you will get for example all januaries of all years
* depending on when you execute the query, you will miss the data from the very beginning of a month to the time when you execute it, fo... | How do I get the last month using a query? | [
"",
"mysql",
"sql",
""
] |
this is my original table.
```
+----------+---------------------+--------+------------+-------+
| lab_code | test_name | sample | time_taken | price |
+----------+---------------------+--------+------------+-------+
| FBS | Fasting blood Suagr | Blood | 01:15:00 | 400 |
| STLC | Stool Culture ... | Give `ALIAS` name to specific column
```
SELECT lab_code AS Hospital
From tableA
``` | What about
```
SELECT lab_code AS Hospital FROM <table_name>;
```
The use of AS is an **ALIAS** that can be used for the column name; it does not mean that the table's column name changes, but rather, when the SELECT query is executed, that becomes the column name or alias for the current column name present in the t... | change attribute name in Mysql | [
"",
"mysql",
"sql",
"select",
"alias",
""
] |
I have a MS SQL table with over 250 million rows. Whenever I execute the following query
`SELECT COUNT(*) FROM table_name`
it takes over 30 seconds to get me the output. Why is it taking so much time? Does this do a count when I query? I'm assuming till date that it stores this information somewhere (probably in the ... | Every time you execute `SELECT COUNT(*) from TABLE` SQL server actually goes through the table and counts all rows. To get estemated row count on one or more tables you can run the following query which gets stored information and returns in under 1 sec.
```
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM s... | No, sql server dosen't store this information. It computes it every query. But it can cache execution plan to emprove perfomace. So, if you want to get results quickly, you need a primary key at least. | What makes count(*) query to run for 30 sec? | [
"",
"sql",
"sql-server",
""
] |
***UPDATED***
I have added a example of the dataset so its easier to explain my problem. It looks to me if it is a lookup question.
I have a basetable with all months from 2013-01 to 2014-12. I have a lookuptable with contract working hours per person (column id; e.g. person 1 and person 2).
I have to match the base... | **This is the answer:**
```
Select A.ID
, A.Date
, ( Select Top 1
B.Hours
From _Lookup B
Where A.Date >= B.Date
and A.Id = B.ID
Order by B.Date desc
) as WorkingHours
From [_Basetable] A
```
Thanks for helping me out!! | Does this work for you?
```
WITH MyTimeDate ([Year], [Month], Hours_Work) AS
(
SELECT 2013, 1, 8 UNION ALL
SELECT 2013, 2, 16 UNION ALL
SELECT 2013, 4, 8 UNION ALL
SELECT 2013, 5, 32 UNION ALL
SELECT 2013, 9, 12 UNION ALL
SELECT 2013, 10, 20 UNION ALL
SELECT 2... | SQL join of 2 date tables with gaps (Lookup) | [
"",
"sql",
"join",
""
] |
I have about 11 columns in a mysql table and none of them are empty. When I view these columns in the Browse section, some columns are hidden whereas I'm sure they exist.
I have updated phpMyAdmin to latest version (4.1.5) but that did not solve anything. I also exported the table, dropped it and imported it again but... | You could look in the exported file to double-check that they exist there.
Another thing to try; from the table, click the SQL tab. The default text will probably say `` SELECT * FROM `tablename` WHERE 1 ``, try running that and see if you get any different response.
If you click the Structure tab, do you see the col... | This question is a duplicate to this one:
[phpMyAdmin doesn't show added columns](https://stackoverflow.com/questions/12960302)
so here is my duplicate answer! I don't think I have enough kudos to flag this as duplicate yet.
Database phpmyadmin is used to store which columns are hidden, which column a table should be ... | Some columns are hidden in phpMyAdmin | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
I'm trying to create a query to return the file with the max version, independent of the value of the server. How could I do that?
actual table data:
```
server filename v4 date
local code1.zip 41 0000-00-00
remote code1.zip 39 0000-00-00
local code1.zip 28 0000-00-00
remote code... | If you just want the row with largest v4 you can use this
```
SELECT
server,
filename,
v4,
date
FROM
`table`
WHERE
date ='0000-00-00'
ORDER BY v4 DESC
LIMIT 1
```
to get max V4 for each filename, first you get max(v4) group by filename then INNER JOIN back with `table` like below
```
SELECT T... | To get the the max version you only have to do:
```
SELECT MAX(version) FROM table
```
If you also want the filename (if you have another column `id`):
```
SELECT t2.filename, t2.maxver
FROM table t1 INNER JOIN
(SELECT id, MAX(version) maxver
FROM table
GROUP BY id) t2 ON t1.id=t2.id
ORDER BY t2.maxver DESC
LIMIT ... | Returning max from query | [
"",
"mysql",
"sql",
"select",
"aggregate-functions",
""
] |
This is just an SSCCE:
```
CREATE TABLE test(i INTEGER NOT NULL);
WITH max_i AS (SELECT MAX(i) FROM test)
SELECT * FROM test WHERE max_i - i < 2 AND max_i!=i
```
PostgreSQL complains:
```
ERROR: column "max_i" does not exist
```
I guess that's because `max_i` is a single value and not a rowset, but how do I get to... | You don't reference the CTE at all in your "final" select statement. Therefor you can't reference it. Additionally the `where` condition needs to reference *columns* not tables.
In your statement `max_i` is the name of a "table", thus it cannot be used in a where condition.
```
WITH t_max AS (
SELECT MAX(i) as max... | First, you don't need both these conditions in the `WHERE` clause. The `i = max_id - 1` would be enough (if it worked.)
To use the value from the CTE, you either have to use a (cross) join as the other answers or use this (less common) syntax:
```
WITH max_i AS
( SELECT MAX(i) FROM test )
SELECT *
FROM test
WHERE i... | why can't I use WITH (Common Table Expressions) in this query? | [
"",
"sql",
"postgresql",
"common-table-expression",
""
] |
I want to retrieve all the files from a cabinet (called 'Wombat Insurance Co'). Currently I am using this DQL query:
```
select r_object_id, object_name from dm_document(all)
where folder('/Wombat Insurance Co', descend);
```
This is ok except it only returns a maximum of 100 results. If there are 5000 files in the ... | Aha, I've figured it out. Using DFS with Java (an abstraction layer on top of DFC) you can set the starting index for query results:
```
String queryStr = "select r_object_id, object_name from dm_document(all)
where folder('/Wombat Insurance Co', descend);"
PassthroughQuery query = new Passthrough... | Well, the hint *is* being used incorrectly. Start with 1, not 0.
**There is no built-in limit** in DQL itself. All results are returned by default. The reason you get only 100 results must have something to do with the way you're using DFC (or whichever other client you are using). Using *IDfCollection* in the followi... | DQL query to return all files in a Cabinet in Documentum? | [
"",
"sql",
"database",
"dql",
"documentum",
"dfc",
""
] |
My table:
```
user | score | category
-----------------------
1 | 20 | 1
2 | 30 | 1
4 | 30 | 1
1 | 20 | 2
2 | 30 | 2
4 | 30 | 3
```
Expected result:
```
user | score | category | rank
------------------------------
1 | 20 | 1 | 3
2 | 30 | ... | You can consider an alternative (which you may find to be faster) to a correlated subquery approach which involves using session variables
```
SET @n := 0, @r := 0, @c := NULL, @s := NULL;
UPDATE users u JOIN
(
SELECT user, score, category,
@n := IF(@c = category, @n + 1, 1) rnum,
@r := IF(@c = cat... | Here is the query to get the rank:
```
select t.*,
(select count(*) + 1
from MyTable2 t2
where t2.category = t.category and
t2.score > t.score
) as rank
from MyTable t;
```
You can put this into an update, by joining again back to the original table, assuming the `user, cate... | How to add "rank" column to mysql table depending on the score with different categories? | [
"",
"mysql",
"sql",
"database",
""
] |
I wrote and managed this query to calculate total time a person has worked per day by dateDiff function now i am stuck at one place. i want to calculate that if a person has done over time than a new column should show OVERITME in hh:mm.
I n our office total working hours are 08:00 hours, greater than 8 hours are cons... | Try this instead:
```
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS InTime
, max(t2.RecTime) AS [TimeOut]
, cast(min(t1.RecTime) as datetime) AS InTimeSub
, cast(max(t2.RecTime) as datetime) AS TimeOutSub
, t1.RecDate AS [DateVisited]
FROM AtdRe... | ```
--You can create a separate function to calculate work-hrs and overtime
-- Try this
CREATE FUNCTION GetWorkHours (
@INTime AS DATETIME
,@OutTime AS DATETIME
,@WorkingHrsINMinutes AS INT
)
RETURNS @WorkHours TABLE (
WorkHours VARCHAR(5)
,OTHours VARCHAR(5)
)
AS
BEGIN
INSERT INTO @WorkHours
SELECT CAST((D... | new column to calculate overtime | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I need to write Simple.data queries for following SQL queries can you help me ?
```
SELECT
Table1.UserID,
Table1.we, Table1.ba, Table1.re,
Table1.rtes, Table1.datae, Table1.void,
Table1.deletee
FROM
Table1
INNER JOIN
Table1 ON UserID.UserID = Table2.UserID
WHERE
Table2.clinicId = 11
```
... | ```
db.Table2.FindAllByClinicId(11)
.Select(
db.Table2.Table1.UserId,
db.Table2.Table1.we,
db.Table2.Table1.ba,
db.Table2.Table2.re,
db.Table2.Table1.rtes,
db.Table2.Table1.datae,
db.Table2.Table1.void,
db.Table2.Table1.deletee);
```
That should end up sending this to the database:
`... | you are joining with same table. so you need to join two different tables or join same table giving alias.
```
SELECT Table1.UserID, Table1.we, Table1.ba, Table1.re, Table1.rtes, Table1.datae,
Table1.void, Table1.deletee FROM Table1 INNER JOIN Table2 ON
UserID.UserID = Table2.UserID
where Table2.clinicId=11
```
OR
... | How to write Simple.Data query to join two tables? | [
"",
"sql",
"database",
"simple.data",
""
] |
I'm having a difficult time figuring out why my mysql query is returning the same row five times. Here is the query below. I read on here something about joins and cartisian products. I'm very new to this, and editing this query on my site that someone else initially created. Trying to understand the joins that are use... | It doesn't look like tbloffers\_cat is used in the query, and may contain rows that aren't visible in your result set. To verify this, add `tbloffers_cat.*` to your query and see if the values in those fields differ from row to row.
If that's the case, try this:
```
SELECT off.*
, resp.tracking_date
, resp.pa... | While your query should be working as intended, it's using deprecated syntax, I suggest replacing the deprecated implicit joins with standard explicit joins:
```
SELECT off. * , resp.tracking_date, resp.paid_date, resp.total_value, resp.total_conversion
FROM tbl_offers AS off
JOIN tbl_tracking AS tr
ON off.id = tr.of... | mysql query returning the same row multiple times | [
"",
"mysql",
"sql",
""
] |
I'm building a program that stores news headlines for companies and its timestamp from various sources.
Let's say the number of company is 1000. It goes like Apple, Google, Microsoft.. etc.
So I can think about two options.
1. One table with numerous rows (above code is just an example).
```
CREATE TABLE news... | Relational databases are designed to store many rows per table. There are a whole bunch of mechanisms to facilitate large tables, such as:
* Indexes on any combination of fields to speed searches
* Page caching so commonly used pages remain in memory
* Vertical partitioning (columnar databases) to further speed reques... | My experience with Many tables, currently working for a company that has 6000+ tables and growing, is the difficulty in managing the many tables. The upside is you reduce the amount of rows in a table ( I have 30 million rows on other companies) which is great - but only if you have a manageable solution for all your t... | Many tables or rows, which one is more efficient in SQL? | [
"",
"mysql",
"sql",
"database",
"schema",
"relation",
""
] |
I am trying to execute a query in Oracle database. The query has case construction in where clause.
```
where
sale.op = 2 and
case when (:stat = -11) then (sale.type_id = 27 or sale.type_id = 28 or sale.type_id = 29)
else
(sale.type_id = 27)
end
```
But I am getting the following error:
> ORA... | ```
where sale.op = 2
and ( (:stat = -11 and sale.type_id in (27, 28, 29))
or (:stat <> -11 and sale.type_id = 27)
)
``` | try this query:
```
where
sale.op = 2 and
((:stat = -11 and (sale.type_id = 27 or sale.type_id = 28 or sale.type_id = 29))
or (:stat <> -11 and sale.type_id = 27))
``` | Oracle - Case in where clause | [
"",
"sql",
"oracle",
"case",
"where-clause",
""
] |
I have a revision database table with multiple revisions for pages(pageId) under a website(webId).I want to write a query to get only the latest revisions of a website.For example the table below shows two files with id 1 and 2,now i want to get the revision number 101 and 104 as they are latest for their respective pa... | To obtain the complete row do:
```
SELECT * FROM revision WHERE Id IN (
SELECT MAX(id) FROM revision GROUP BY pageId ORDER BY dateUpdated DESC
)
``` | try this
```
SELECT max(id) id FROM revision
GROUP BY pageId
```
[**DEMO HERE**](http://sqlfiddle.com/#!2/73aff/6)
output:
```
ID
104
101
```
EDIT: if you need to filrter or order the output then just add `ORDER BY dateUpdated DESC` | Getting latest entries from the revision table in mysql | [
"",
"mysql",
"sql",
"database",
""
] |
How can I pull only the number from a field and put that value into its own field?
For example, if a field1 contains a value of "Name(1234U)".
I need an SQL or VBA way to scan that field and pull the number out. So field2 will equal "1234".
Any ideas? | It is possible that this or a variation may suit:
```
SELECT t.Field1, Mid([Field1],InStr([field1],"(")+1,4) AS Stripped
FROM TheTable As t
```
For example:
```
UPDATE TheTable AS t SET [field2] = Mid([Field1],InStr([field1],"(")+1,4);
```
EDIT re comment
If the field ends `u)`, that is, alpha bracket, you can ... | The following VBA function might do the trick:
```
Option Compare Database
Option Explicit
Public Function RegexReplaceAll( _
OriginalText As Variant, _
Pattern As String, _
ReplaceWith As String) As Variant
Dim rtn As Variant
Dim objRegExp As Object ' RegExp
rtn = Null
If No... | How to select only numbers from a text field | [
"",
"sql",
"ms-access",
"ms-access-2007",
"vba",
""
] |
I've got a small problem with an SQL cursor.
I'm trying to execute an SQL command on android. I'm trying to sort the returned content by cases, but it seems like the system doesn't accept the returned values (?!)
I've tried everything! Do you have the solution ? ;)
```
cursor = db.rawQuery(c, null);
String c = "SELECT... | When you are SELECTing records from a single table, you can use anything from those records for sorting.
However, when you are combining multiple queries with UNION, the sorting is done on the entire result, so you must use some column from the result for ordering.
In this case, this means that you must move the calcu... | See [this post](https://stackoverflow.com/questions/4715820/how-to-order-by-with-union) and try specifying all columns in your select statements. | SQL request with case in order by throws "(1) 1st ORDER BY term does not match any column in the result set" | [
"",
"android",
"sql",
"sqlite",
""
] |
I have a query that SELECTs from multiple databases where column 'auth' = mad:
```
$result = mysql_query("SELECT * FROM test.1 WHERE auth = 'mad' LIMIT 1
UNION SELECT * FROM test.2 WHERE auth = 'mad' LIMIT 1
UNION SELECT * FROM test.3 WHERE auth = 'mad' LIMIT 1");
```
How do I mark or categorize the result,... | Add the table name to results:
```
$result = mysql_query("SELECT *, 'test.1' FROM test.1 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test.2' FROM test.2 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test.3' FROM test.3 WHERE auth = 'mad' LIMIT 1");
``` | ```
$result = mysql_query("SELECT *, 'test1' as Source FROM test.1 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test2' FROM test.2 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test3' FROM test.3 WHERE auth = 'mad' LIMIT 1");
``` | "Categorize" or "Mark" SELECT query | [
"",
"mysql",
"sql",
"select",
""
] |
I try to join two tables. One is table filled with totally unique variables `debtor`. No duplicates of the debtor id can exist.
Now I wish to join it with the `items` table where the `debtor.debtor` id can appear multiple times.
What I wish to do is to only join if the item `'20004'` does not exist in the order histor... | Try this:
```
SELECT * FROM debtor d
JOIN items i on d.debtor = i.debtor
WHERE NOT EXISTS
(SELECT debtor
FROM items i2
WHERE item = '20004' AND i2.debtor = i.debtor
)
```
Update fiddle: <http://sqlfiddle.com/#!2/a0826/12/0> | Or this:
```
select * from debtor d
join items i on d.debtor = i.debtor
where d.debtor not in (select debtor from items where item = '20004');
``` | Only join tables if certain value does not exist among multiple rows in other table | [
"",
"sql",
"sql-server",
"join",
""
] |
I am making a small project in which I am using mysql for my database, in which i need to input phone numbers with std codes.
The problem is in inserting proper std codes.
Suppose the std code is `0123` but while running the query it is only inserting `123`.
If it is 0275, it is only inserting 275.
but if it is `2210... | Try with this.It should work `varchar(5)` | I usually store phone numbers as a BIGINT in E164 format.
E164 never start with a 0, with the first few digits being the country code.
```
+441234567890
+44 (0)1234 567890
01234 567890
```
etc. would be stored as `441234567890`.
> But my suggestion is you can use a **varchar** for a telephone number.
> You do not n... | How do I insert proper std code in mysql | [
"",
"mysql",
"sql",
""
] |
My colleague has this in a procedure:
```
BEGIN TRAN
--Some deletes and inserts
IF(@@error <> 0)
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
```
I have another in a stored procedure that simply is:
```
BEGIN TRANSACTION
--Some deltes and inserts
COMMIT TRANSACTION
```
I have tested and found that my procedure... | **YES**, the `ROLLBACK` is necessary!
I would do a stored procedure based on this template for SQL Server 2005 and newer:
```
BEGIN TRANSACTION
BEGIN TRY
-- put your T-SQL commands here
-- if successful - COMMIT the work
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- handle the error case (here by di... | There a problem with the @@ERROR variable.
It's a global variable thus if you are doing something like:
```
BEGIN TRAN
--inserts
--deletes
--updates
-- last operation
IF(@@error <> 0)
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
```
@@error contains the result for the last operation only. Thus this pi... | SQL Server 2008 R2 Transaction is @@error necessary and is ROLLBACK TRANS necessary | [
"",
"sql",
"sql-server-2008",
"transactions",
"sql-server-2008-r2",
""
] |
I have Table Fields (Columns) like
```
ID
DATE
```
I want to insert the rows in above table in between date ranges
For Example:
If I given the date Range like 23/1/2014 to 25/1/2014
then row insertion result should be like this
```
ID | DATES
1 | 23/1/2014
2 | 24/1/2014
3 | 25... | If you want to use generated range in one query then look to the solution of your problem [How to get list of dates between two dates in mysql select query](https://stackoverflow.com/questions/9295616/). | Try this equivalent in MySQL. This works in SQL Serever but not tried in MySQL
```
Declare @date table(autoid int IDENTITY(1, 1),d date)
Declare @d datetime
set @d='20140123'
While @d<='20140125'
Begin
Insert into @date values (@d)
set @d=@d+1
End
Select autoid ,d as DateCol from @date
``` | How i can Insert Dates in the table from given date Ranges | [
"",
"mysql",
"sql",
"date",
""
] |
My Table data looks like
```
Col1 | Col2 | Col3
1 | NULL | NULL
NULL | 2 | NULL
NULL | NULL | 3
```
It is given that for any column there will be only entry. This means that, in the above data, if row1 has value for Col1, then there will be no row with value for Col1. Similarly, if row1 has value for C... | The easiest way to do this is using aggregation:
```
select max(col1) as col1, max(col2) as col2, max(col3) as col3
from t;
``` | Assuming the table is called tab the following query will work if there are only 3 columns:
```
select t1.Col1, t2.Col2, t3.Col3
from tab t1, tab t2, tab t3
where t1.Col1 is not null and t2.Col2 is not null and t3.Col3 is not null
```
The problem is the query will have to alias the table for each additional column. I... | SQL Multiple rows into one row | [
"",
"sql",
"select",
""
] |
The application is datasnap (with sqlite database). I run the following query against two tables (LOKACIJE and UPORABNIKI):
```
procedure TForm4.FormShow(Sender: TObject);
begin
ClientDataSet1.Close;
ClientDataSet1.CommandText :='';
ClientDataSet1.CommandText := 'select lokacije.[HOTEL_ID],'+
... | I believe this is a case in which `TDatasetProvider` is unable to produce the right command to update the tables involved. In this cases, what I do is to add a handler to the `TDatasetProvider.BeforeUpdateRecord` event. This event will let you handle each operation worked on the dataset and produce the needed SQL state... | See the `OnGetTableName` event on the `TDatasetProvider`.
Also, I believe it would be better if you invert your query, i.e., use `... FROM UPORABNKI inner join LOKACIJE...` | Delphi update a joined query | [
"",
"sql",
"sqlite",
"delphi",
"delphi-xe4",
""
] |
My DB has table ip(address, count) and I want to update the 'count' value if address is found in DB, else add a new record. I do this:
```
INSERT INTO ip(address,count)
VALUES('0.0.0.1', 3)
ON DUPLICATE KEY UPDATE count=count+VALUES(count);
```
But as a result a have this table:
```
+----+---------+-------+
| id | a... | create your table using following query
```
CREATE TABLE `ip` (
`id` INT(50) NOT NULL AUTO_INCREMENT,
`address` VARCHAR(40) NULL DEFAULT NULL,
`count` VARCHAR(10) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `address` (`address`)
)
```
Then use following query to insert
```
INSERT INTO ip(... | Have you actually created the unique key on the address column? If you haven't then the ON DUPLICATE KEY UPDATE clause will never run and so rows will keep being created.
Could you update your question to include the schema for the table? | Mysql update if one of fields is a duplicate | [
"",
"mysql",
"sql",
"database",
""
] |
SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.
SO, there is the table `Elem`:
```
+-----------+----+---+----------+------------+
|VERSION(PK)|NAME|KEY|PARENT_KEY|DIST_KEY(FK)|
+-----------+----+---+----------+------------+
|1 |a |12 |NULL |1 |
+... | I have met this problem,I resolved problem by this way
```
--all "parent + grandparent + etc" @childID Replaced with the ID you need
with tbParent as
(
select * from Elem where [KEY]=@childID
union all
select Elem.* from Elem join tbParent on Elem.[KEY]=tbParent.PARENT_KEY
)
SELECT * FROM tbParent
--a... | here is a recursive query giving you both all ancestors and all descendants of an element. Use these together or separate according to the situation. Replace the where clauses to get the desired record. In this example I am looking for key 13 (this is the element with name = b) and find its ancestor 12/a and its descen... | Select all parents or children in same table relation SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"select",
"sql-server-2012",
""
] |
my problem is this:
I have a table named
```
Doctor(id, name, department)
```
and another table named
```
department(id, name).
```
a Doctor is associated with a department (only one department, not more)
I have to do a query returning the department with the maximum number of doctors associated with it.
I am n... | A common approach to the "Find ABC with the maximum number of XYZs" problem in SQL is as follows:
* Query for a list of ABCs that includes each ABC's count of XYZs
* Order the list in descending order according to the count of XYZs
* Limit the result to a single item; that would be the top item that you need.
In your... | You can use `Group BY`
```
Select top (1) department.id,count(Doctor.*) as numberofDocs
from department inner join Doctor on Doctor.id = department.id
Group by department.id
Order by count(Doctor.*) desc
``` | SQL Maximum number of doctors in a department | [
"",
"sql",
"t-sql",
""
] |
I have a table where I am storing timespan data. the table has a schema similar to:
```
ID INT NOT NULL IDENTITY(1,1)
RecordID INT NOT NULL
StartDate DATE NOT NULL
EndDate DATE NULL
```
And I am trying to work out the start and end dates for each record id, so the minimum StartDate and maximum EndDate. StartDa... | It's a bit ugly but because the `NULL`s have a special meaning to you, this is the cleanest way I can think to do it:
```
SELECT recordid, MIN(startdate),
CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
THEN MAX(enddate)
END
FROM tmp GROUP BY recordid
```
That is, if any row has a `NULL`,... | The effect you want is to treat the NULL as the largest possible date then replace it with NULL again upon completion:
```
SELECT RecordId, MIN(StartDate), NULLIF(MAX(COALESCE(EndDate,'9999-12-31')),'9999-12-31')
FROM tmp GROUP BY RecordId
```
Per your fiddle this will return the exact results you specify under al... | How can I include null values in a MIN or MAX? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Simple enough, I can't figure out how to add (that's +) an integer from a textbox to the integer in the SQL Field.
So for example, the SQL Field may have '10' in it and the textbox may have '5' in it. I want to add these numbers together to store '15' without having to download the SQL Table.
The textbox that contain... | Take the current value of the `U_G_Studio` field, add the value of the parameter and reassign to `U_G_Studio`, but keep in mind that you need to pass the value as an integer because otherwise the `AddWithValue` will pass a string and you get conversion errors coming from the db.
```
cmd = New SqlCommand("UPDATE Pe... | You have to use the correct sql:
```
Dim sql = "UPDATE PersonsA SET U_G_Studio=U_G_Studio + @ugpoints WHERE Members_ID=@recevierID"
```
Also use the correct type with `AddWithValue`:
```
Using cmd = New SqlCommand(sql, con)
' use the using-statement to dispose everything that implements IDisposable, so also the ... | SQL Update Column By Adding A Number To Current Int | [
"",
"sql",
"sql-server",
"vb.net",
"sqlcommand",
""
] |
For compound keys in MySQL, does the order of the columns matter for insuring the uniqueness of the rows?
E.g.
```
CREATE TABLE test (
A INT NOT NULL,
B INT NOT NULL,
PRIMARY KEY (A, B)
);
```
Now, assuming I already have a row that contains the values A = 1, B = 2, will MySQL refuse to insert a row wi... | The ordering in an index matters. As a reminder for why the order matters, consider what happens if the types are incompatible -- say `date` and `varchar(255)`. The values are not interchangeable.
If you want uniqueness for both values, then you are going to need to add a trigger. The trigger can probably implement a ... | no, it does not matter for uniqueness, it is only important for sorting and access time | MySQL Compound Primary Key Column-Order-Insensitivity | [
"",
"mysql",
"sql",
""
] |
I'm working on an Oracle database with an error made by a user. The issue is a number of person records were moved into a different "round". Each round has "episodes": Wrong "round" means all the episode processing has been affected (episodes skipped over). These users won't receive mails they were supposed to receive ... | Sorry to see this post that late... Hope it's not too late...
I suppose you are using Oracle 10+, and you know approximately the hour of the crime (!).
I see 2 possibilities:
1) Use the Log Miner to review the executed SQL: <http://docs.oracle.com/cd/B19306_01/server.102/b14215/logminer.htm>
2) Use the flashback qu... | If you want to find all tables with column "round\_no" you probably should use this query
```
select table_name from all_tab_columns where column_name='round_no'
``` | Find the tables affected by user error & reverse the mistake | [
"",
"sql",
"oracle11g",
""
] |
I am using the Select and Right Join SQL functions to call all the data into one table. Data being called will only populate if ans\_primary = '1' on the Assignment table.
If asn\_primary = '1' then it will join all the below columns on att\_id = att\_id for both tables.
The two tables and the columns used are below:
... | The syntax for `join` in an `update` in SQL Server is:
```
Update att
set att_name = att_name + '.tif'
from assignment a join
attachment att
on a.att_id = att.att_id
where a.asn_primary = '1' and
att.att_path3 like '%.tif%';
```
The `right outer join` doesn't seem appropriate, ... | What you're looking for is referred to as a side-effecting query. You'll want to follow the basic structure as below. Be careful of the results. If a row shows up three times, it will be updated three times. This can significantly affect server performance and the resulting logs.
I usually imbed a 'SELECT \*' to allow... | Update a Column after a SQL Join | [
"",
"sql",
"sql-server-2008",
"sql-update",
"right-join",
""
] |
this query is working fine.
```
UPDATE data
SET unit_id='a3110a89'
WHERE unit_id='7d18289f';
```
Now, I need to run this query over 30 times
so I made csv file import it to the DB with this command:
```
COPY mytable FROM 'D:/test.csv' WITH CSV HEADER DELIMITER AS ','
```
Now I have table called my table with 2 ... | Your subqueries need to be correlated to the outer update:
```
UPDATE data
SET unit_id = (SELECT mytable."new" FROM public.mytable where data.old = mytable.old)
WHERE unit_id in (SELECT mytable."old" FROM public.mytable);
```
That is, set the `unit_id` to the "new" value, when you find the "old" value in the ta... | Can you try like this,
```
UPDATE data A
SET A.unit_id=B.old
FROM (SELECT mytable."old",mytable."new" FROM public.mytable) B
WHERE A.unit_id=B.new
``` | SQL update set table if value in table A is equals to value in table B | [
"",
"sql",
"postgresql",
"sql-update",
""
] |
I am using Mysql Workbench. I have already made the table.
Now I want to add foreign key in a table called `Personal_Details` that key is primary key in `Login` table.
But when I am trying to do so, it shows me the following error:
```
ERROR 1005: Can't create table 'shaadiDB.#sql-404_25' (errno: 121)
```
SQL Statem... | before adding any constrain to a table that already have some data might cause this problem,try to add constrain with out data | It seems that the table `Personal_Details` is having data from which there might be some rows with Login\_Id for which entry is not present in table `Login`.
If this is the case , then solution would be that you need to move the data to another table, then add constraint. After adding the constraint you need to add al... | Error while adding Foreign key | [
"",
"mysql",
"sql",
"foreign-keys",
"innodb",
"foreign-key-relationship",
""
] |
lets say here is my DB structure
```
TableA
{
[ID] INT IDENTITY (1, 1) primary key,
[Title] varchar (50) NOT NULL,
[Details] varchar(50) NOT NULL
}
TableB:
{
[ID] INT foreign key references [TableA] ([ID])
[AvailableTime] DATETIME NOT NULL
}
TableC:
{
[ID] INT foreign key references [TableA] ([ID... | You'll need to do processing on the client in either case to get a "tree" out of SQL. SQL returns *tabular* data which is de-normalized.
---
> Performance wise and speed wise, would it be better if I do two separate queries to retrieve those information or do a join and then loop through the list twice?
*Usually*, d... | If I understand the question correctly, you don't need a `join` at all:
```
select PropertyA
from tableA
where id = XXX
union all
select PropertyC
from tableB
where id = XXX;
```
If you want to remove duplicates, change `union all` to `union`. | SQL - multiple queries or one join | [
"",
"sql",
"join",
""
] |
I am trying to `SELECT` rows in a table, by applying a filter condition of identifying number only columns. It is a report only query, so we least bother the performance, as we dont have the privilege to compile a PL/SQL am unable to check by `TO_NUMBER()` and return if it is numeric or not.
I have to achieve it in SQ... | I just tried to correct the mistakes of you and made the SQL simple as possible. But not neat!
```
WITH dummy_data AS
( SELECT '-1.0' AS txt FROM dual
UNION ALL
SELECT '+.0' FROM dual
UNION ALL
SELECT '-.1' FROM dual
UNION ALL
SELECT '+1,2034.89.0' FROM dual
UNION ALL
SELECT '+1,2034.89' FROM dual
... | First you remove plus and minus with translate and then you wonder why their position is not considered? :-)
This should work:
```
WITH dummy_data AS
( SELECT '-1.0' AS txt FROM dual
UNION ALL
SELECT '+0.1' FROM dual
UNION ALL
SELECT '-.1' FROM dual
UNION ALL
SELECT '+12034.89.00' FROM dual -- invalid: ... | Filter the rows with number only data in a column SQL | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a table with people and timestamps. Each person has multiple timestamps
```
SELECT person, time FROM table;
A 1
A 2
B 1
B 2
B 3
```
I would like to get the most recent timestamp for each person
```
SELECT ????
A 2
B 3
``` | `GROUP BY` will do the trick :
```
SELECT person, MAX(time)
FROM table
GROUP BY person
``` | In Oracle:
```
SELECT person, MAX(time)
FROM table
GROUP BY person
``` | Most recent timestamp for each person | [
"",
"sql",
""
] |
Before Query
```
User Friend
A B
A C
D A
F A
```
After Query
```
User Friend
A B
A C
A D
A F
```
How can I get the result shown. I want to get all friends of A. | With a union:
```
select user, friend
from t
where user = 'A'
union
select friend, user
from t
where friend = 'A'
```
Notice than `Union` behavior is `distinct` that is that you expect ( opposed to `union all` ) | Try this
```
SELECT USER AS 'User',
friend AS 'Friend'
FROM t
WHERE USER = 'A'
UNION
SELECT friend ,
USER
FROM t
WHERE friend = 'A'
``` | How to query a pair like table structure? | [
"",
"sql",
"sql-server",
""
] |
I am new to database and making a gym management system, I implemented a database from the tutorials on www.homeandlearn.co.uk. I have completed the project without foreign keys. Now I have to link tables but I am getting this error:
> Update cannot proceed due to validation errors.
> Please correct the following er... | This is your table `instructor_info`
```
[dbo].[instructor_info]
PRIMARY KEY CLUSTERED ([InstructorID] ASC)
```
So if you want to reference that primary key from your table `member_info`, you must reference **that exact column name** (`InstructorID`).
So your current FK constraint won't work - you need to reference... | You have to create primary keys for your tables in order to reference them in your foreign keys. Below an example of creating a table with a primary key, so you don't stumble on this error later on.
```
CREATE TABLE member_info (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
) ENGIN... | Foreign Key confusion | [
"",
"sql",
"sql-server",
"database",
""
] |
I have a DB in which there is a table `shows` with a multilingual column `title`. I would like to optimise full text search by adding an index like so:
```
CREATE INDEX title_idx ON shows USING gin(to_tsvector(title));
```
I get this error:
```
ERROR: functions in index expression must be marked IMMUTABLE
```
It b... | > Is it possible to create an index that works for several languages ?
Yes, but you need a second column that identifies the language of the text. Say you added a column `doc_language` to the table; you could then write:
```
CREATE INDEX title_idx ON shows USING gin(to_tsvector(doc_language, title));
```
Of course, ... | I've just made a Postgres function to test the text language. It's not perfect but it works for long texts.
```
CREATE OR REPLACE FUNCTION get_language(t text) RETURNS regconfig AS $$
DECLARE
ret regconfig;
BEGIN
WITH l as ( SELECT cfgname, to_tsvector(cfgname::regconfig, title) as vector, length(t... | Full text search index on a multilingual column | [
"",
"sql",
"postgresql",
""
] |
I have a query that exports its results via email in a table format, i would really like to hide the first row of my data so it never gets exported with my results.
Example database table:
```
+------+--------+--------+
|Number|Language|Date |
+------+--------+--------+
|2039 |text 1 |20/01/14|
+------+--------+... | `` SELECT COUNT(*) as `count`,`lang`, DATE(NOW()) as `week_ending` FROM mydata.table WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) GROUP BY `lang`, DATE(NOW()) LIMIT 1,x; ``
replace x with a number big enough to contain all your records.
or use, instead of x, 18446744073709551615, th... | Use LIMIT 1, N at the End of query.
Where N is the number of rows you want to retrieve. | Hide first row in database query | [
"",
"mysql",
"sql",
"select",
""
] |
I am trying to generate a report for accepted orders each month against the total orders for that month. For example, I have a table `Orders` like so:
```
Order_Id Submit_Date Order_Status
-------- ----------- ------------
1 20130501 Accepted
2 20130509 Rejected
3 ... | Assuming you will never have a time component, this should work just fine:
```
DECLARE @d TABLE([Order] INT, [Date] DATETIME, [Status] CHAR(8));
INSERT @d VALUES
(1 ,'20130501','Accepted'),
(2 ,'20130509','Rejected'),
(3 ,'20130610','Accepted'),
(4 ,'20130614','Accepted'),
(5 ,'20130626','Rejected'),
(6 ,'20130802','... | To get yyyy-dd format you can use this
```
SELECT CONVERT(VARCHAR(7),[Date],20)
,COUNT(CASE WHEN [status] = 'Accepted' THEN 1
ELSE NULL END) AS 'Accepted'
,COUNT(*) AS Total
FROM Orders
GROUP BY CONVERT(VARCHAR(7),[Date],20)
``` | How to group filtered rows against non filtered by month | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
sorry I don't know how else to put the title into words. Below is my code.
```
SELECT DISTINCT association.NamaBadan,
(
CASE
WHEN type = 5
THEN 'Batal'
WHEN NamaBadan LIKE '%BATAL%'
THEN 'Batal'
ELSE 'Sah'
END
) AS STA... | Solved it by the following query
```
SELECT DISTINCT association.NamaBadan,
(
CASE
WHEN type = 5
THEN 'Batal'
WHEN NamaBadan LIKE '%BATAL%'
THEN 'Batal'
ELSE 'Sah'
END
) AS STATUS
FROM association
LEFT JOIN tindakan
... | You can try either a `Group by` clause or an `order by` clause to sort the results for you.
then you might try this:
```
SELECT association.NamaBadan,
(
CASE
WHEN type = 5
THEN 'Batal'
WHEN NamaBadan LIKE '%BATAL%'
THEN 'Batal'
ELSE 'Sah... | In SQL query, if condition exist, select that condition over anything else | [
"",
"mysql",
"sql",
""
] |
i an new in vb.net sql and what i am asking may be silly question. I have a table in sql server 2005 and a column name activated. this column contain NULL, true or false.
I want to select only NULL or false values. How can i do this? | The selection should be done on the SQL Server's side. Your query should look like this:
```
SELECT *
FROM MyTable
WHERE activated = 0 OR activated is NULL
```
The above assumes that the column `activated` is of an integral or a `BIT` data type.
Note: it may be tempting to use a seemingly equivalent `WHERE activated... | With SQL's 3-valued logic, comparisons for NULL need to be done using the `IS NULL` operator... the check for false can be done with `=`:
```
SELECT YourColumn
FROM YourTable
WHERE
YourColumn IS NULL
OR YourColumn = 0
``` | select NULL and false but not true in sql | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
Good Evening,
I have the following sql code and need to replace the NULL values within a sub query. As you can tell from the code I have tried using the ISNULL function and case where = NULL.
Could someone please help?
```
Select Student_Details.STU_ID ,
( Select case ISNULL( s1stu_disability_type.DISABILITY_... | Try this:
```
Select Student_Details.STU_ID ,
IsNull(( Select case ISNULL( s1stu_disability_type.DISABILITY_TYPE_CD , '' )
when '' then 'NO'
else 'YES'
end
from s1stu_disability_type
Where Student_Details.STU_ID = s1stu_disability_type.STU_ID
and DISA... | Your `where` clause in your subquery rejects all rows but those where the column `DISABILITY_TYPE_CD` is `'$HEAR'`. Consequently, the `case` statement will always take the `else` route, as that column will never, ever be `null` or empty (`''`).
What exactly are you trying to do?
You query can better be written as
``... | Case Statement with IS NULL not acting as required | [
"",
"sql",
"sql-server",
"t-sql",
"null",
"case",
""
] |
Suppose I have a table of election data, call it ELECTIONS, with one row per voter per election, like so:
```
VoterID ElectionID
A 1
A 2
B 1
C 2
D 3
E 1
E 2
```
I want to know the number of voters who voted both in election 1 and in election 2; I d... | Yes. what you have should work. (You will need to add an alias on the derived table, the error messsage you get should be self explanatory. Easy to fix, just add a space and the letter c (or whatever name you want) at the end of your query.
There's one caveat regarding the potential for duplicate `(VoterID, ElectionID... | I would recommend something more like this:
```
SELECT COUNT(*) AS NumVoters
FROM ELECTIONS e1
WHERE e1.ElectionID = 1
AND e1.VoterID in (
SELECT e2.VoterID
FROM ELECTIONS e2
WHERE e2.ElectionID = 2
);
```
That way you solve the problem, and have only 1 subquery. | SQL query to count number of times certain values occur in multiple rows | [
"",
"mysql",
"sql",
""
] |
When I use the following statement I just get `NULL` back where it's supposed to return values and undefined fields where the column value is blank.
`SELECT STR_TO_DATE(strdate, '%Y-%m-%d %H:%m:%s') from table`

My date format is set to `2013-12-11 ... | The correct code for minutes is `%i` not `%m`:
```
SELECT STR_TO_DATE(strdate, '%Y-%m-%d %H:%i:%s')
from (select '2013-12-11 00:58:00' as strdate) t
``` | The culprit is `'%Y-%m-%d %H:%m:%s'` - `%m` can't stand for month **and** minute. IIRC `%m` is correct for them month, and `%i` is what you want for the minute. | NULL when converting VARCHAR to DATETIME | [
"",
"mysql",
"sql",
""
] |
Im working on a website that processes statistics, for a sporting competition. I.E my site will let users quickly look up which player(s) scored the most points in a game/season or what 1 players record is against another players or team.
*My data for previous games are displayed like this*
![enter image description h... | Capture the statistics at the lowest applicable level. You want to apply the principles of database normalization to your initial design. This gives you the most straight-forward data capture scenario while leaving you the most flexibility for reporting.
Once you decide exactly what reporting you need and have determi... | If the hope of teaching how to fish....
Write out what Entities you think you have, and what attributes they own. An attribute might be another Entity. For example a Team entity has a Name attribute, and multiple Player attributes. But Player is also an Entity with a Name attribute and maybe some Statistics attributes... | Need help creating structure to database | [
"",
"mysql",
"sql",
"database",
"database-design",
"data-structures",
""
] |
I am fetching rows from my DB using this request:
```
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY 'amount' DESC
```
So, obviously, i expected the returned values to be sorted in descending order by the amount column in my DB, but it doesn't? it still fetches them, but just doesn't sort them?
Any ideas ... | ORDER BY clause uses column name.
Column name should not give in quotes.
there fore the query becomes as follows
```
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
``` | remove single quote around amount like this and try:
```
SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
``` | MySQL sort by not sorting? | [
"",
"mysql",
"sql",
"sorting",
""
] |
I have a table called `flags` that contains a column called `coordinates` that is full of MySQL 'points'. I need to perform a query where I get all the flags within a circle based on a latitude and longitude position with 100m radius.
From a usage point of view this is based around the user's position. For example, th... | ~~**There are no geospatial extension functions in MySQL supporting latitude / longitude distance computations.**~~ [There is as of MySQL 5.7](https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-distance-sphere).
You're asking for proximity circles on the surface of the earth. You me... | **UPDATE**
**Use ST\_Distance\_Sphere() to calculate distances using a lat/long**
<http://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-distance-sphere> | Use MySQL spatial extensions to select points inside circle | [
"",
"mysql",
"sql",
"geospatial",
""
] |
I have a table
```
id user Visitor timestamp
13 username abc 2014-01-16 15:01:44
```
I have to 'Count' total visitors for a 'User' for last seven days group by date(not timestamp)
```
SELECT count(*) from tableA WHERE user=username GROUPBY __How to do it__ LIMIT for last seven day from today.
```
If any day... | There is no need to `GROUP BY` resultset, you need to count visits for a week (with unspecified user). Try this:
```
SELECT
COUNT(*)
FROM
`table`
WHERE
`timestamp` >= (NOW() - INTERVAL 7 DAY);
```
If you need to track visits for a specified user, then try this:
```
SELECT
DATE(`timestamp`) as `date`,... | Try this:
```
SELECT DATE(a.timestamp), COUNT(*)
FROM tableA a
WHERE a.user='username' AND DATEDIFF(NOW(), DATE(a.timestamp)) <= 7
GROUP BY DATE(a.timestamp);
``` | match timestamp with date in MYSQL using PHP | [
"",
"mysql",
"sql",
"date",
"select",
"group-by",
""
] |
I want to insert the current date into one of the columns of my table. I am using the following:
```
to_date(SYSDATE, 'yyyy-mm-dd'));
```
This is working great, but it is displaying the year as '0014'. Is there some way that I can get the year to display as '2014'? | to\_date is used to convert a string to a date ... try to\_char(SYSDATE, 'yyyy-mm-dd') to convert a date to a string. | Inserting it as `TRUNC(sysdate)` would do. Date actually doesn't have a format internally as it is DataType itself. TRUNC() actualy will just trim the time element in the current date time and return today's date with time as 00:00:00
To explain what happened in your case.
say ur `NLS_DATE_FORMAT="YY-MM-DD"`
The Pro... | Formatting value of year from SYSDATE | [
"",
"sql",
"oracle",
""
] |
How can I select Current Month records from a table of MySql database??
Like now current month is January. I would like to get records of January Month, Where data type of my table column is `timestamp`.I would like to know the sql query.
Thanks | This query should work for you:
```
SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
``` | Check the [**MySQL Datetime**](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html) Functions:
Try this:
```
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
``` | Get records of current month | [
"",
"mysql",
"sql",
"date",
"select",
"timestamp",
""
] |
Here is my query:
```
select * from students where status != 4.
```
I am not getting rows with status null.
Shouldn't it return all the rows where status is not 4 - including rows with null status values?
I can get what I need by following query.
```
select * from students where status != 4 or status is null
``` | Use:
IS DISTINCT FROM
```
SELECT * FROM students WHERE status IS DISTINCT FROM 4;
```
<http://www.postgresql.org/docs/current/interactive/functions-comparison.html> | SQL's understanding of `NULL` is ["three-valued"](http://en.wikipedia.org/wiki/Three-valued_logic#Application_in_SQL). Think of `NULL` as `UNKNOWN`. So, in other words:
```
UNKNOWN = 4 yields UNKNOWN
UNKNOWN != 4 yields also UNKNOWN
```
In other words, if a student has `status is null`, then it is "unknown" whe... | postgres column with nulll values and filtering with "!=" | [
"",
"sql",
"postgresql",
""
] |
I want to query a table for all the values that are on a list on another table to find matches, but I know that some of the values in either table may be typed in incorrectly. One table may have '10Hf7K8' and another table may have '1OHf7K8' but I still want them to match.
Another example, if one table has 'STOP' but ... | Cleaning data is preferable, but could use nested `REPLACE()` statements if you can't alter the underlying data:
```
SELECT *
FROM Table1 a
JOIN Table2 b
ON REPLACE(REPLACE(REPLACE(a.field1,'2','Z'),'5','S'),'0','O') = REPLACE(REPLACE(REPLACE(b.field1,'2','Z'),'5','S'),'0','O')
```
Cleansing the data could be the s... | what you can and should do is to clean your data, replace all these `2,0,5` with `Z,O and S`.
But if you want to try some other solution, then you can try something like this
```
select case when
REPLACE(REPLACE(REPLACE('stop','0','o'),'5','s'),'2','Z') = REPLACE(REPLACE(REPLACE('5t0p','0','o'),'5','s'),'2','Z') the... | Ignoring specific letters to find match in SQL Query | [
"",
"sql",
"sql-server",
""
] |
Here is my source data,
```
Group | Item | Capacity
-----------------------
1 | A | 100
1 | B | 80
1 | C | 20
2 | A | 90
2 | B | 40
2 | C | 20
```
The above data shows the capacity to consume "something" for each item.
Now suppose I have maximum 100 allocated to each gro... | Without a subquery using just the analytic SUM function:
```
SQL> create table mytable (group_id,item,capacity)
2 as
3 select 1, 'A' , 100 from dual union all
4 select 1, 'B' , 80 from dual union all
5 select 1, 'C' , 20 from dual union all
6 select 2, 'A' , 90 from dual union all
7 select 2, 'B' ... | Here's a solution using recursive subquery factoring. This clearly ignores your preference to avoid subqueries, but doing this in one pass might be impossible.
Probably the only way to do this in one pass is to use [MODEL](http://docs.oracle.com/cd/E11882_01/server.112/e25554/sqlmodel.htm#DWHSG022), which I'm not allo... | SQL query to Calculate allocation / netting | [
"",
"sql",
"oracle",
""
] |
I have the following Input table:
```
Article Store Supplier NetPrice Pieces Sum Inventory Price Cond
NL1234 N001 3100000 161,5 2 323 7 123,45 2,47
NL1234 N001 3100000 161,5 0 0 4 103,8 2,08
NL1234 N001 ... | You cant use (Inventory\*Price)/sum(Inventory) because you are not grouping by Inventory column. You only can use aggrigation functions like sum(Inventory).
```
SELECT
Article,
SUM(Pieces) as "Pieces",
SUM(Sum) as "Sum",
SUM(Inventory) as "Inventory",
SUM(Inventory * Price) / SUM(Inventory) as "Pr... | Move the row totals into a `CROSS APPLY`, then use the result of that in the query like so:
```
SELECT Article,
Store,
Supplier,
MAX(NetPrice),
sum(Pieces) as "Pieces",
sum(Sum) as "Sum",
sum(Inventory) as "Inventory",
T.TotalInvCost/sum(Inventory) as "Price",
T.... | Calculation on multiple rows | [
"",
"mysql",
"sql",
"sql-server",
"select",
"hana",
""
] |
I wanted to use function LEAST in my procedure to find the smallest value. The problem is that some of the values might have been NULLs so if I do
```
select least(NULL,0,1) from dual
```
The answer I get is NULL, which is probably correct by is not something I am expecting to return. I would like to get the least re... | I doubt that's actually your query. Maybe you're doing something more like this?
```
select least(some_column) from dual
```
If so, change it to this:
```
select least(some_column) from dual where some_column is not null
```
---
Or, if you're doing something more like this, where you can't just use `where` to filt... | If any argument is NULL, you want to take the least of the other argument(s). If all arguments are NULL, you want to return NULL.
I might use something like this for two arguments:
```
LEAST(NVL(colA,colB), NVL(colB,colA))
```
It starts getting ugly for >2 arguments though:
```
LEAST(COALESCE(colA,colB,colC)
,... | Least value but not NULL in Oracle SQL | [
"",
"sql",
"oracle",
""
] |
my table's schema is something like
```
Table A
Id | val | updatedtime
```
Where updatedtime column is of the type Datetime,
I need to find all the records from db where the time difference between current time and updatedtime of the db is less than 5 min. I couldn't find any right approach on the internet | Like such?
```
SELECT *
FROM TableA
WHERE updatetime > DATEADD(MI, -5, GETDATE())
``` | ```
SELECT *
FROM TableA
WHERE DATEDIFF(minute,updatedtime,GETDATE()) < 5
```
Yo can use **[DATEDIFF](http://technet.microsoft.com/en-us/library/ms189794.aspx)**
> Returns the count (signed integer) of the specified datepart
> boundaries crossed between the specified startdate and enddate | Difference between 2 datetimes in sql server | [
"",
"sql",
"sql-server",
"date",
"datetime",
""
] |
We have a table which have millions of entry. The table have two columns, now there is correlation between X and Y when X is beyond a value, Y tends to be B (However it is not always true, its a trend not a certainty).
Here i want to find the threshold value for X, i.e(X1) such that at least 99% of the value which are... | This is mostly inspired from the previous answer, which had some flaws.
```
select max(next_x) from
(
select
count(case when y='B' then 1 end) over (order by x) correct,
count(case when y='G' then 1 end) over (order by x) wrong,
lead(x) over (order by x) next_x
from table_name
)
where... | Ok, I think this accomplishes what you want to do, but it will **not** work for the data volume you are mentioning. I'm posting it anyway in case it can help someone else provide an answer.
This may be one of those cases where the most efficient way is to use a cursor with sorted data.
Oracle has some builting functio... | Calculating data point which have Precision of 99% | [
"",
"sql",
"oracle",
"aggregate-functions",
"precision",
"percentile",
""
] |
Within a stored proc ,I want to include an AND clause in a query only if a particular condition is satisfied.
```
INSERT INTO #firstResults
SELECT x, y, z FROM ep
WHERE ep.proposedBy = @Id
AND ep.pId IN ( SELECT DISTINCT pId FROM #tempProj)
```
The 'AND' clause should join in only when the #tempProj is not... | Try this ...
```
AND (ep.pId IN (SELECT DISTINCT pId FROM #tempProj)
OR (SELECT COUNT(*) FROM #tempProj) = 0))
``` | ```
IF EXISTS (SELECT * FROM #tempProj)
BEGIN
INSERT INTO #firstResults
SELECT x, y, z FROM ep
WHERE ep.proposedBy = @Id
AND ep.pId IN ( SELECT DISTINCT pId FROM #tempProj)
END
ELSE
BEGIN
INSERT INTO #firstResults
SELECT x, y, z FROM ep
WHERE ep.proposedBy = @Id
END
``` | Dynamic AND clause | [
"",
"sql",
"sql-server",
""
] |
So I have a file that has over 100 entries in it as an excel worksheet. I want to put those over into a sql. So I fire up my sql developer and try and import the data but it doesn't show up.

The next and finish buttons don't do anything. (the blue underline w... | Have you tried converting the original file to text (csv) then importing? That has worked for me in the past. | I had the same problem and the only way to get rid of it was to rename the preferences folder (as described here: <https://www.thatjeffsmith.com/archive/2015/08/how-to-reset-your-sql-developer-preferencessettings/>) and start the program with factory defaults. | SQL developer Import data wizard comes up blank | [
"",
"sql",
"sql-server",
"excel",
"import",
"oracle-sqldeveloper",
""
] |
I am designing a DB and I cannot figure out how to model the following situation:
* There is a main table that is called "Transaction".
* Every transaction has a "Status" to describe it.
* Every status has 1 or 2 "Substatus" to describe it.
* A "Substatus" can have a "Subsubstatus" to describe it.
Moreover I need to ... | You are desrcribing several things.
1. `Transaction` has a `Status`, a `SubStatus` and a `SubSubStatus`.
2. There is a parent child relationship between `Status` and `SubStatus`.
3. These is a parent child realtionship between `SubStatus` and `SubSubStatus`.
4. A `Transaction`'s `Substatus` is contrained by its `Statu... | Store the all the (sub)\*statuses in the same table.
```
STA_Id,STA_Name,*SuperStatus_ID*
```
You might also want an extra field, `STA_Depth` to indicate how many sub levels you are down. | Database design: different precision level to describe a table | [
"",
"sql",
"database",
"database-design",
""
] |
I am trying to check if there is any zeros in Flag1 or Flag2 fields but I am getting the wrong results here when I run the code below. In this case I know there is one zero in Flag1 field but my count is zero when I run the SQL. If there is one zero in either field then I am expecting to see the count to be either >=1.... | ```
select count(*) from myTable
where (FLAG1 = 0 or FLAG2 = 0)
and ID = 202
``` | Instead of `and` use `or` (and don't use `in` unless you provide a list of values or a subquery):
```
select count(*) from myTable
where (FLAG1=0 or FLAG2=0)
and ID = 202
``` | How to check if there is any Zeros in Column Fields using SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
iEndDate = Year(Now)
For iStartDate As Int32 = 1900 To iEndDate
StartDate = Format(dtpSD.Value, "dd/MMM") + "/" + iStartDate.ToString
EndDate = Format(dtpED.Value, "dd/MMM") + "/" + iStartDate.ToString
lSql = lSql & " And" & " MD.MD_DOB >= '" & StartDate.ToString & "' AND MD.MD_DOB <= '" & EndDate.ToString & "'"
... | Get days and numeric values of month and use next `WHERE` clause
```
...
WHERE MONTH(MD.MD_DOB) > @StartMonth AND MONTH(MD.MD_DOB) < @EndMonth
OR (MONTH(MD.MD_DOB) = @StartMonth AND DAY(MD.MD_DOB) >= @Startday)
OR (MONTH(MD.MD_DOB) = @EndMonth AND DAY(MD.MD_DOB) <= @Endday)
```
You don't need to set year in the `WHER... | I would say you can use a fixed year, for instance:
```
DECLARE @startDate DATETIME = '2000-02-01'
DECLARE @endDate DATETIME = '2000-03-31';
WITH cal
AS ( SELECT *,
CAST('2000-' + CAST(MONTH(BirthDate) AS VARCHAR) + '-' + CAST(DAY(BirthDate) AS VARCHAR) AS DATETIME) FakeBirthday
... | Single Query to get values from Sql server 2008 table based on Birthdate(dd/mmm). User will not specify Year | [
"",
"sql",
"sql-server",
"vb.net",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have 3 Tables
```
Item, Primary, Secondary
```
i want it to return `All columns` on Items and `Brandname` from Primary and `Size, Color`
from Secondary
ItemID - pk(item)
ItemID - fk(Primary)
ItemID - fk(Secondary)
i know how to do 2 tables but I'm having problem on how to do 3 tables
here's my code
```
From Ite... | Since primary is a reserved word, surround the word primary with brackets []
[Edit to explain comment]
Using the query that @janet wrote, try adding an open paren before the item table and a closing paren just before the second inner join.
```
SELECT a.*, b.Brandname, c.Size, c.Color
FROM (Item a
INNER JOIN [Prim... | try this:
```
From Item
JOIN [Primary] ON Item.ItemID=[Primary].ItemID
JOIN [Secondary] ON Item.ItemID=[Secondary].ItemID
``` | How to join 3 tables in MS access | [
"",
"sql",
"ms-access",
""
] |
I need to find how many true bit exists in my binary value.
example:
```
input: 0001101 output:3
input: 1111001 output:5
``` | ```
DECLARE @BinaryVariable2 VARBINARY(10);
SET @BinaryVariable2 = 60; -- binary value is 111100
DECLARE @counter int = 0
WHILE @BinaryVariable2 > 0
SELECT @counter +=@BinaryVariable2 % 2, @BinaryVariable2 /= 2
SELECT @counter
```
Result:
```
4
``` | While both answers work, both have issues. A loop is not optimal and destructs the value. Both solutions can not be used in a select statement.
Possible better solution is by masking together as follows
```
select @counter = 0
+ case when @BinaryVariable2 & 1 = 1 then 1 else 0 end
+ case when @BinaryVariable2 & 2 =... | Calculate Count of true bits in binary type with t-sql | [
"",
"sql",
"t-sql",
"count",
"binary",
"varbinary",
""
] |
I would like to find out for which discount ids the expirationDate has changed. Here is a snapshot of the table. I will need to do a self join.
```
tablename discountid expirationdate
NEW 182150 2013-12-02 00:00:00.000
OLD 182150 2099-12-31 00:00:00.000
NEW 182151 2013-12-02 00:00... | From the comments I gather that you don' only look for changes of expiration dates, but for several columns. Here is a solution:
```
select discountid
, decode(min(a),max(a),0,1) as a_changed
, decode(min(b),max(b),0,1) as b_changed
, decode(min(c),max(c),0,1) as c_changed
from test
group by discountid
having
de... | Here is one way to find the ids having two different expiration dates in the table:
```
select discountid
from mytable
group by discountid
having count(distinct expirationdate) > 1;
``` | I would like to find out for which discount ids the expirationDate has changed. Here is a snapshot of the table. I will need to do a self join | [
"",
"sql",
""
] |
MySQL query:
```
CREATE TABLE FC_Categories (
CategoryID INTEGER NOT NULL AUTO_INCREMENT ,
CategoryName VARCHAR( 15 ) ,
Description TEXT,
Picture LONGBLOB,
UNIQUE (
CategoryName
),
PRIMARY KEY ( CategoryID )
) TYPE = MYISAM ;
```
MySQL error after running query:
```
Documentation #1064 - You have an error in your SQ... | `Type` is obsolete now, and hence is the error.
Use `Engine=MyISAM` | please use `ENGINE=MyISAM` instead. | how to remove mysql error #1064? | [
"",
"mysql",
"sql",
"syntax-error",
""
] |
I'm creating a commenting system, which will have 2 top comments.
How can I select the latest 20 rows, and then from that selection, select the top 2 rows (likes-dislikes)? I can do it with a PHP loop, but it would not be as efficient. Currently I am just selecting the top 2 from the all the comments, but the two top ... | Nest your query:
```
SELECT *
FROM (
SELECT *
FROM pagecomments
WHERE page_id='$pageid'
ORDER BY date DESC
LIMIT 20
) t
ORDER BY likes-dislikes DESC
LIMIT 2
``` | Order not only by LIkes, first order by date entered or timestamp. By ordering by date, you assure that you`ll get the latest 20 posts or comments.
```
SELECT * FROM pagecomments WHERE page_id='$pageid' ORDER by date_entered desc ,
likes-dislikes DESC limit 2
``` | How to select from a selection? | [
"",
"mysql",
"sql",
""
] |
Consider a table Users with columns Id, Name, Surname and a table Actions with columns Ip and Actor. I need to retrieve, for every Ip, the set of users who did as action using that Ip.
What I have now looks like:
```
SELECT a.ip, (
SELECT GROUP_CONCAT(t.id, '-', t.name, ' ', t.surname) FROM(
SELECT ud.id, ... | I solved it using this query (still quite slow, so there's still space for improvements...):
```
SELECT SQL_NO_CACHE t.ip, COUNT(t.id) AS c, GROUP_CONCAT(t.id, '-', t.name, ' ', t.surname, '-', t.designerAt > 0) FROM (
SELECT a.ip, ud.id, ud.name, ud.surname, u.designerAt
FROM actions AS a
JOIN users_da... | You can rewrite your query as
```
SELECT n.ip, GROUP_CONCAT( DISTINCT n.your_user SEPARATOR ' -- ') `users` FROM
(
SELECT a.ip AS ip, CONCAT(t.id, '-', t.name, ' ', t.surname) `your_user`
FROM users_data AS ud
JOIN actions AS a ON a.actor = ud.id
) `new_table` n
WHERE n.ip != '' AND n.ip != '0.... | mysql - rewrite query with subqueries | [
"",
"mysql",
"sql",
""
] |
I created a fiddle for this, at this link:
<http://www.sqlfiddle.com/#!2/7e007>
I could'nt find SQL compact / CE so it's in MySQL.
The tables looks like this
```
Records Clients
ID | NAME | AGE ID | NAME
------------------ ----------------
1 | John | 20 ... | ```
select r.id,
IF(c.name != '',c.name,r.name) as name,
r.age
FROM Records r
LEFT JOIN Clients c ON c.id = r.id
GROUP BY c.id
```
Use above query.
**EDITED:**
```
SELECT t.id, t.name, t.age FROM
(
(
SELECT r.id,
CASE WHEN c.name <> '' THEN c.name ELSE r.name END as name,
... | ```
select case when a.id <> '' then a.id else b.id end as id ,
case when a.name <> '' then a.name else b.name end as name,a.age
from records a
full outer join clients b on a.Id = b.id
order by a.id
``` | Select from other table if value exist | [
"",
"sql",
"sql-server-ce",
""
] |
I've been creating a database in derby/netbeans. And I'd like to output the structure of the database, not just exporting the whole database. How do I do this?
I've tried both "EXEC 'table name';"
which returned
"Error code -1, SQL state 42X01: Syntax error: Encountered "exec" at line 1, column 1."
and
"SELECT \* FROM... | **GET TABLE STRUCTURE**
```
select COLUMNNAME,COLUMNDATATYPE
FROM sys.systables t, sys.syscolumns
WHERE TABLEID = REFERENCEID and tablename = 'FRIENDS'
```

Other fields you can use in select
* COLUMNDEFAULT
* COLUMNDEFAULTID
* AUTOINCREMENTVALUE... | The simplest with NetBeans (8.0, perhaps with the previous versions too): "View Data..." of the table, right click on the data and choose "Show SQL Script for CREATE". You can copy the SQL script. | Get table schema or structure in netbeans, derby | [
"",
"sql",
"netbeans",
"schema",
"structure",
"derby",
""
] |
Hello I have three tables that I have joined but it returns empty result even though there suppose to some result. Here is my sql
```
SELECT c.code,c.name, a.ltp as begning, b.ltp as enddate, d.interim_cash,d.interim_rec_date,
CAST(((b.ltp - a.ltp) / a.ltp * 100) AS DECIMAL(10, 2)) as chng
FROM eod_stock a
JOIN eod_st... | So finally I got what i needed here is the query:
```
SELECT c.code,c.name, a.ltp as begning, b.ltp as enddate, d.interim_cash,d.interim_rec_date, d.annual_rec_date,d.annual_cash,
CAST(((b.ltp - a.ltp) / a.ltp * 100) AS DECIMAL(10, 2)) as chng
FROM eod_stock AS a
LEFT OUTER JOIN eod_stock AS b
ON a.company_... | This is your query:
```
SELECT c.code,c.name, a.ltp as begning, b.ltp as enddate, d.interim_cash,d.interim_rec_date,
CAST(((b.ltp - a.ltp) / a.ltp * 100) AS DECIMAL(10, 2)) as chng
FROM eod_stock a JOIN
eod_stock b
ON a.company_id = b.company_id LEFT OUTER JOIN
company AS c
ON c.ID = a.compa... | Mysql three table join results empty set | [
"",
"mysql",
"sql",
"outer-join",
"right-join",
""
] |
Given these entries in a table `table`:
```
user entry
A 1
A 2
A 5
A 6
B 1
B 2
B 3
B 4
B 5
B 6
C 1
C 4
D 1
D 2
D 5
D 6
D 7
D 9
```
And we have a subset `entries_A` to work with, which is the arr... | I think the easiest way to perform this type of query is using aggregation and `having`. Here is an example.
To get A's that have exactly those four elements:
```
select user
from table
group by user
having sum(entry in (1,2,5,6)) > 0 and
count(distinct entry) = 4;
```
To get A's that have those four elements... | This is how I would to your first query (though I think Gordon Linoff's answer is more efficient):
```
select distinct user from so s1
where not exists (
select * from so s2 where s2.entry in (1,2,5,6)
and not exists (
select * from so s3 where s2.entry = s3.entry and s1.user = s3.user
)
)... | What's an easy way to perform this complicated SELECT query? | [
"",
"mysql",
"sql",
"performance",
""
] |
I am trying to group my station codes as shown below however my result set keeps outputting everything and `others` multiple times. I want to group everything by my alias names however for my station `others` it doesn't seem like it is grouping it.
```
WITH
station as (
SELECT
CASE
... | The results you're getting is due to the fact that you have three `t.station` values that get mapped to `Other` The statement `GROUP BY t.station` doesn't care that they get projected to `Other` in your Select.
To fix this you need to group by your case instead of the untranslated value `t.station`
```
GROUP BY
... | This isn't an answer, just a note that you can simplify your case statement a lot:
```
CASE WHEN t.station in ('AB', 'AS', 'KF', 'PR', 'SV', 'RE') THEN t.station
WHEN t.station in ('TVR', 'TDT') THEN 'TDT'
ELSE 'Others'
END
``` | Grouping By Alias names | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have one function that returns all employee IDs
Function definition is like this:
```
CREATE OR REPLACE FUNCTION tmp()
RETURNS setof record AS
$func$
begin
select emp_id from employee_master;
end;
$func$
LANGUAGE plpgsql;
```
But when i call this function using
```
select * from tmp() as abc(emp_id text);
... | If you want to return a rowset from a PL/PgSQL function you must use `RETURN` - in this case, probably `RETURN QUERY`:
```
RETURN QUERY SELECT emp_id FROM employee_master;
```
I don't see the point of having this in a PL/PgSQL function at all, though. | Make the function a [plain SQL](http://www.postgresql.org/docs/current/static/xfunc-sql.html#XFUNC-SQL-FUNCTIONS-RETURNING-SET) one as in:
```
...
LANGUAGE SQL;
``` | Error when calling a function | [
"",
"sql",
"postgresql",
"plpgsql",
"sql-function",
""
] |
I have a table like below
```
Column | Type | Modifiers
------------+--------------------------+-----------
id | integer | not null
number | integer | not null
status | integer |
uid | integer |
val... | This below query should work for you.
```
SELECT id FROM table_name
WHERE (number = 5 AND status = 1 AND uid = 1)
AND NOT (number = 3 AND status = 0 AND uid = 1 AND value = 1)
```
**EDIT :** I think I might have misunderstood your question. The following query will get you ids that have `5| 1| 1 (number| status... | Modifying **user2989408** answer to the below could work.
```
SELECT id FROM table_name
WHERE (id like '%58943' AND number = 5 AND status = 1 AND uid = 1)
AND NOT (number = 3 AND status = 0 AND uid = 1 AND value = 1)
``` | Select that column which don't have certain row | [
"",
"sql",
"database",
"postgresql",
""
] |
I have this table shown below...How do I select only the latest data of the id based on changeno?
```
+----+--------------+------------+--------+
| id | data | changeno | |
+----+--------------+------------+--------+
| 1 | Yes | 1 | |
| 2 | Yes | 2 | |
| 2 | Maybe | 3 | ... | This is typically referred to as the ["greatest-n-per-group"](https://stackoverflow.com/questions/tagged/greatest-n-per-group+sql-server?sort=votes&pageSize=50) problem. One way to solve this in SQL Server 2005 and higher is to use a CTE with a calculated `ROW_NUMBER()` based on the grouping of the `id` column, and sor... | You want to use `row_number()` for this:
```
select id, data, changeno
from (SELECT t.*,
row_number() over (partition by id order by changeno desc) as seqnum
FROM Table1 t
) t
where seqnum = 1;
``` | SELECT only latest record of an ID from given rows | [
"",
"sql",
"sql-server",
""
] |
I have one table in relational database Sybase ASE, with few columns. Three of them looks like this example:
```
_____________
| Product |
---------------
| ProductId |
| Name |
| Quantity |
_____________
```
So we have some records:
```
__________________________________
| ProductId | Name | ... | The correct way to do this is temp table + cursors:
1. create a temp table
2. create [cursor](http://www.sybaseteam.com/sybase-cursors-overview-explanation-and-examples-t-122.html) to iterate through Product table
3. within the cursor, create an inner [WHILE loop](http://www.sqlines.com/sybase/insert_n_rows_commit_aft... | To do this, you need a series of integers. You can generate one manually:
```
select p.name
from product p join
(select 1 as n union all select 2 union all select 3 union all select 4
) n
on n.n <= p.quantity;
```
This will work if `quantity` is not too big and you can put in the values in `n`. | How to select as much records as indicated by the value from database | [
"",
"sql",
"sap-ase",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.